出于分析目的,我正在分析注册视图。
我想了解SignUp View是否可以改进。现在可以使用,但是可以改进吗?
例如,如果我使用:
username = user.cleaned_data.get('username')
代替:
username = user_form.cleaned_data.get('username')
我得到这个错误:
'User' object has no attribute 'cleaned_data'
为什么?
注册视图:
@transaction.atomic
def signupView(request):
###
peru = Peru.objects.all()
department_list = set()
province_list = set()
district_list = set()
for p in peru:
department_list.add(p.departamento)
department_list = list(department_list)
if len(department_list):
province_list = set(Peru.objects.filter(departamento=department_list[0]).values_list("provincia", flat=True))
province_list = list(province_list)
else:
province_list = set()
if len(province_list):
district_list = set(
Peru.objects.filter(departamento=department_list[0], provincia=province_list[0]).values_list("distrito",
flat=True))
else:
district_list = set()
if request.method == 'POST':
print("SIGNUP REQUEST POST: ", request.POST)
#####
peru = Peru.objects.all()
department_list = set()
province_list = set()
district_list = set()
for p in peru:
department_list.add(p.departamento)
department_list = list(department_list)
if len(department_list):
province_list = set(
Peru.objects.filter(departamento__in=department_list).values_list("provincia", flat=True))
province_list = list(province_list)
else:
province_list = set()
if len(province_list):
district_list = set(
Peru.objects.filter(departamento__in=department_list, provincia__in=province_list).values_list(
"distrito",
flat=True))
else:
district_list = set()
#####
user_form = SignUpForm(request.POST, request.FILES)
profile_form = ProfileForm(district_list, province_list, department_list, request.POST, request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
user.is_active = False
user.save()
username = user_form.cleaned_data.get('username')
signup_user = User.objects.get(username=username)
customer_group = Group.objects.get(name='Clientes')
customer_group.user_set.add(signup_user)
raw_password = user_form.cleaned_data.get('password1')
user.refresh_from_db() # This will load the Profile created by the Signal
profile_form = ProfileForm(district_list, province_list, department_list, request.POST, request.FILES,
instance=user.profile) # Reload the profile form with the profile instance
profile_form.full_clean() # Manually clean the form this time. It is implicitly called by "is_valid()" method
print("Profile Cleaned Data: ", profile_form.cleaned_data)
profile_form.save() # Gracefully save the form
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('carrito_de_compras:cart_detail')
else:
print(user_form.errors)
print(profile_form.errors)
else:
user_form = SignUpForm()
profile_form = ProfileForm(district_list, province_list, department_list)
return render(request, 'accounts/signup.html', {
'user_form': user_form,
'profile_form': profile_form
})
奖金:
profile_form = ProfileForm(district_list, province_list, department_list, request.POST, request.FILES)
之前
if user_form.is_valid() and profile_form.is_valid():
但也要紧随其后。正确吗?
forms.py :
class SignUpForm(UserCreationForm):
error_messages = {
'password_mismatch': "Las contraseñas no coinciden.",
}
first_name = forms.CharField(label="Nombre", max_length=100, required=True)
last_name = forms.CharField(label='Apellido', max_length=100, required=True)
username = forms.CharField(label='Nombre de usuario', max_length=100, required=True,
error_messages={'invalid': "you custom error message"})
email = forms.EmailField(label='Correo electrónico', max_length=60, required=True)
password1 = forms.CharField(label='Contraseña', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirmar contraseña', widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
for fieldname in ['username', 'password1', 'password2']:
self.fields[fieldname].help_text = None
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1',
'password2')
class ProfileForm(ModelForm):
MONTHS = {
1:'ene', 2:'feb', 3:'mar', 4:'abr',
5:'may', 6:'jun', 7:'jul', 8:'ago',
9:'set', 10:'oct', 11:'nov', 12:'dic'
}
def __init__(self, district_list, province_list, department_list, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
self.fields['shipping_district'] = forms.ChoiceField(label='Distrito', choices=tuple([(name, name) for name in district_list]))
self.fields['shipping_province'] = forms.ChoiceField(label='Provincia', choices=tuple([(name, name) for name in province_list]))
self.fields['shipping_department'] = forms.ChoiceField(label='Departamento', choices=tuple([(name, name) for name in department_list]))
dni = forms.CharField(label='DNI', max_length=100, required=True)
phone_number = forms.CharField(label='Celular')
birthdate = forms.DateField(label='Fecha de nacimiento', widget=SelectDateWidget(years=range(1980, 2012), months=MONTHS))
shipping_address1 = forms.CharField(label='Dirección de envío', max_length=100, required=True)
address_reference = forms.CharField(label='Referencia', max_length=100, required=False)
photo = forms.ImageField(label='Foto de perfil', required=False)
class Meta:
model = Profile
fields = ('dni', 'phone_number', 'birthdate', 'shipping_address1',
'address_reference', 'shipping_department', 'shipping_province', 'shipping_district', 'photo')
models.py:
### User Profile ###
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthdate = models.DateField(null=True, blank=True)
dni = models.CharField(max_length=30, blank=True)
phone_number = models.CharField(max_length=30, blank=True)
shipping_address1 = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
shipping_department = models.CharField(max_length=100, blank=False)
shipping_province = models.CharField(max_length=100, blank=False)
shipping_district = models.CharField(max_length=100, blank=False)
photo = models.ImageField(upload_to='profile_pics', default='profile_pics/default_profile_pic_white.png')
def __str__(self):
return str(self.user.first_name) + "'s profile"
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
答案 0 :(得分:1)
“用户”是用户模型的实例,它没有cleaned_data。只有表单具有该属性。