在django中集成电话号码应用程序

时间:2017-08-07 18:55:06

标签: python django

我是python的初学者。我正在尝试整合我从以下网址安装的phonenumber应用程序

https://github.com/stefanfoulis/django-phonenumber-field

参考网址为Good way to store phone numbers in django models

我已在settings.py。

中的已安装应用中添加了'phonenumber_field'

forms.py代码看起来像这样

from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Field
from ajax_select.fields import AutoCompleteSelectField, AutoCompleteField
from phonenumber_field.modelfields import PhoneNumberField
from . import models

class SignUpForm(forms.Form):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    phone_number = PhoneNumberField()

注册HTML

{% extends "account/base.html" %}

{% load i18n crispy_forms_tags %}

{% block head_title %}{% trans "Signup" %}{% endblock %}

{% block content %}
<h1>{% trans "Sign Up" %}</h1>

<p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p>

<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
  {% csrf_token %}
  {{ form|crispy }}
  {% if redirect_field_value %}
  <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
  {% endif %}
  <button class="btn btn-success" type="submit">{% trans "Sign Up" %} <span class="fa fa-chevron-right"></span></button>
</form>

{% endblock %}

但是在我的注册表单中没有显示电话字段。我必须在模型中调用函数而不是表单。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

您正在导入模型字段,而不是表单字段。

from phonenumber_field.modelfields import PhoneNumberField

模型字段适用于您的模型,而不适用于您的表单。

from phonenumber_field.modelfields import PhoneNumberField

class SignupModel:
    phone_number = PhoneNumberField()

然后,您可以使用ModelForm生成包含与模型相同字段的表单。

但是,如果您坚持手动构建表单,则需要导入表单字段。

from phonenumber_field.formfields import PhoneNumberField

class SignUpForm(forms.Form):
    phone_number = PhoneNumberField()