gpt4 book ai didi

python - 在 Django 中扩展表单?

转载 作者:行者123 更新时间:2023-11-28 20:51:30 24 4
gpt4 key购买 nike

我最近尝试使用以下内容扩展 django 的注册表单,但我只能看到默认的四个字段。有什么我想念的吗?

或者如果我要创建自定义表单,我应该创建自己的注册后端吗?

class RegistrationForm(forms.Form):

username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(attrs=attrs_dict),
label=_(u'Username'))
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_(u'Email address'))
first_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'First Name'))
last_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'Last Name'))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_(u'Password'))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_(u'Password (again)'))
keywords = forms.ModelMultipleChoiceField(queryset=Keyword.objects.all())
#keywords = forms.ModelChoiceField(queryset=Keyword.objects.all())

def clean_username(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_(u'This username is already taken. Please choose another.'))

def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_(u'You must type the same password each time'))
return self.cleaned_data

def save(self, profile_callback=None):
new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],password=self.cleaned_data['password1'],email=self.cleaned_data['email'],profile_callback=profile_callback)
new_profile = UserProfile(user=new_user,username=self.cleaned_data['username'], keywords_subscribed=self.cleaned_data['keywords'],first_name=self.cleaned_data['first_name'],last_name=self.cleaned_data['last_name'],email=self.cleaned_data['email'])
new_profile.save()
return new_user

添加模板代码:

添加模板代码供引用。

引用自注册模块中的forms.py

<html>
<body>
<div id="popupLayer_login" style="visibility: visible; position: fixed;">
<div id="content-home" style="width: 700px; margin-left: -300px; top: 60px; position: fixed;">
<br />
{% block title %}<h2 style="margin: 0px; margin-bottom: 20px; text-align: center">Register for an account</h2>{% endblock %}
{% block content %}
<table style="margin-left: 100px; width: 500px;">
<tbody>
<form method='post' action=''>
{% csrf_token %}
{{ form }}
<tr>
<td style="border-width: 0px;"></td>
<td style="border-width: 0px;">
<input type="submit" value="Send activation email" />
</td>
</tr>
</form>
</tbody>
</table>
{% endblock %}
</div>
</div>
</body>
</html>

这是我的 urls.py

urlpatterns = patterns('',
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get to the view;
# that way it can return a sensible "invalid key" message instead of a
# confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
activate,
name='registration_activate'),
url(r'^login/$',
auth_views.login,
{'template_name': 'registration/login.html'},
name='auth_login'),
url(r'^logout/$',
auth_views.logout,
{'template_name': 'registration/logout.html'},
name='auth_logout'),
url(r'^password/change/$',
auth_views.password_change,
name='auth_password_change'),
url(r'^password/change/done/$',
auth_views.password_change_done,
name='auth_password_change_done'),
url(r'^password/reset/$',
auth_views.password_reset,
name='auth_password_reset'),
url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
auth_views.password_reset_confirm,
name='auth_password_reset_confirm'),
url(r'^password/reset/complete/$',
auth_views.password_reset_complete,
name='auth_password_reset_complete'),
url(r'^password/reset/done/$',
auth_views.password_reset_done,
name='auth_password_reset_done'),
url(r'^register/$',
register,
name='registration_register'),
url(r'^register/complete/$',
direct_to_template,
{'template': 'registration/registration_complete.html'},
name='registration_complete'),
)

和我的views.py

def register(request, success_url=None,
form_class=RegistrationForm, profile_callback=None,
template_name='registration/registration_form.html',
extra_context=None):
if request.method == 'POST':
form = form_class(data=request.POST, files=request.FILES)
if form.is_valid():
new_user = form.save(profile_callback=profile_callback)
# success_url needs to be dynamically generated here; setting a
# a default value using reverse() will cause circular-import
# problems with the default URLConf for this application, which
# imports this file.
return HttpResponseRedirect(success_url or reverse('registration_complete'))
else:
form = form_class()

if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{ 'form': form },
context_instance=context)

最佳答案

实际上,您不应该修改外部应用程序的代码,除非您有充分的理由这样做——显然这种情况没有。因为这称为 fork 并且需要更多维护:他们进行更新,您必须反射(reflect)更新。

您应该始终尝试在不修改其代码的情况下重用外部应用。在这种情况下,完全可以在不触及他们的代码的情况下扩展注册表单。也就是说,它需要一点巫术。请注意,这适用于任何理智的应用程序:

  1. 检查 View 签名中的 form_class 参数,有问题的 View 有这样一个签名:request(request, success_url=None, form_class=RegistrationForm, profile_callback=None , template_name='registration/registration_form.html', extra_context=None)。这非常棒,这意味着您可以通过不同的成功 URL、配置文件回调、模板、额外的上下文以及最重要的在您的案例中重用 View :form_class。

  2. 继承表单,创建另一个继承自RegistrationForm的表单

  3. 覆盖传递表单类的 URL,创建另一个传递表单类的 url

在您的项目目录中创建一个 forms.py:

from django import forms

from registration.forms import RegistrationForm

class ProjectSpecificRegistrationForm(RegistrationForm):
keywords = forms.ModelMultipleChoiceField(queryset=Keyword.objects.all())
first_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'First Name'))
last_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'Last Name'))

然后,在您的 urls.py 中,您应该有如下内容:

urlpatterns = patterns('',
url(r'registration/', include('registration.urls'),
)

用绝对路径 /registration/register/ 覆盖名为“registration_register”的 url,如下所示:

import forms

urlpatterns = patterns('',
url(r'^registration/register/$', 'views.registration.register', {
'form_class': forms.ProjectSpecificRegistrationForm}, 'registration_register'),
url(r'^registration/', include('registration.urls'),
)

这是怎么回事

url() function有这样一个签名:url(regex, view, kwargs=None, name=None, prefix='')。在上面的定义中,我们将带有 form_class 的字典传递给 kwargs。因此,将使用 form_class=您的表单类调用该 View 。这真的很有趣,因为您还可以添加额外的上下文,例如:

    url(r'^registration/register/$', 'views.registration.register', {
'form_class': forms.ProjectSpecificRegistrationForm,
# provided that you imported SomeModel
'extra_context': {'models': SomeModel.objects.all()}}, 'registration_register'),

无论如何,下次您打开 /registration/register/ 时,它将使用您的 url,它会传递您的表单类。

请注意,您还可以创建一个类似 project_specific 的应用程序,您可以在其中放置真正特定于您的项目且没有理由重复使用的所有代码。

关于python - 在 Django 中扩展表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9544579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com