简体   繁体   English

如何在 Django 注册表单中添加额外的字段?

[英]How to add extra fields to django registration form?

I have a registration form which generates in view.我有一个在视图中生成的注册表单。 Now I need to add some fields from other model.现在我需要从其他模型中添加一些字段。 How should I change view to add fields from another model?我应该如何更改视图以从另一个模型添加字段?

Here is my view code:这是我的视图代码:

def register(request):
    """ User registration """
    if auth.get_user(request).username:
        return redirect('/')

    context = {}
    context.update(csrf(request))
    context['form'] = UserCreationForm()
    if request.POST:
        newuser_form = UserCreationForm(request.POST)
        if newuser_form.is_valid():
            newuser_form.save()
            newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],
                                    password=newuser_form.cleaned_data['password2'])
        auth.login(request, newuser)
        return redirect('/')
        else:
            context['form'] = newuser_form

    return render(request, 'user_auth/user_auth_register.html', context)

Something like this should help you:像这样的东西应该可以帮助你:

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

class UserCreateForm(UserCreationForm):
    extra_field = forms.CharField(required=True)

    class Meta:
        model = User
        fields = ("username", "extra_field", "password1", "password2")

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.extra_field = self.cleaned_data["extra_field"]
        if commit:
            user.save()
        return user

Basically, extending UserCreationForm and adding an extra field.基本上,扩展UserCreationForm并添加一个额外的字段。 Also, save it in the save() method.此外,将其保存在save()方法中。

Hope it helps.希望它有帮助。

By default the UserCreationForm comes with username, password, first_name, last_name, email.默认情况下,UserCreationForm 带有用户名、密码、名字、姓氏、电子邮件。

I wanted to add additional fields of information (easily accomplished after the fact using the ProfileUpdateForm) but I wanted it included in the initial registration form so the user would only have to submit once.我想添加其他信息字段(事后使用 ProfileUpdateForm 很容易完成),但我希望它包含在初始注册表中,这样用户只需提交一次。

Solution is to use two forms and combine them.解决方案是使用两种形式并将它们组合起来。 The magic trick is to initiate a manual database refresh to access the newly created profile魔术是启动手动数据库刷新以访问新创建的配置文件

Reference: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html参考: https : //simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

views.py视图.py

def register(request):
if request.method == 'POST':
    form = UserRegisterForm(request.POST)
    p_reg_form = ProfileRegisterForm(request.POST)
    if form.is_valid() and p_reg_form.is_valid():
        user = form.save()
        user.refresh_from_db()  # load the profile instance created by the signal
        p_reg_form = ProfileRegisterForm(request.POST, instance=user.profile)
        p_reg_form.full_clean()
        p_reg_form.save()
        messages.success(request, f'Your account has been sent for approval!')
        return redirect('login')
else:
    form = UserRegisterForm()
    p_reg_form = ProfileRegisterForm()
context = {
    'form': form,
    'p_reg_form': p_reg_form
}
return render(request, 'users/register.html', context)

forms.py表格.py

class UserRegisterForm(UserCreationForm):
email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class ProfileRegisterForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['city', 'state', 'country', 'referral']

models.py模型.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    confirmed = models.BooleanField("Confirmed", default=False)

    city = models.CharField("City", max_length=50, blank=True)
    state = models.CharField("State", max_length=50, blank=True)
    country = models.CharField("Country", max_length=50, blank=True)
    referral = models.CharField("Referral", max_length=50, blank=True)

def __str__(self):
    return f'{self.user.username} Profile'

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

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

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