即使表格有效,我也无法提交

时间:2019-06-28 09:22:24

标签: python django django-models django-forms

我已经将CreateView用于表单,但是即使表单有效也没有提交。它只是再次重定向到同一页面。我正在使用来自字段的form_id,甚至提交了一次或两次,但现在却无法正常工作。

models.py

class Centre(models.Model):
    name= models.CharField(max_length=50, blank=False, unique=True)
    address = models.CharField(max_length =250)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.")
    contact = models.CharField(max_length=100, blank=False)
    phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) 

views.py

class centre(CreateView):
    fields = ('name','address','contact','phone',)
    model = Centre
    success_url = reverse_lazy("NewApp:logindex")

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

模板:

<form method="POST">
    {% csrf_token %}
    <div class="col col-md-12">
    <div class="fieldWrapper" >
    {{ form.name.errors }}
    <div class="form-group col col-md-3">
        <label for="{{form.name.id_for_label}">Centre Name</label>
        <input type="text" placeholder="Centre Name" name="name" maxlength="250"  id="id_name" style="box-sizing: border-box; width:500px;">
    </div>
    </div>
    <div class="form-group col col-md-3" style="float:right; margin-top=-80px;width=200%">
        <label for="{{form.address.id_for_label}" style="margin-left:200px;width:200%;white-space:nowrap;">Centre&nbsp;Address</label>
         <input type="text" placeholder="Centre Address" name="address" maxlength="250" id="id_address" style="width:500px; margin-left:200px;">
    </div>
    </div>
    <br> <br><br><br>
    <div class="col col-md-12">
     <div class="form-group col col-md-3" style="float:right; margin-top=-80px;">
    <label for="{{form.contact.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">Contact&nbsp;Person</label>
     <input type="text" placeholder="Contact Person" name="address" maxlength="250" id="id_contact" style="width:500px; margin-left:200px;">
     </div>
    {{ user_form.non_field_errors }}
    <div class="fieldWrapper" >

     <div class="form-group col col-md-3" >
        <label for="{{form.phone.id_for_label}" style="white-space:nowrap;">Contact&nbsp;Number</label>
    <input type="text" name="phone"  maxlength="10" id="id_phone" placeholder="Contact Number" style="width:500px";>
        {{ form.phone.errors }}
     </div>
    </div>
    </div>
    <br>
    <br>
    <div class="col col-md-12" style="padding-left:4.5% ;padding-top:2%">
    <input type="submit" value="Save" class="btn btn-primary" style=" height:30px;width:80px;padding-bottom:2em;"></input>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

您为name字段设置了错误的contact属性,因此没有提交该属性。同时,您不会在该字段上输出错误。

(注意,您确实应该使用Django表单标签来输出输入元素;这样可以避免这种情况,并且可以在验证后重新显示模板时预先填充字段。)