Skip to main content
 首页 » 编程设计

python之如何让用户改变他的属性

2025年04月02日13cmt

我正在尝试弄清楚如何允许用户更改他们的个人资料。我有一个由 User Profile (OneToOne) 扩展的 Users。

我正在考虑更改注册 View ,预填充用户的属性并允许他更改它们。但这可能不是好方法。

你能告诉我怎么做吗?

class UserForm(forms.ModelForm): 
    password1 = forms.CharField(widget=forms.PasswordInput()) 
    password2 = forms.CharField(widget=forms.PasswordInput()) 
 
    class Meta: 
        model = User 
        fields = ('username', 'email', 'password1','password2', 'first_name', 'last_name') 
 
    def clean(self): 
        password1 = self.cleaned_data.get('password1') 
        password2 = self.cleaned_data.get('password2') 
 
        if password1 and password1 != password2: 
            raise forms.ValidationError("Passwords don't match") 
 
        return self.cleaned_data 
 
class UserProfileForm(forms.ModelForm): 
    class Meta: 
        model = UserProfile 
        fields = ('telephone','marital_status','how_do_you_know_about_us') 

MODELS.PY

class UserProfile(models.Model): 
    user = models.OneToOneField(User,on_delete=models.CASCADE) 
 
    # ATRIBUTY KTORE BUDE MAT KAZDY 
    telephone = models.CharField(max_length=40,null=True) 
 
    HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = ( 
            ('coincidence',u'It was coincidence'), 
            ('relative_or_friends','From my relatives or friends'), 
            ) 
    how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True) 
 
    MARITAL_STATUS_CHOICES = ( 
        ('single','Single'), 
        ('married','Married'), 
        ('separated','Separated'), 
        ('divorced','Divorced'), 
        ('widowed','Widowed'), 
    ) 
    marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True) 
 
    # OD KIAL STE SA O NAS DOZVEDELI 
    # A STAV 
 
    def __unicode__(self): 
        return '{} {}'.format(self.user.first_name,self.user.last_name) 
 
    def __str__(self): 
        return '{} {}'.format(self.user.first_name,self.user.last_name) 

注册 View :

def register(request): 
    if request.method == 'POST': 
        user_form = UserForm(request.POST) 
        profile_form = UserProfileForm(request.POST) 
        if user_form.is_valid() and profile_form.is_valid(): 
 
            user = user_form.save() 
            user.set_password(user_form.cleaned_data['password1']) 
            user.save() 
 
            profile = profile_form.save(commit=False) 
            profile.user = user 
 
            profile.save() 
            return register_success(request) 
 
        else: 
            print user_form.errors, profile_form.errors 
 
    else: 
        user_form = UserForm() 
        profile_form = UserProfileForm() 
 
    return render(request, "auth/registration/register.html", 
                  context={'user_form': user_form, 'profile_form': profile_form}) 

编辑:

这是我要创建的 View ,但它不会自动填充表单:

@login_required 
def edit_profile(request): 
    myUser = request.user 
    user_form = UserForm(request.POST, instance=myUser) 
    user_profile_form = UserProfileForm(request.POST, instance=myUser) 
 
    context={'user_form': user_form, 
             'user_profile_form':user_profile_form} 
    return render(request, 'auth/profiles/my_profile.html', context=context) 

请您参考如下方法:

在您添加的 edit_profile View 中,您正在向表单传递一个 POST 请求参数。您应该只在 POST 请求上传递此参数。因此,如果请求是 GET 请求,请将您的表单更新为以下内容:

View .py

user_form = UserForm(instance=myUser) 
user_profile_form = UserProfileForm(instance=myUser) 

表单.py

# Something like this will only save password if data is entered in one of the password fields 
def clean(self): 
    cleaned_data = super(UserForm, self).clean() 
    password1 = cleaned_data.get('password1', None) 
    password2 = cleaned_data.get('password2', None) 
    old_password = cleaned_data.get('old_password', None) 
    if password1 or password2: 
        if password1 != password2: 
            self._errors['password1'] = 'New Password and Confirm New Password must match.' 
            self._errors['password2'] = 'New Password and Confirm New Password must match.' 
        if not self.user.check_password(old_password): 
            self._errors['old_password'] = 'Your old password was entered incorrectly.' 
    return cleaned_data 
 
def save(self, request): 
    user = self.user 
    if self.cleaned_data.get('password1', None): 
        user.set_password(self.cleaned_data.get('password1')) 
        update_session_auth_hash(request, user) 
    user.save() 
    return user 

对于您的选择问题,您可以在为字段指定小部件时将选择指定为参数。