django模型表格。包括相关模型中的字段 [英] django model Form. Include fields from related models

查看:74
本文介绍了django模型表格。包括相关模型中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Student的模型,该模型具有一些字段,并且与用户(django.contrib.auth.User)具有OneToOne关系。

I have a model, called Student, which has some fields, and a OneToOne relationship with a user (django.contrib.auth.User).

class Student(models.Model):

    phone = models.CharField(max_length = 25 )
    birthdate = models.DateField(null=True) 
    gender = models.CharField(max_length=1,choices = GENDER_CHOICES) 
    city = models.CharField(max_length = 50)
    personalInfo = models.TextField()
    user = models.OneToOneField(User,unique=True)

然后,我有用于该模型的ModelForm

Then, I have a ModelForm for that model

class StudentForm (forms.ModelForm):
    class Meta:
        model = Student

使用类Meta中的fields属性,我设法仅显示模板中的某些字段。但是,我可以指出要显示哪些用户字段吗?

Using the fields attribute in class Meta, I've managed to show only some fields in a template. However, can I indicate which user fields to show?

类似的内容:

   fields =('personalInfo','user.username')

当前未显示任何内容。不过,仅适用于StudentFields。

is currently not showing anything. Works with only StudentFields though/

预先感谢。

推荐答案

一种常见的做法是使用两种形式来实现您的目标。

A common practice is to use 2 forms to achieve your goal.


  • User 模型:

class UserForm(forms.ModelForm):
    ... Do stuff if necessary ...
    class Meta:
        model = User
        fields = ('the_fields', 'you_want')


  • 学生模型的表格:

    class StudentForm (forms.ModelForm):
        ... Do other stuff if necessary ...
        class Meta:
            model = Student
            fields = ('the_fields', 'you_want')
    


  • 在视图中使用这两种形式(用法示例):

  • Use both those forms in your view (example of usage):

    def register(request):
        if request.method == 'POST':
            user_form = UserForm(request.POST)
            student_form = StudentForm(request.POST)
            if user_form.is_valid() and student_form.is_valid():
                user_form.save()
                student_form.save()
    


  • 在模板中一起渲染表单:

  • Render the forms together in your template:

    <form action="." method="post">
        {% csrf_token %}
        {{ user_form.as_p }}
        {{ student_form.as_p }}
        <input type="submit" value="Submit">
    </form>
    


  • 另一种选择是让您将关系从 OneToOne 更改为 ForeignKey (这完全取决于您和我只需提及它,不推荐它)并使用 inline_formsets 即可达到预期效果。

    Another option would be for you to change the relationship from OneToOne to ForeignKey (this completely depends on you and I just mention it, not recommend it) and use the inline_formsets to achieve the desired outcome.

    这篇关于django模型表格。包括相关模型中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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