简体   繁体   English

如何在 Django 的 UserCreationForm 中扩展字段?

[英]How to extend field in UserCreationForm in django?

I have been trying to add a phone number field in UserCreationForm so that on registration a user gives its phone number but unfortunately phone number is not storing.我一直在尝试在 UserCreationForm 中添加电话号码字段,以便在注册时用户提供其电话号码,但不幸的是电话号码未存储。 it accepts the Phone number on the registration page but it doesn't show the phone number on the webpage.它接受注册页面上的电话号码,但不显示网页上的电话号码。 I think it is not storing.我认为它不是存储。

forms.py表格.py

class myCreateForm(UserCreationForm):
ph= forms.CharField(max_length=400, required=True, label='Phone')
class Meta:
    model = User
    fields = ['first_name', 'last_name' ,'username', 'email', 'password1', 'password2','ph']

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

views.py视图.py

def register(request):
form = myCreateForm()
if request.method == "POST":
    form = myCreateForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('loginPage')
return render(request , 'register.html', {'form' : form})

template模板

{%for i in user%}
Hi {{i.first_name}}<br>
Username : {{i.username}}<br>
E-Mail : {{i.email}}<br>
Phone : {{i.ph}}<br>
{%endfor%}

but on my webpage, it shows everything except phone number.但是在我的网页上,它显示了除电话号码之外的所有内容。

Please Help Me Out请帮帮我

You need to extend the Django User model.See the Docs .您需要扩展 Django 用户模型。请参阅文档

For example let's create a new model Profile which will have OneToOne relation with django user model例如,让我们创建一个新的模型Profile ,它将与 django 用户模型具有OneToOne关系

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=50..)

Now in your view现在在你看来

form = myCreateForm(request.POST)
    if form.is_valid():
        user = form.save()
        phone = form.cleaned_data.get('ph')
        Profile.objects.create(user=user,phone=ph)
        return redirect...

Now in the template {{i.profile.phone}} will give the result for phone field.现在在模板中{{i.profile.phone}}将给出电话字段的结果。

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

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