我正在创建一个使用django-userena的基本django网站。我通过在forms.py上创建EditProfileFormExtra类来覆盖默认注册表单。但是,我发现了一个非常奇怪的问题。 “纬度”和“经度”字段不会显示。更改字段的名称似乎使它们显示出来,但是将它们命名为“lat”或“latitude”和“long”或“longitude”会让它们消失?!这是为什么?
from django import forms
from django.utils.translation import ugettext_lazy as _
from userena.forms import SignupForm
from userena.forms import EditProfileForm
from Couches.models import Location
from django.core.validators import RegexValidator
# Code adapted from: http://django-userena.readthedocs.org/en/latest/faq.html#how-do-i-add-extra-fields-to-forms
class SignupFormExtra(SignupForm):
first_name = forms.CharField(label=_(u'First name'),
max_length=30,
required=True)
last_name = forms.CharField(label=_(u'Last name'),
max_length=30,
required=True)
latitude = forms.CharField(label=_(u'Latitude'),
max_length=30,
required=False,
validators=[RegexValidator(regex='^[-+]?[0-9]*\.?[0-9]+$'),])
longitude = forms.CharField(label=_(u'Longitude'),
max_length=30,
required=False,
validators=[RegexValidator(regex='^[-+]?[0-9]*\.?[0-9]+$'),])
def save(self):
# First save the parent form and get the user.
new_user = super(SignupFormExtra, self).save()
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
new_user.save()
Location.objects.create(available=True,
user=new_user,
latitude=self.cleaned_data['latitude'],
longitude=self.cleaned_data['longitude'])
return new_user
class EditProfileFormExtra(EditProfileForm):
description = forms.CharField(label=_(u'Description'),
max_length=300,
required=False,
widget=forms.Textarea)
contact_information = forms.CharField(label=_(u'Contact Information'),
max_length=300,
required=False,
widget=forms.Textarea)
graduation_year = forms.CharField(label=_(u'Graduation Year'),
max_length=4,
required=False,
validators=[RegexValidator(regex='^\d{4}$'), ])
address = forms.CharField(label=_(u'Contact Information'),
max_length=100,
required=False)
# BUG: the two fields below do not appear on the form
latitude = forms.CharField(label=_(u'Latitude'),
max_length=30,
required=False,
validators=[RegexValidator(regex='^[-+]?[0-9]*\.?[0-9]+$'), ])
longitude = forms.CharField(label=_(u'lon'),
max_length=30,
required=False,
validators=[RegexValidator(regex='^[-+]?[0-9]*\.?[0-9]+$'), ])
def save(self, force_insert=False, force_update=False, commit=True):
profile = super(EditProfileFormExtra, self).save()
profile.description = self.cleaned_data['description']
profile.contact_information = self.cleaned_data['contact_information']
profile.graduation_year = self.cleaned_data['graduation_year']
location = Location.objects.get(user = profile.user)
if(location):
location.latitude = self.cleaned_data['latitude']
location.longitude = self.cleaned_data['longitude']
location.save()
return profile
这是显示表单的模板:
{% extends 'base.html' %}
{% load i18n %}
{% load url from future %}
{% block title %}{% trans "Account setup" %}{% endblock %}
{% block content_title %}<h2>{% blocktrans with profile.user.username as username %}Account » {{ username }}{% endblocktrans %}</h2>{% endblock %}
{% block content %}
Edit your very own profile.
<form action="" enctype="multipart/form-data" method="post">
<ul id="box-nav">
<li class="first"><a href="{% url 'userena_profile_detail' user.username %}"><span>{% trans 'View profile' %}</span></a></li>
<li class="selected"><a href="{% url 'userena_profile_edit' user.username %}">{% trans "Edit profile" %}</a></li>
<li><a href="{% url 'userena_password_change' user.username %}">{% trans "Change password" %}</a></li>
<li class="last"><a href="{% url 'userena_email_change' user.username %}">{% trans "Change email" %}</a></li>
</ul>
{% csrf_token %}
<fieldset>
<legend>{% trans "Edit Profile" %}</legend>
{{ form.as_p }}
</fieldset>
<input type="submit" value="{% trans "Save changes" %}" />
</form>
{% endblock %}
以下是模型:
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
from django.core.validators import RegexValidator
class UserProfile(UserenaBaseProfile):
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='my_profile')
first_name = models.TextField()
last_name = models.TextField()
description = models.CharField(max_length=300, blank=True)
contact_information = models.CharField(max_length=300, blank=True) # extra contact information that the user wishes to include
graduation_year = models.CharField(max_length=300, blank=True)
address = models.CharField(max_length=100, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Location(models.Model):
user = models.ForeignKey(User)
available = models.BooleanField(default=True) # Is this location available to couchsurf
latitude = models.CharField(max_length=30, validators=[RegexValidator(regex='^[-+]?[0-9]*\.?[0-9]+$'),]) # floating point validator
longitude = models.CharField(max_length=30, validators=[RegexValidator(regex='^[-+]?[0-9]*\.?[0-9]+$'),]) # floating point validator
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
这是来自django-userena(https://github.com/bread-and-pepper/django-userena/blob/master/userena/views.py)
的视图Adef profile_edit(request, username, edit_profile_form=EditProfileForm,
template_name='userena/profile_form.html', success_url=None,
extra_context=None, **kwargs):
"""
Edit profile.
Edits a profile selected by the supplied username. First checks
permissions if the user is allowed to edit this profile, if denied will
show a 404. When the profile is successfully edited will redirect to
``success_url``.
:param username:
Username of the user which profile should be edited.
:param edit_profile_form:
Form that is used to edit the profile. The :func:`EditProfileForm.save`
method of this form will be called when the form
:func:`EditProfileForm.is_valid`. Defaults to :class:`EditProfileForm`
from userena.
:param template_name:
String of the template that is used to render this view. Defaults to
``userena/edit_profile_form.html``.
:param success_url:
Named URL which will be passed on to a django ``reverse`` function after
the form is successfully saved. Defaults to the ``userena_detail`` url.
:param extra_context:
Dictionary containing variables that are passed on to the
``template_name`` template. ``form`` key will always be the form used
to edit the profile, and the ``profile`` key is always the edited
profile.
**Context**
``form``
Form that is used to alter the profile.
``profile``
Instance of the ``Profile`` that is edited.
"""
user = get_object_or_404(get_user_model(),
username__iexact=username)
profile = user.get_profile()
user_initial = {'first_name': user.first_name,
'last_name': user.last_name}
form = edit_profile_form(instance=profile, initial=user_initial)
if request.method == 'POST':
form = edit_profile_form(request.POST, request.FILES, instance=profile,
initial=user_initial)
if form.is_valid():
profile = form.save()
if userena_settings.USERENA_USE_MESSAGES:
messages.success(request, _('Your profile has been updated.'),
fail_silently=True)
if success_url:
# Send a signal that the profile has changed
userena_signals.profile_change.send(sender=None,
user=user)
redirect_to = success_url
else: redirect_to = reverse('userena_profile_detail', kwargs={'username': username})
return redirect(redirect_to)
if not extra_context: extra_context = dict()
extra_context['form'] = form
extra_context['profile'] = profile
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request)