在Django中,如何将ForeignKey传递给Model的实例?

时间:2012-02-17 16:34:35

标签: django django-models django-forms django-users

我正在编写一个存储“Jobs”的应用程序。它们被定义为具有链接到“用户”的ForeignKey。我不明白在创建它时如何将ForeignKey传递给模型。我的Model for Job在没有ForeignKey的情况下运行良好,但是现在我正在尝试将用户添加到系统中,我无法获得要验证的表单。

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

在views.py中,我按如下方式创建了对象:

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

据我所知,这会将表单数据和上传的文件传递给表单。但是,我不明白如何传入用户设置为ForeignKey。

提前感谢任何可以提供帮助的人。

2 个答案:

答案 0 :(得分:7)

Django中的典型模式是:

  1. 从模型表单中排除user字段
  2. 使用commit=False
  3. 保存表单
  4. 设置job.user
  5. 保存到数据库
  6. 在你的情况下:

    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()
    

    有关详细信息,请参阅model form save() method上的Django文档。

答案 1 :(得分:1)

尝试:

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