【问题标题】:Django forms does not care about html inputDjango 表单不关心 html 输入
【发布时间】:2020-01-09 07:04:24
【问题描述】:

在我的 django 项目中,我创建了一个用于管理用户注册的表单,这里是我的代码:

models.py:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,)
    u_fullname = models.CharField(max_length=200)
    u_email = models.EmailField()
    u_profile = models.CharField(max_length=1)
    u_type = models.CharField(max_length=1, default='F')
    u_job = models.CharField(max_length=100, null=True, blank=True, default='D')
    u_country = models.CharField(max_length=20, null=True, blank=True, default='Italy')
    u_regdata = models.DateTimeField(auto_now=True)
    u_picture = models.ImageField(upload_to='profile_images', blank=True)
    u_active = models.BooleanField(default=False)
    u_terms = models.BooleanField(default=False)

    def __unicode__(self):
        return self.u_profile

forms.py

class ProfileModelForm(ModelForm):

    class Meta:
        model = UserProfile
        fields = ['u_fullname',
              'u_job',
              'u_country',
              'u_email',
              'u_terms',
              ]

    def clean(self):
        cleaned_data = super(ProfileModelForm, self).clean()
        u_fullname = cleaned_data.get('u_fullname')
        u_job = cleaned_data.get('u_job')
        u_country = cleaned_data.get('u_country')
        u_email = cleaned_data.get('u_email')
        u_terms = cleaned_data.get('u_terms')
        if not u_terms:
            raise forms.ValidationError("Please read and accept our Terms of Service")
        return u_terms

        if not u_fullname and not u_job and not u_country and not u_terms:
            raise forms.ValidationError('You have to write something!')

views.py

if request.method == 'POST':
    if 'user_reg' in request.POST:
        form = ProfileModelForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            #Create user and get the id
            n_user = User.objects.create_user(username=request.POST['u_email'],
                                            email=request.POST['u_email'],
                                            password=request.POST['u_password'])
            instance.user = User.objects.get(id=n_user.id)
            instance.u_profile = 'U'
            instance.save()
            return
        else:
            messages.error(request, "Error")

最后是我的 html 表单部分:

<form action="" method="POST">
                                        {% csrf_token %}

                                        {{ form.errors }}

                                        <div class="row">
                                            <div class="col-lg-12 no-pdd">
                                                <div class="sn-field">
                                                    <input type="text" name="u_fullname" placeholder="Full Name" value={{ form.u_fullname }}>
                                                    <i class="la la-user"></i>
                                                </div>
                                            </div>
                                            <div class="col-lg-12 no-pdd">
                                                <div class="sn-field">
                                                    <select value={{ form.u_country }}>
                                                        <option selected="selected">Italy</option>
                                                        <option>Spain</option>
                                                        <option>USA</option>
                                                        <option>France</option>
                                                    </select>
                                                    <i class="la la-globe"></i>
                                                    <span><i class="fa fa-ellipsis-h"></i></span>
                                                </div>
                                            </div>
                                            <div class="col-lg-12 no-pdd">
                                                <div class="sn-field">
                                                    <select value={{ form.u_job }}>
                                                        <option value="D" selected="selected">Developer</option>
                                                        <option value="T">Tester</option>
                                                        <option value="S">System Administrator</option>
                                                        <option value="V">Sales</option>
                                                    </select>
                                                    <i class="la la-dropbox"></i>
                                                    <span><i class="fa fa-ellipsis-h"></i></span>
                                                </div>
                                            </div>
                                            <div class="col-lg-12 no-pdd">
                                                <div class="sn-field">
                                                    <input type="text" name="u_email" placeholder="Enter a valid email" value="{{ form.u_email }}">
                                                    <i class="la la-envelope"></i>
                                                </div>
                                            </div>
                                            <div class="col-lg-12 no-pdd">
                                                <div class="sn-field">
                                                    <input type="password" name="u_password" placeholder="Password">
                                                    <i class="la la-lock"></i>
                                                </div>
                                            </div>
                                            <div class="col-lg-12 no-pdd">
                                                <div class="sn-field">
                                                    <input type="password" name="repeat-password" placeholder="Repeat Password">
                                                    <i class="la la-lock"></i>
                                                </div>
                                            </div>
                                            <div class="col-lg-12 no-pdd">
                                                <div class="checky-sec st2">
                                                    <div class="fgt-sec">
                                                        <input type="checkbox" name="cc" id="c2" value={{ form.u_terms }}>
                                                        <label for="c2">
                                                            <span></span>
                                                        </label>
                                                        <small>Yes, I understand and agree to the workwise Terms & Conditions.</small>
                                                    </div><!--fgt-sec end-->
                                                </div>
                                            </div>
                                            <div class="col-lg-12 no-pdd">
                                                <button type="submit" name="user_reg" value="submit">Get Started</button>
                                            </div>
                                        </div>
                                    </form>

好吧,现在我的问题是输入的字段数据似乎没有被考虑在内;我所做的每一次选择,或者如果我选中数据库中的框,我都会找到模型默认值。 如何解决我的问题以正确管理表单中的所有字段?

提前非常感谢

【问题讨论】:

    标签: python django python-3.x django-forms


    【解决方案1】:

    问题在于clean 方法中的覆盖;此方法应返回与所有字段相关的数据:

    class ProfileModelForm(ModelForm):
        # ...
    
        def clean(self):
            cleaned_data = super(ProfileModelForm, self).clean()
            u_fullname = cleaned_data.get('u_fullname')
            u_job = cleaned_data.get('u_job')
            u_country = cleaned_data.get('u_country')
            u_email = cleaned_data.get('u_email')
            u_terms = cleaned_data.get('u_terms')
            if not u_terms:
                raise forms.ValidationError("Please read and accept our Terms of Service")
            return cleaned_data
    
            # This would never run:
    
            if not u_fullname and not u_job and not u_country and not u_terms:
                raise forms.ValidationError('You have to write something!')

    还请记住,永远不会检查您的第二个 if 语句,因为它位于 return 语句之后。

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2020-01-31
      • 2018-01-19
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      相关资源
      最近更新 更多