重置Invalid_form中的初始数据,并在Django中显示错误

发布于 2025-02-04 18:41:00 字数 3198 浏览 1 评论 0原文

我有一个配置文件表格,显示电子邮件用户名名字。用户只允许更改名字字段,而其他用户仅读取,如果用户更改 emage 用户名然后提交它,它返回错误,但输入了无效的值。我尝试创建一个形式的新实例并渲染它,但它不再显示错误。 我想要的是重置无效数据,然后显示错误。

forms.py

class UserEditForm(forms.ModelForm):

    email = forms.EmailField(
        label='Account email (can not be changed)', max_length=200, widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'email', 'id': 'form-email', 'readonly': 'readonly'}))

    user_name = forms.CharField(
        label='Username', min_length=4, max_length=50, widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'Username', 'id': 'form-username', 'readonly': 'readonly'}))

    first_name = forms.CharField(
        label='First name', min_length=4, max_length=50, widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'Firstname', 'id': 'form-firstname'}))

    class Meta:
        model = UserBase
        fields = ('email', 'user_name', 'first_name',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['user_name'].required = True
        self.fields['email'].required = True
    
    def clean_user_name(self):
        username = self.cleaned_data['user_name'] 
        if username != self.instance.user_name:
            raise forms.ValidationError('Sorry, you can not change your username')
        return username
    
    def clean_email(self):
        email = self.cleaned_data['email']
        if email != self.instance.email:
            raise forms.ValidationError('Sorry, you can not change your email')
        return email

views.py

class ChangeUserDetail(SuccessMessageMixin, LoginRequiredMixin, FormView):
    template_name = 'accounts/user/default_form.html'
    success_url = reverse_lazy('accounts:dashboard')
    success_message = "Username changed successfully"
    form_class = UserEditForm


    def get_form(self, form_class=form_class):
        return form_class(instance = self.request.user, **self.get_form_kwargs())

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            form = self.form_class(instance=self.request.user)
            return self.form_invalid(form)

    def form_valid(self, form):
        user = form.save()
        return super().form_valid(form)

    def form_invalid(self, form):
        return super().form_invalid(form)

html页面

<div class="row">
    <div class="col-md-6">
        {% if form.errors %}
            <div class="alert alert-danger" role="alert">
                {{form.errors}}
            </div>
        {% endif %}
        <form method="post">
            {%csrf_token%}
            {{form|crispy}}
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">{{title}}</button>
            </div>
        </form>
    </div>
</div>

I have a profile form that shows email, user name and first name. user only allowed to change first name field and the others are read only, if user change HTML value in email and username then submit it, it returns error but fill the fields with invalid value entered. I tried create a new instance of form and render it but it no longer shows the error.
The thing I want is to reset invalid data then display the error.

forms.py

class UserEditForm(forms.ModelForm):

    email = forms.EmailField(
        label='Account email (can not be changed)', max_length=200, widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'email', 'id': 'form-email', 'readonly': 'readonly'}))

    user_name = forms.CharField(
        label='Username', min_length=4, max_length=50, widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'Username', 'id': 'form-username', 'readonly': 'readonly'}))

    first_name = forms.CharField(
        label='First name', min_length=4, max_length=50, widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'Firstname', 'id': 'form-firstname'}))

    class Meta:
        model = UserBase
        fields = ('email', 'user_name', 'first_name',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['user_name'].required = True
        self.fields['email'].required = True
    
    def clean_user_name(self):
        username = self.cleaned_data['user_name'] 
        if username != self.instance.user_name:
            raise forms.ValidationError('Sorry, you can not change your username')
        return username
    
    def clean_email(self):
        email = self.cleaned_data['email']
        if email != self.instance.email:
            raise forms.ValidationError('Sorry, you can not change your email')
        return email

views.py

class ChangeUserDetail(SuccessMessageMixin, LoginRequiredMixin, FormView):
    template_name = 'accounts/user/default_form.html'
    success_url = reverse_lazy('accounts:dashboard')
    success_message = "Username changed successfully"
    form_class = UserEditForm


    def get_form(self, form_class=form_class):
        return form_class(instance = self.request.user, **self.get_form_kwargs())

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            form = self.form_class(instance=self.request.user)
            return self.form_invalid(form)

    def form_valid(self, form):
        user = form.save()
        return super().form_valid(form)

    def form_invalid(self, form):
        return super().form_invalid(form)

html page

<div class="row">
    <div class="col-md-6">
        {% if form.errors %}
            <div class="alert alert-danger" role="alert">
                {{form.errors}}
            </div>
        {% endif %}
        <form method="post">
            {%csrf_token%}
            {{form|crispy}}
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">{{title}}</button>
            </div>
        </form>
    </div>
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若有似无的小暗淡 2025-02-11 18:41:00

经过几次搜索,我发现可以通过将 disabled = true 属性添加到我的字段中来解决我的问题href =“ https://docs.djangoproject.com/en/4.0/ref/forms/fields/fields/#disabled” rel =“ nofollow noreferrer”> django文档

class UserEditForm(forms.ModelForm):

    email = forms.EmailField(
        label='Account email (can not be changed)', 
        max_length=200,
        disabled=True, 
        widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'email', 'id': 
        'form-email', 'readonly': 'readonly'}))

    user_name = forms.CharField(
        label='Username', 
        disabled=True,
        min_length=4, 
        max_length=50,
        widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'Username', 'id': 
        'form-username', 'readonly': 'readonly'}))

After a few searches I found that I can address my issue by adding disabled=True attribute to my fields so if user try to change it database will ignore change and returns the initial value as it said in Django documentation

class UserEditForm(forms.ModelForm):

    email = forms.EmailField(
        label='Account email (can not be changed)', 
        max_length=200,
        disabled=True, 
        widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'email', 'id': 
        'form-email', 'readonly': 'readonly'}))

    user_name = forms.CharField(
        label='Username', 
        disabled=True,
        min_length=4, 
        max_length=50,
        widget=forms.TextInput(
        attrs={'class': 'form-control mb-3', 'placeholder': 'Username', 'id': 
        'form-username', 'readonly': 'readonly'}))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文