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

2

6

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 model when creating it. My Model for Job worked fine without a ForeignKey, but now that I am trying to add users to the system I can't get the form to validate.

models.py:

from django.db import models
from django import forms
from django.contrib.auth.models import User

class Job(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=50, blank=True)
    pub_date = models.DateTimeField('date published', auto_now_add=True)
    orig_image = models.ImageField('uploaded image', upload_to='origImageDB/', blank=True)
    clean_image = models.ImageField('clean image', upload_to='cleanImageDB/', blank=True)
    fullsize_image = models.ImageField('fullsize image', upload_to='fullsizeImageDB/')
    fullsize_clean_image = models.ImageField('fullsize clean image', upload_to='fullsizeCleanImageDB/')
    regions = models.TextField(blank=True)
    orig_regions = models.TextField(blank=True)

class JobForm(forms.ModelForm):
    class Meta:
        model = Job

In views.py I was creating the objects as follows:

if request.method == 'POST':
    form = JobForm(request.POST, request.FILES)
    if form.is_valid():
        #Do something here

I understand that this passes the form data and the uploaded files to the form. However, I don't understand how to pass in a User to be set as the ForeignKey.

Thanks in advance to anyone who can help.

Cirro answered 17/2, 2012 at 16:34 Comment(0)
T
7

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.

Tyrolienne answered 17/2, 2012 at 17:13 Comment(1)
Didn't realize the ModelForm save() function returned an instance of the model class specified in the form's Meta class model attribute. Thanks for this!Elude
H
1

Try:

if request.method == 'POST':
    data = request.POST
    data['user'] = request.user
    form = JobForm(data, request.FILES)
    if form.is_valid():
        #Do something here
Hagar answered 17/2, 2012 at 16:43 Comment(3)
This works fine except 'request.user' should be 'request.user.id'. Thank you.Cirro
@Cirro Actually in Django 1.6.1 request.user works fineElude
request.POST is immutableXenophon

© 2022 - 2024 — McMap. All rights reserved.