如何在django的UserCreationForm中包含django-countries软件包?

时间:2019-09-23 03:55:47

标签: python django django-forms country-codes

我已经使用“ pip install django-countries”下载了django-countries软件包,我需要在“ django”项目中使用UserCreationForm的“ Country”字段中包含所有国家的下拉列表。我打算创建国家/地区字段,并允许用户选择带有其国家/地区代码的国家/地区,并使选择字段成为与我的表格中的电话号码字段相关的从属选择字段。我现在面临的唯一问题是我下载了country包,但似乎无法在表格中显示country字段。请告诉我应该对当前代码进行哪些更改。

我写了country = CountryField(),并将国家包括在“字段”列表中。但是,当我运行服务器时,发生错误,指出为用户指定的未知字段(国家/地区)。

/* views.py */
import phonenumbers
from phonenumbers import carrier
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django_countries.fields import CountryField
from validate_email import validate_email
# from phonenumber_field.formfields import PhoneNumberField


class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    # phone_number = PhoneNumberField()
    phone_number = forms.CharField(max_length=100)
    country = CountryField()

    class Meta:
        model = User
        fields = ['username', 'email', 'phone_number', 'country']

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if not validate_email(email, verify=True):
            raise forms.ValidationError("Invalid email")
        return email

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get("phone_number")
        z = phonenumbers.parse(phone_number, "SG")
        if not phonenumbers.is_valid_number(z):
        raise forms.ValidationError("Number not in SG format")
        if carrier.name_for_number(z, "en") == '':
        raise forms.ValidationError("Please enter a mobile number")
        return phonenumbers.format_number(
            z, phonenumbers.PhoneNumberFormat.E164)

    '''def clean_country(self):
        return country'''

/* 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():
            # user = form.save()
            # phone_number = form.cleaned_data['phone']
            # do something with phone number??
            user = form.save()
            user.refresh_from_db()
            phone = form.cleaned_data.get('phone_number')
            user.Meta.phone_number = phone
            user.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})

我希望我的Django的UserCreationForm包含国家/地区字段,其中包含所有国家/地区以及国家/地区代码。例如,选项之一可以是“ US +1”。

0 个答案:

没有答案