简体   繁体   English

Django:表单数据未保存

[英]Django : Form data not saving

I have a form where user just uploads an image,but problem is when I choose an image and press button to submit. 我有一个form ,用户只上传一张图片,但是问题是当我选择一张图片并按按钮提交时。 It says This field is required. 它说This field is required. on the page although I have already pointed the image. 在页面上,尽管我已经指出了图像。 And that's all it does.I checked if it was actually submitted but no, it was not.What could be the problem ? 这就是全部操作了。我检查了它是否确实提交了,但不是,不是。这可能是什么问题?

Models.py Models.py

class pic(models.Model):
    username = "anonymous"
    picpost = models.ImageField(upload_to='anon_pics')
    creation_date = models.DateTimeField(auto_now_add=True)

forms.py forms.py

from django import forms
from .models import pic

class PicForm(forms.ModelForm):
    class Meta:
        model = pic
        fields = [
            "picpost"
        ]

view.py view.py

def pic_create(request):
    form = PicForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False) 
        instance.save()
    context = {
        "form" : form,
    }
    return render(request, "create_pic.html", context)

create_pic.html create_pic.html

<body>
    <form method='POST' action=''>{% csrf_token %}
        {{ form.as_p }}
        <input type='submit' value='Upload Picture' />
    </form>
</body>

Any help is highly appreciated.Thank you very much! 非常感谢您的帮助。非常感谢!

There are two issues here. 这里有两个问题。

Firstly, your view needs to pass request.FILES as well as request.POST to the form. 首先,您的视图需要将request.FILESrequest.POST传递给表单。

Secondly, your form element in the template needs to include enctype="multipart/form-data" . 其次,模板中的表单元素需要包含enctype="multipart/form-data"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM