Django如何将POST保存为表格?

问题描述 投票:0回答:2

我正在尝试将POST保存到我的表单中。

views.py

def index(request):

    if request.method == 'POST':
       print('!PRINT request.POST')
       print(request.POST)
       form = PostForm(request.POST, request.FILES)
       print('!PRINT form')
       print(form)
       if form.is_valid():
          form.save()
       return redirect('/')

返回:!PRINT request.POST

〜'title':['Bart','Mat'],'Create Match':['Submit']}>

!PRINT表格

〜name =“ title” value =“ Mat” maxlength =“ 200”必需的id =“ id_title”

〜name =“ title1” class =“ errorlist”此字段为必填。

forms.py

class PostForm(forms.ModelForm):

    class Meta:
       model = Post
       fields = '__all__'

models.py

class Post(models.Model):
title = models.CharField(max_length=200)
title1 = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
    return self.title

list.html

<form method="POST" enctype="multipart/form-data" action="/">
{%  csrf_token %}
{{ form.title }}
{{ form.title }}
<input type="submit" name="Create Match">
</form>>
python django forms post http-post
2个回答
0
投票

您没有将值传递给表单,没有要保存的数据

尝试这样的事情:

def index(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            new_post = name_of_your_model(
                field1=value_you_want_to_safe,
                field2=value_you_want_to_safe,
                ...
            )
            new_post.save()
        return redirect('/')

0
投票

尝试此代码段,

在views.py

def index(request):
    form = PostForm()

    if request.method == 'POST':
       form = PostForm(request.POST, request.FILES)

       if form.is_valid():
           form.save()
           return redirect('/')

    return render(request,'path_to/html_template.html',context={'form':form})

在您的html_template.html中

<form method="POST" enctype="multipart/form-data" >
    {%csrf_token%}
    {% form.as_p %}
    <button type="submit">Submit</button>
</form>
© www.soinside.com 2019 - 2024. All rights reserved.