Django--制作表单

    xiaoxiao2021-04-17  28

    --------------这只是其中一个方法--------------

    step1

    创建一个模型model

    class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(auto_now=True)

    step2

    新建一个form.py。(任意命名,放在你的app同级目录)

    from django.forms import ModelForm from .models import Question class NewPoll(ModelForm): class Meta: model = Question fields='__all__'

    step3

    views中

    def new_poll(request): if request.method == 'POST': form = NewPoll(request.POST) if form.is_valid(): poll=form.save() poll.save() return HttpResponse('ok') else: form = NewPoll() return render(request,'polls/new_poll.html',{'form':form})

    step4

    新建模板,就是一个html,就叫new_poll.html。body中写一个form表单。

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>创建新问卷</title> </head> <body> <form action="" method="post"> {% csrf_token %} {{ form }} <br/> <input type="submit" value="submit"/> </form> </body> </html>

    step5

    配置,应用的url,urlpattern中添加

    url(r'^newpoll/$',views.new_poll,name='newpoll'),

    --------------注意点--------------------

    request的方法,POST,必须大写

    csrf打开,否则无法接收到表单

    转载请注明原文地址: https://ju.6miu.com/read-673248.html

    最新回复(0)