简体   繁体   English

如何使用UserCreationForm Django向数据库添加额外的字段数据?

[英]How add extra fields data to database with UserCreationForm Django?

I'm trying to add data from UserCreationForm extra fields to database, i want to add multiple fields to UserCreationForm and save it to database. 我正在尝试将UserCreationForm额外字段中的数据添加到数据库中,我想将多个字段添加到UserCreationForm中并将其保存到数据库中。 I saw other examples from topics here in stackoverflow, but it doesn't work. 我在stackoverflow中看到了主题的其他示例,但是它不起作用。

Here is a example of my code: ( fields: "agree_terms" or "price" could be anything else) 这是我的代码示例:(字段:“ agree_terms”或“ price”可以是其他任何内容)

forms.py forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm



class UserRegisterForm(UserCreationForm):
    email = forms.EmailField(widget = forms.EmailInput(attrs= 
                                               {'placeholder':'Email'}))
    agree_terms = forms.BooleanField()
    price = forms.DecimalField(decimal_places=2, max_digits=10000)

    class Meta(UserCreationForm.Meta):
        model = User

        fields = UserCreationForm.Meta.fields + ('username', 'password1', 
                                'email','password2','agree_terms','price')

views.py views.py

@csrf_protect
def registers(request):

    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        print(form)
        print(form.is_valid())
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request,'Conta criada {}'.format(username))
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request,'header-login.html',{'form':form})

Did you also changed your User model to support those fields? 您是否还更改了User模型以支持这些字段? You'd need to add them to the model/table as well. 您还需要将它们添加到模型/表中。

Although, I wouldn't recommend piling up so much extra data directly on the User model. 虽然,我不建议直接在User模型上堆积太多额外的数据。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM