In Django, how do you pass a ForeignKey into an instance of a Model?

后端 未结 2 1531
夕颜
夕颜 2020-12-06 07:59

I am writing an application which stores \"Jobs\". They are defined as having a ForeignKey linked to a \"User\". I don\'t understand how to pass the ForeignKey into the mode

相关标签:
2条回答
  • 2020-12-06 08:17

    A typical pattern in Django is:

    1. exclude the user field from the model form
    2. save the form with commit=False
    3. set job.user
    4. save to database

    In your case:

    class JobForm(forms.ModelForm):
        class Meta:
            model = Job
            exclude = ('user',)
    
    if request.method == 'POST':
        form = JobForm(request.POST, request.FILES)
        job = form.save(commit=False)
        job.user = request.user
        job.save()
        # the next line isn't necessary here, because we don't have any m2m fields
        form.save_m2m()
    

    See the Django docs on the model form save() method for more information.

    0 讨论(0)
  • 2020-12-06 08:36

    Try:

    if request.method == 'POST':
        data = request.POST
        data['user'] = request.user
        form = JobForm(data, request.FILES)
        if form.is_valid():
            #Do something here
    
    0 讨论(0)
提交回复
热议问题