如何使Django用户注册一步(而不是两步)进程与电子邮件强制? [英] How can I have Django user registration single step (instead of two step)process with email compulsory?
问题描述
我希望Django通过登录详细信息向用户电子邮件地址发送电子邮件,一旦admin添加了一个新的用户到管理站点。所以我尝试使用Django信号,但只是becoz django用户注册是一个两步过程信号获得通知仅在第一步,并且没有电子邮件地址(即第二步)的电子邮件功能。
我的信号代码:
I want Django to send an email to user email-address with Login details once admin adds a new user to admin site.So I tried using Django signals for that but just becoz django user registration is a two step process signals get notified in first step only and called email function without email address(which comes in second step). My signal code:
def email_new_user(sender, **kwargs):
if kwargs["created"]: # only for new users
new_user = kwargs["instance"]
send_mail('Subject here', 'Here is the message.', 'from@example.com',['to@example.com'], fail_silently=False)
post_save.connect(email_new_user, sender=User)
所以我试图克服这个问题。我在admin.py中使用这个代码
So what i tried to overcome this problem.I use this code in admin.py
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login')
search_fields = ['username', 'email']
filter_horizontal = ('user_permissions',)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
这使得所有注册过程都是单步进程,我的信号开始工作并发送m ail到user_id新用户添加。但是问题出现在这之后:
This makes all registration process a single step process and my signals start working and sending mail to user_id on new user addition.But the problem came after this were:
1。用户密码不会转换成哈希,并且在输入表单时可见,这使得用户无法登录到管理站点。
2。
2.Email field in form is not compulsory which I want to be compulsory.
请帮助我:(
I tried your code But I m still at same place where i was before posting this question.
the code i used in my admin.py is:
from django.contrib import admin
from mysite.naturefarms.models import *
from django.contrib.auth.models import User,Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.contrib.admin.views.main import *
class MyUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
class UserAdmin(admin.ModelAdmin):
add_form = MyUserCreationForm
admin.site.unregister(User)
class MyUserAdmin(UserAdmin):
add_form = MyUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
admin.site.register(User, MyUserAdmin)
推荐答案
如果你看看django.contrib.auth admin.py,你会看到UserAdmin类指定了add_form作为UserCreationForm。
If you look in django.contrib.auth admin.py, you'll see that the UserAdmin class specifies the add_form as UserCreationForm.
UserCreationForm只包含username字段用户模型。
UserCreationForm only includes the 'username' field from the User model.
由于您提供自己的UserAdmin,您可以覆盖一个自定义UserCreationForm的add_form,其中包含您需要使信号正常工作的字段。
Since you're providing your own UserAdmin, you can just override the add_form to a custom UserCreationForm that includes the fields you need to make your signal work properly.
希望能帮助您。
这是来自contrib.auth forms.py的UserCreationForm:
Here's the UserCreationForm from contrib.auth forms.py:
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and password.
"""
username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
help_text = _("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ("username",)
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_("A user with that username already exists."))
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
通知fields =(username)元组,排除用户模型上的所有其他字段。你需要这样的东西:
Notice the fields = ("username",) tuple which excludes all other fields on the User model. You need something like:
class MyUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
那么你可以使用它您的自定义UserAdmin中的add_form:
then you can use that as the add_form in your custom UserAdmin:
class UserAdmin(admin.ModelAdmin):
add_form = MyUserCreationForm
我的世界已经很晚了,但是我明天是否可以为你找到一个工作样本。
It's pretty late in my part of the world, but I'll see if I can get a working sample for you tomorrow.
好的,这是您需要做的这些工作所需的更改。我已经使用Django 1.3进行了测试:
Ok, here's the necessary changes you'll need to make to make this work. I've tested it using Django 1.3:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django import forms
admin.site.unregister(User)
class MyUserAdmin(UserAdmin):
add_form = MyUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
admin.site.register(User, MyUserAdmin)
我没有看到UserAdmin最初有一个add_fieldset属性。这就是为什么电子邮件字段没有以添加形式显示。
I didn't see that the UserAdmin had an add_fieldset property initially. That's why the email field wasn't displaying in the add form.
这篇关于如何使Django用户注册一步(而不是两步)进程与电子邮件强制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!