I'm having difficulty uploading the following model with model form. I can upload fine in the admin but that's not all that useful for a project that limits admin access.
#Models.py
class Profile(models.Model):
name = models.CharField(max_length=128)
user = models.ForeignKey(User)
profile_pic = models.ImageField(upload_to='img/profile/%Y/%m/')
#views.py
def create_profile(request):
try:
profile = Profile.objects.get(user=request.user)
except:
pass
form = CreateProfileForm(request.POST or None, instance=profile)
if form.is_valid():
new = form.save(commit=False)
new.user = request.user
new.save()
return render_to_response('profile.html', locals(), context_instance=RequestContext(request))
#Profile.html
<form enctype="multipart/form-data" method="post">{% csrf_token %}
<tr><td>{{ form.as_p }}</td></tr>
<tr><td><button type="submit" class="btn">Submit</button></td></tr>
</form>
Note: All the other data in the form saves perfectly well, the photo does not upload at all. Thank you for your help!
In Django, a default database is automatically created for you. All you have to do is add the tables called models. The upload_to tells Django to store the photo in a directory called pics under the media directory. The list_display list tells Django admin to display its contents in the admin dashboard.
You need to pass request.FILES
to your form:
form = CreateProfileForm(request.POST, request.FILES, instance=profile)
Ref: Handling uploaded files with a model
Form initialization code have to be like this:
form = MemberSettingsForm(request.POST or None, request.FILES or None, instance=user)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With