django 模型表单.包括来自相关模型的字段 [英] django model Form. Include fields from related models

查看:32
本文介绍了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/

提前致谢.

推荐答案

一个常见的做法是使用 2 个表单来实现您的目标.

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

  • Student 模型的表格:

    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天全站免登陆