Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 288
user1216674 Avatar asked Feb 17 '12 16:02

user1216674


2 Answers

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.

like image 175
Alasdair Avatar answered Sep 21 '22 17:09

Alasdair


Try:

if request.method == 'POST':
    data = request.POST
    data['user'] = request.user
    form = JobForm(data, request.FILES)
    if form.is_valid():
        #Do something here
like image 44
Chris Pratt Avatar answered Sep 18 '22 17:09

Chris Pratt