Django Forms - 将用户名字段设置为等于电子邮件字段

时间:2014-10-16 19:24:29

标签: django django-models django-forms

我有一个Django模型表单,我正在尝试将用户名字段设置为等于电子邮件字段。

这是我的表格

class UserForm(forms.ModelForm):
    email = forms.EmailField()
    username = forms.CharField(widget=forms.HiddenInput())

    class Meta:
        model = User
        fields = ('email', 'username')

我目前正在使用一些JavaScript在用户提交表单之前将新的电子邮件值复制到用户名隐藏输入,但我想在服务器端执行此操作。

在保存表单之前,我尝试通过执行以下UserForm['username'] = email设置它并收到以下错误object does not support item assignment

任何提示都将不胜感激。

2 个答案:

答案 0 :(得分:3)

我没有测试过这个,我认为它会起作用。如果没有检查覆盖肯定有效的保存方法。 Django Model Field Default Based Off Another Field in Same Model

class UserForm(forms.ModelForm):
    email = forms.EmailField()
    username = forms.CharField(default=email)

    class Meta:
        model = User
        fields = ('email', 'username')

答案 1 :(得分:0)

也许有用

from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User
    

更多信息 enter link description here

class UserForm(UserCreationForm):

    class Meta:
        model = User
        fields = ('email', 'username')
        email = forms.EmailInput(attrs={'placeholder': "Email"})

    def save(self, commit=True):
        user = super(UserForm, self).save(commit=False)
        user.username = user.email
        if commit:
            user.save()
        return user