简体   繁体   English

使用扩展的用户模型,如何在同一视图中创建具有两个模型形式的两个模型实例?

[英]Using an extended usermodel, how can I create two model instances with two modelforms in the same view?

First off, I want to say that I am new to django though I understand most of it, forms have always been confusing to me. 首先,我想说我是django的新手,尽管我了解其中的大部分内容,但表格一直让我感到困惑。

I have two models in which I need to create an instance from, the standard built in User model and my own UserProfile model. 我有两个需要从中创建实例的模型,即内置的User模型和我自己的UserProfile模型。

The problem I am facing is that really do not know how to display two forms (one for each model) in the template and on save() then tell django that the newly created UserProfile instance's User = model.ForeignKey belongs to the also newly created User . 我面临的问题是真的不知道如何在模板中和在save()上显示两种形式(每个模型一种),然后告诉django新创建的UserProfile实例的User = model.ForeignKey属于新创建的User

My forms.py is fairly simple: 我的forms.py非常简单:

from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from .models import UserProfile

class UserForm(ModelForm):

    class Meta:
        model = User
        fields = ('username', 'email', 'password')

class  UserProfileForm(ModelForm):

    class Meta:
        model = UserProfile
        fields = ('display_name', 'avatar', 'birthday', 'usertype', 'daw', 'usergenre')

In my views.py I've tried doing this: 在我的views.py中,我尝试这样做:

from .forms import UserForm
from .forms import UserProfileForm

# Create your views here.
def RegisterView(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        form2 = UserProfileForm(request.POST)
        if form.is_valid():
            if form2.is_valid():
                return HttpResponseRedirect('/login/')

    return render(request, 'register.html', {'form': form, 'form2': form})

But when I try to access /register I get this error: http://dpaste.com/19NH2A6 但是,当我尝试访问/register此错误: http : //dpaste.com/19NH2A6

You should use save() method. 您应该使用save()方法。 Next time you have a problem, check the official Django documentation. 下次遇到问题时,请查看官方Django文档。 ModelForms - save() method ModelForms-save()方法

from .forms import UserForm
from .forms import UserProfileForm
from django.http import HttpResponseRedirect


def RegisterView(request):
    if request.method == 'POST':
        form = UserForm(request.POST, prefix='uf')
        form2 = UserProfileForm(request.POST, prefix='upf')
        if form.is_valid():
            if form2.is_valid():
                form.save()
                form2.save()
                return HttpResponseRedirect('/login/')
    elif request.method == 'GET':
        form = UserForm(prefix='uf')
        form2 = UserProfileForm(prefix='upf')            

    return render(request, 'register.html', {'form': form, 'form2': form2})

When you hit /register page from browser, your view gets GET request, you have created form only for POST request 当您从浏览器点击/register页面时,您的视图将获得GET请求,而您仅为POST请求创建了表单

from .forms import UserForm
from .forms import UserProfileForm

# Create your views here.
def RegisterView(request):
    if request.method == 'POST':
        form = UserForm(request.POST, prefix='uf')
        form2 = UserProfileForm(request.POST, prefix='upf')
        if form.is_valid():
            if form2.is_valid():
                return HttpResponseRedirect('/login/')
    elif request.method == 'GET':
        form = UserForm(prefix='uf')
        form2 = UserProfileForm(prefix='upf')            

    return render(request, 'register.html', {'form': form, 'form2': form2})

You should read the traceback yourself so that you can find the error easily. 您应该自己阅读回溯,以便可以轻松找到错误。 It says; 它说;

Exception Type: NameError at /register/ Exception Value: name 'HttpResponseRedirect' is not defined 异常类型:/ register /处的NameError异常值:未定义名称'HttpResponseRedirect'

You've used HttpResponseRedirect but you didn't import it, therefore it is not defined. 您已经使用了HttpResponseRedirect,但没有导入它,因此未定义它。

Add this to top of your code. 将此添加到您的代码的顶部。

from django.http import HttpResponseRedirect

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用modelForms在同一表格中使用两个以上的模型? - How to use more than two models in the same form using modelForms? 同一页面上的两个Django ModelForms,相同模型,没有Formset - Two django ModelForms on the same page, same model, without Formset 您可以在一个模型中创建引用同一模型的两个外键的实例吗? - Can you create instances of two foreign keys referencing the same model in one model? 如何将一个视图中的两个ModelForms与以任意顺序显示的字段组合在一起? - How do I combine two ModelForms in one view with the fields displayed in an arbitrary order? 如何在同一模型中使用两个不同的模型序列化器? - How Can I Use Two Different Model Serializers With the Same Model? 使用相同的模型创建两个不同的表 - Create two different tables using the same model django-使用一种形式创建两个模型实例 - django - Using one form to create two model instances 如何检查 Django 模型的两个实例在一组属性中是否相同并相应地注释查询集? - How do I check if two instances of a Django model are the same across a set of attributes and annotate a queryset accordingly? 如何将两个外键关联到 SQLAlchemy 中同一父 model 的不同实例? - How do I associate two foreign keys to separate instances of the same parent model in SQLAlchemy? 如何在REPL中测试同一类的两个实例是否具有相同的属性? - How can I test in REPL whether two instances of the same class have the same attributes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM