Django不阅读表格

时间:2019-12-19 21:50:31

标签: python django

我有表格:

<form id="contact-form" class="contact__form" method="POST" action="{% url 'backcall' %}">

    {% csrf_token %}
    <span class="text-color">Send letter</span>
    <div class="form-group">
        <input name="name" type="text" class="form-control" placeholder="Name">
    </div>
     <div class="form-group">
       <input type="tel" name="phone" class="form-control" placeholder="Phone (+380)"  pattern="[\+][3][8][0]\d{9}" minlength="13" maxlength="13" />
    </div>
    <div class="form-group">
        <input name="email" type="email" class="form-control" placeholder="Email">
    </div>
    <div class="form-group-2 mb-4">
        <textarea name="message" class="form-control" rows="4" placeholder="Your letter"></textarea>
    </div>
    <button class="btn btn-main" name="submit" type="submit">Send</button>
</form>

views.py:

def backcall(request):
    backcall = BackCall(name = request.POST['name'], phone = request.POST['phone'], email=request.POST['email'] , message = request.POST['message'])
    backcall.save()
    return redirect('thanks')

models.py

class BackCall(models.Model):
    name = models.CharField(max_length=50)
    phone = models.CharField(max_length=13)
    email = models.EmailField()
    message = models.TextField(default=None)
    datetime = models.DateTimeField(auto_now_add=True)

当我填写表格并且不提交任何内容时。当我点击链接“ backcall /”时,我得到一个error

可以解决什么问题,以及如何解决?

1 个答案:

答案 0 :(得分:0)

请搜索更多,存在solution

  

使用MultiValueDict的get方法。这也存在   标准命令,是在提供默认值的同时获取值的一种方法   如果不存在。

def backcall(request):
    backcall = BackCall(name = request.POST.get('name'), phone = request.POST.get('phone'), email=request.POST.get('email') , message = request.POST.get('message'))
    backcall.save()
    return redirect('thanks')

您应该检查记录是否存在于数据库中,我认为,一个简单的例子是:

 def backcall(request):
     obj, created = BackCall.objects.get_or_create(email=request.POST.get('email'),
                           defaults={'phone': request.POST.get('phone'),
                                              'name': request.POST.get('name'),
                                              'message': request.POST.get('message')}

    if created:
       return redirect('thanks')

    return ...