Django图片表单提交提示‘this field is required’及作者字段自动填充问题
Fixing the "this field is required" Error for Image Uploads
The primary reason you're seeing this error is that your form isn't configured to handle file uploads correctly. Let's walk through the fixes:
Add the
enctypeattribute to your HTML form
When uploading files, the form must includeenctype="multipart/form-data"to tell the server how to process the file data. Update your form tag like this:<form class="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form>Correct the
cleaned_dataaccess in your view
Inviews.py, you're treatingcleaned_dataas a method (with parentheses), but it's actually a dictionary property. Remove the parentheses:# Replace this line clean_data = form.cleaned_data() # With this clean_data = form.cleaned_dataProperly create the Picture object
You can't pass theclean_datadict directly tocreate()without unpacking it. Use the double asterisk (**) to unpack the dictionary, and we'll add the author field in the next section:Picture.objects.create(**clean_data, author=request.user)
Auto-Filling the Author Field with the Logged-In User
To automatically assign the current logged-in user to the author field:
Restrict access to authenticated users
First, import thelogin_requireddecorator and apply it to your form view to ensure only logged-in users can submit the form:# Add this import at the top of views.py from django.contrib.auth.decorators import login_required # Apply the decorator to your view @login_required def picture_form_view(request): # ... existing view code ...Assign the logged-in user to the author field
As shown earlier, when creating the Picture object, passauthor=request.user—this will use the currently authenticated user for the author field without needing to include it in the form.
These fixes should resolve both your image upload error and automatically set the author field for you.
内容的提问来源于stack exchange,提问作者Pablo Cortes Rodriguez

