Skip to main content
 首页 » 编程设计

python之关于 Django 和 User Auth 的问题

2025年05月04日29qlqwjy

Django 的菜鸟问题:

我使用 dango.contrib.auth 来管理我网站的用户。 但是现在,我正在开发“设置页面”,用户可以在其中编辑他的名字、姓氏和电子邮件地址。但在设置页面中,我还想要一个“时事通讯”复选框。

问题是: 1)我应该把时事通讯字段放在数据库的什么地方? 2) 如何创建用于编辑这些信息的表单?

谢谢。

-- 更新--

现在我在 models.py 中有这个:

class UserProfile(models.Model): 
    user = models.ForeignKey(User, unique = True) 
    favourite_color = models.CharField(max_length = 40) 

在 forms.py 中:

class UserSettingsForm(forms.ModelForm): 
 
    class Meta: 
        model = User 
        exclude = ('password',) 
 
    def save(self, commit=False): 
        user = super(UserSettingsForm,self).save(commit) 
        favourite_color = self.cleaned_data.get('favourite_color', '') 
        if favourite_color and user.favourite_color is None: 
            UserProfile(user=user).save() 
        if not slug: 
            UserProfile.objects.filter(user=user).delete() 
 
        if not commit: 
            user.save() 
        return user 

我有点困惑。我会在设置表单中编辑名字、姓氏、电子邮件和最喜欢的颜色等信息,但实际上我做错了。

请您参考如下方法:

你想看user profiles .

编辑:关于表格,是否有什么阻止您使用两种表格?我认为 Django 会忽略 HTTP 请求中与表单不匹配的字段,因此您可以将请求提供给两个表单。呈现模板时,Django 不会生成 <form>标签或提交按钮,所以你只需将两个表单放在同一个 <form> 中.在您看来是这样的(修改 Django example ):

def edit_user_view(request): 
    if request.method == 'POST': # If the form has been submitted... 
        # Two forms bound to the POST data 
        userForm = UserForm(request.POST) 
        profileForm = ProfileForm(request.POST) 
        if userForm.is_valid() and userForm.is_valid(): 
            # All validation rules pass 
            # Process the data in userForm. and profileForm.cleaned_data 
            # ... 
            return HttpResponseRedirect('/thanks/') # Redirect after POST 
    else: 
        # Unbound forms 
        userForm = UserForm() 
        profileForm = ProfileForm() 
 
    return render_to_response('edit_user.html', { 
        'userForm': userForm, 
        'profileForm': profileForm, 
    }) 

在模板中:

<form action="/contact/" method="post">{% csrf_token %} 
{{ userForm.as_p }} 
{{ profileForm.as_p }} 
<input type="submit" value="Submit" /> 
</form> 

这实际上只是一个起点,但我看不出有任何理由不能奏效。