Django,外键没有填充会话数据

Django, Foreign key not getting filled with session data

我试图用登录的用户填充我的外键(雇主),但我已经看到了很多方法,但它们对我没有用,有人知道我做错了什么吗?我该如何解决?

查看:

class JobCreate(CreateView):
    model = Job
    form = JobCreateForm()
    form_class = JobCreateForm
    context = {}
    success_url = reverse_lazy('jobsview')

    def POST(self,request):
        if request.method == 'POST':
            form = JobCreateForm(request.POST)
            if form.is_valid():
                job = form.save(commit=False)
                job.employer = request.user
                job.save()
                context = {}
                return render(request, 'jobs/jobs.html',context)
            else:
                context = {}
                return render(request, 'jobs/job_form.html',context)

型号:

class Job(models.Model):
    employer = models.ForeignKey(User, related_name='employer', on_delete=CASCADE,blank=True)
    employees = models.ManyToManyField(User, related_name='employees2user',null=True,blank=True)
    title = models.CharField(max_length=200,)
    description = models.CharField(max_length=200,null=True,blank=True)
    category_id = models.ManyToManyField(Category,blank=True)
    skill_id = models.ManyToManyField(Skill,blank=True)
    approved = models.BooleanField(default=False)
    # img = models.ImageField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)


def __str__(self):          # Default value
    return self.title

HTML:

{% extends "jobs/layout.html" %}

{% block content %}
<h3> Job</h3>
<div class="container">
    <div class="jobform">
        <form action="" method="POST">
            {%csrf_token%}
            {% for field in form %}
                <label for="{{field.id_for_label}}">{{field.html_name}}</label>
                {{field}}
            {% endfor %}
            <p>Ctrl in houden om meerder te selecteren</p>
            <button type="submit" class="btn btn-dark btn-space">Submit</button>
        </form>
    </div>
</div>
{%endblock%}

在您的视图方法中,尝试替换

job = form.save(commit=False)
job.employer = request.user
job.save()

self.object = form.save(commit=False)
self.object.employer = self.request.user
self.object.save()

此外,上下文 {} 的用途是什么?

能不能直接把它放在 form_valid 方法里?这样就干净多了。

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.employer = self.request.user
        self.object.save()
        return super(JobCreate, self).form_valid(form)