如何将HTML表单附加到Django表单 [英] How to attach a html form to Django Form

查看:45
本文介绍了如何将HTML表单附加到Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有一个html表单,我想将数据从该表单发布到Django DB.反正有做吗,还是我必须在html内使用{{form.as_p}}?

I do have a form in html and I want to post the data from this form to Django DB. Does there has anyways to do it or I must use the {{form.as_p}} inside the html?

html内的表单:

<form method="post">
    {% csrf_token %}
       <div class="row align-items-stretch mb-5">
       <div class="col-md-6">
          <div class="form-group">
            <input class="form-control" id="name" name="name"/>
              <p class="help-block text-danger"></p>
          </div>
          <div class="form-group">
            <input class="form-control" id="mail" name="email"/>
              <p class="help-block text-danger"></p>
          </div>
          <div class="form-group mb-md-0">
            <input class="form-control" id="phone" name="phone"/>
              <p class="help-block text-danger"></p>
          </div>
       </div>
       <div class="col-md-6">
          <div class="form-group form-group-textarea mb-md-0">
             <textarea class="form-control" name="content" id="content"></textarea>
                <p class="help-block text-danger"></p>
           </div>
        </div>
        </div>
        <div class="text-center">
           <div id="success"></div>
               <button class="btn btn-primary btn-xl text-uppercase" type="submit">發送</button>
           </div>
</form>

views.py.如何将html表单连接到forms.py?

views.py. How do I connect the html form to forms.py?

def contact(request):

form = messageForm(request.POST or None)

if request.method == 'POST':
    form = messageForm(request.POST)
    if form.is_valid():
        form.save()
    return redirect('/#contact')
else:
    form = messageForm

context = {
    'form': form,
}
return render(request, 'contact.html', context)

forms.py

from django import forms

class messageForm(forms.ModelForm):
  class Meta:
    model = message
    fields = ('name', 'mail', 'phone', 'content')

推荐答案

您不必使用内置表单.您可以使用具有字段名称属性的任何形式将数据发布到DB.在您的项目中添加以下代码.希望对您有所帮助.

You don't have to use built in forms. You can post data to DB from any form with the name attribute of fields. Add below codes in your project. Hope it will help.

models.py

models.py

class Message(models.Model):

    """your other fields"""
    objects = models.Manager()

views.py

def contact(request):

    if request.method == 'POST':
        name = request.POST["name"]
        email = request.POST["email"]
        phone = request.POST["phone"]
        content = request.POST["content"]

        Message.objects.create(name = name, mail = email, phone = phone, content = content).save()

        return redirect('/#contact')

    else:
        return render(request, 'contact.html')

这篇关于如何将HTML表单附加到Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆