本站消息

站长简介/公众号


站长简介:逗比程序员,理工宅男,前每日优鲜python全栈开发工程师,利用周末时间开发出本站,欢迎关注我的微信公众号:幽默盒子,一个专注于搞笑,分享快乐的公众号

  价值13000svip视频教程,python大神匠心打造,零基础python开发工程师视频教程全套,基础+进阶+项目实战,包含课件和源码

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Django 3.0 表单:表单错误未显示在模板上

发布于2021-06-04 04:30     阅读(929)     评论(0)     点赞(16)     收藏(3)



###I have model named Publisher in models.py file.###
###And based on this model, a modelForm has made, called "RegistrationForm".###
###Which renders form on registration.html template.###
<br /> <br />**This is code of registration.html**

<pre><code>
```
        <body>
            <div class="container">
                {% load my_filters %}
                <div class="row">
                    <div class="col-md-6 offset-md-3">
                        {% if registered %}
                            <h1>Thank you for registering!</h1>
                        {% else %}
                            <h1>Register Here</h1>
                            <h3>Just fill out the form.</h3>
                            <form enctype="multipart/form-data" method="POST">
                                {% csrf_token %}

                                {{ reg_form.non_field_errors }}
                                <div class="fieldWrapper">
                                    <div class="form-group">
                                        {{ reg_form.name.errors }}
                                        <label for="{{ reg_form.name.id_for_label }}" >Name:</label>
                                        {{ reg_form.name|addclass:'form-control' }}
                                    </div>
                                </div>
                                <div class="fieldWrapper">
                                    <div class="form-group">
                                        {{ reg_form.email.errors }}
                                        <label for="{{ reg_form.email.id_for_label }}">Email:</label>
                                        {{ reg_form.email|addclass:'form-control' }}
                                    </div>
                                </div>
                                <div class="fieldWrapper">
                                    <div class="form-group">
                                        {{ reg_form.contact.errors }}
                                        <label for="{{ reg_form.contact.id_for_label }}">Contact:</label>
                                        {{ reg_form.contact|addclass:'form-control' }}
                                    </div>
                                </div>
                                <div class="fieldWrapper">
                                    <div class="form-group">
                                        {{ reg_form.password.errors }}
                                        <label for="{{ reg_form.password.id_for_label }}">Password: 
                                        </label>
                                        {{ reg_form.password|addclass:'form-control' }}
                                    </div>
                                </div>
                                <div class="fieldWrapper">
                                    <div class="form-group">
                                        {{ reg_form.confirm_password.errors }}
                                        <label for="{{ reg_form.confirm_password.id_for_label }}">Confirm 
                                         Password:</label>
                                        {{ reg_form.confirm_password|addclass:'form-control' }}
                                    </div>
                                </div>
                                <input type="submit" name="" value="Register">
                            </form>
                        {% endif %}
                    </div>
                </div>
            </div>
        </body>

```
</code></pre>
### I am NOT using crispy forms just manually rendering Django forms and using manual template tag to add classes to fields. 
**This is the template tag in used to add classes to form fields**

<code><pre>
```
     @register.filter(name='addclass')
        def addclass(value, arg):
            return value.as_widget(attrs={'class': arg})

```
</code></pre>

**This is the model in models.py**

<code><pre>
```
        class Publisher(models.Model):
            id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
            name = models.CharField('Name', max_length=50)
            email = models.EmailField('Email', unique=True)
            password = models.CharField('Password', max_length=50)
            contact = models.CharField('Contact #', max_length=16, unique=True, validators=[
            RegexValidator(
                regex=r'^\+?1?\d{9,15}$',
                    message="Phone number must be entered in the format '+123456789'. Up to 15 digits allowed."
                    ),
                ],)

                def __str__(self):
                    return self.name

```
</code></pre>
**This is the form in forms.py file**
<code><pre>
```
    class RegistrationForm(forms.ModelForm):
        password = forms.CharField(widget=forms.PasswordInput())
        confirm_password = forms.CharField(widget=forms.PasswordInput())
        class Meta():
            model = Publisher
            fields = ('name','email','contact','password')

        def clean(self):
            cleaned_data = super(RegistrationForm, self).clean()
            password = cleaned_data.get("password")
            confirm_password = cleaned_data.get("confirm_password")

            if password != confirm_password:
                raise forms.ValidationError(
                        "password and confirm_password does not match"
                    )       

```
</code></pre>
**This is the view in views.py file**
<code><pre>
```
    def registration(request):
        registered = False

        if request.method == 'POST':

            reg_form = RegistrationForm(data=request.POST)

            if reg_form.is_valid():

                user = reg_form.save()
                user.save()
                registered = True

            else:
                #Now issue is this printing statement working fine and printing errors on console.But 
                #errors are not showing on template.
                print(reg_form.errors)    
        else:
            reg_form = RegistrationForm()

        return render(request, 'seller/registration.html',
                      {'reg_form': RegistrationForm,
                       'registered': registered
                       })
```
</code></pre>

我已经看到了所有的堆栈溢出并尝试了很多事情,但没有一个能帮助我解决表单模板上的错误(尽管密码不匹配和联系电话错误等错误会打印在 django 控制台上views.py 文件)。

用错误的数据填写表单后按下“提交”按钮,它会刷新表单而不是显示错误。并用正确的数据填写表格后,用户注册(它显示模板中定义的“感谢您注册”)我知道我在做或错过了一些愚蠢的事情。请让我知道。


解决方案


暂无回答






所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/983426/fcd34efe5500191506be/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

16 0
收藏该文
已收藏

评论内容:(最多支持255个字符)