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

时间:2020-05-05 01:07:38

标签: python django django-models django-forms django-views

###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文件的else语句中所定义)。

用错误的数据填写表格后,按“提交”按钮将刷新表格而不显示错误。在用正确的数据填写表格后,用户将被注册(显示模板中定义的“感谢您注册”)。我知道我在做或想念的东西一定很愚蠢。请让我知道。

0 个答案:

没有答案