如何在 Django 中向 ModelForm 添加外键字段? [英] How do I add a Foreign Key Field to a ModelForm in Django?

查看:46
本文介绍了如何在 Django 中向 ModelForm 添加外键字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是显示一个表单,让用户:

What I would like to do is to display a single form that lets the user:

  • 输入文档标题(来自 Document 模型)
  • 从下拉列表中选择他们的 user_defined_code 选项之一(由 UserDefinedCode 模型填充)
  • 输入unique_code(存储在Code 模型中)
  • Enter a document title (from Document model)
  • Select one of their user_defined_code choices from a drop down list (populated by the UserDefinedCode model)
  • Type in a unique_code (stored in the Code model)

我不知道如何在表单中显示外键关系的字段.我知道在视图中您可以使用 document.code_set(例如)来访问当前 document 对象的相关对象,但我不确定如何将其应用于 ModelForm.

I'm not sure how to go about displaying the fields for the foreign key relationships in a form. I know in a view you can use document.code_set (for example) to access the related objects for the current document object, but I'm not sure how to apply this to a ModelForm.

我的模型:

class UserDefinedCode(models.Model):
    name = models.CharField(max_length=8)
    owner = models.ForeignKey(User)

class Code(models.Model):
    user_defined_code = models.ForeignKey(UserDefinedCode)
    unique_code = models.CharField(max_length=15)

class Document(models.Model):
    title = models.CharField(blank=True, null=True, max_length=200)
    code = models.ForeignKey(Code)
    active = models.BooleanField(default=True)

我的模型表单

class DocumentForm(ModelForm):
    class Meta:
        model = Document

推荐答案

关于在表单中显示外键字段,您可以使用 forms.ModelChoiceField 并传递一个查询集.

In regards to displaying a foreign key field in a form you can use the forms.ModelChoiceField and pass it a queryset.

所以,forms.py:

so, forms.py:

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user','')
        super(DocumentForm, self).__init__(*args, **kwargs)
        self.fields['user_defined_code']=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user))

views.py:

def someview(request):
    if request.method=='post':
        form=DocumentForm(request.POST, user=request.user)
        if form.is_valid():
            selected_user_defined_code = form.cleaned_data.get('user_defined_code')
            #do stuff here
    else:
        form=DocumentForm(user=request.user)

    context = { 'form':form, }

    return render_to_response('sometemplate.html', context, 
        context_instance=RequestContext(request))

来自您的问题:

我知道在一个视图中你可以使用document.code_set(例如)到访问相关对象当前文档对象,但我不是确定如何将其应用于 ModelForm.

I know in a view you can use document.code_set (for example) to access the related objects for the current document object, but I'm not sure how to apply this to a ModelForm.

实际上,您的 Document 对象不会有 .code_set,因为 FK 关系是在您的文档模型中定义的.它定义了与 Code 的多对一关系,这意味着每个 Code 对象可以有多个 Document 对象,而不是相反.你的 Code 对象会有一个 .document_set.您可以从文档对象中访问与使用 document.code 相关的 Code.

Actually, your Document objects wouldn't have a .code_set since the FK relationship is defined in your documents model. It is defining a many to one relationship to Code, which means there can be many Document objects per Code object, not the other way around. Your Code objects would have a .document_set. What you can do from the document object is access which Code it is related to using document.code.

我认为这会满足您的要求.(未经测试)

edit: I think this will do what you are looking for. (untested)

forms.py:

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        exclude = ('code',)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user','')
        super(DocumentForm, self).__init__(*args, **kwargs)
        self.fields['user_defined_code']=forms.ModelChoiceField(queryset=UserDefinedCode.objects.filter(owner=user))
        self.fields['unique_code']=forms.CharField(max_length=15)

views.py:

def someview(request):
    if request.method=='post':
        form=DocumentForm(request.POST, user=request.user)
        if form.is_valid():
            uniquecode = form.cleaned_data.get('unique_code')
            user_defined_code = form.cleaned_data.get('user_defined_code')
            doc_code = Code(user_defined_code=user_defined_code, code=uniquecode)
            doc_code.save()
            doc = form.save(commit=False)
            doc.code = doc_code
            doc.save()
            return HttpResponse('success')
    else:
        form=DocumentForm(user=request.user)

    context = { 'form':form, }

    return render_to_response('sometemplate.html', context, 
        context_instance=RequestContext(request))

实际上,您可能希望在创建 Code 对象时使用 get_or_create 而不是这个.

actually you probably want to use get_or_create when creating your Code object instead of this.

doc_code = Code(user_defined_code=user_defined_code, code=uniquecode)

这篇关于如何在 Django 中向 ModelForm 添加外键字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆