简体   繁体   中英

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. It says 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

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

forms.py

from django import forms
from .models import pic

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

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

<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.

Secondly, your form element in the template needs to include enctype="multipart/form-data" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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