如何扩展django UserCreationForm模型以包括电话号码字段

时间:2019-09-13 07:00:26

标签: python django django-registration

我似乎在这里找不到有关扩展Django UserCreationForm模型以包含电话号码字段的信息,以便用户输入其电话号码,然后在后端使用phonenumbers.parse验证电话号码以检查电话号码是否在各自的格式以及是否存在。我需要知道应该在“用户”应用下的form.py中包含哪些代码。

我尝试为电话号码包含普通的html文本字段,它不属于Django中默认的UserCreationForm模型,也不能存储在数据库中。 (我需要将其存储在数据库中以获取电话号码)。我只使用forms.py,views.py和register.html来在视图中呈现,如下所示,当前我没有使用models.py。

/* forms.py */ 

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


class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    phone_number = forms.IntegerField(required=True)

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

        def save(self, commit=True):
            user = super(UserCreationForm, self).save(commit=False)
            user.email = self.cleaned_data['email']

            if commit:
                user.save()

            return user

/* views.py */
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm


def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('blog-home')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

/* register.html */
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="content-section">
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Join Today</legend>
                {{ form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Sign 
Up</button>
            </div>
        </form>
        <div class="border-top pt-3">
            <small class="text-muted">
                ALready Have An Account? <a class="ml-2" href="#">Sign In</a>
            </small>
        </div>
    </div>
{% endblock content %}

我需要在Django中将电话号码字段作为UserCreationForm的一部分,并验证该号码以检查其是否存在,然后将其保存在数据库中。

1 个答案:

答案 0 :(得分:0)

我通常使用OneToOneLink扩展Django用户模型

models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=11, blank=True) #  change the field to watever works for you


#  This will auto create a profile of user with blank phone number that can be updated later.
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

forms.py

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('phone')

views.py

def create_user(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.user_profle)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, _('New user created successfully'))
            return redirect('settings:profile')
        else:
            messages.error(request, _('Please correct the error below.'))
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.user_profile)
    return render(request, 'template_name.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

模板:

<form method="post">
  {% csrf_token %}
  {{ user_form.as_p }}
  {{ profile_form.as_p }}
  <button type="submit">Save changes</button>
</form>