Django image uploading

霸气de小男生 提交于 2019-12-11 10:15:43

问题


I have a problem with image uploading. For now, chosen image file is not copied to destination directory and path to this file is not added to database.

I'm giving my code below:

models.py:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField(upload_to="avatar/")

form.py

class ProfileEditionForm(ModelForm):
    class Meta:
        model = UserProfile
        exclude = ('user')

view.py:

def index(request):
    if request.user.is_authenticated():
        user = User.objects.get(pk=request.user.id)

        if request.method == "POST":
            form = ProfileEditionForm(request.POST, request.FILES, instance=user)

            if form.is_valid():
                form.save()
                #return HttpResponseRedirect(reverse('profile_edit'))
        else:
            form = ProfileEditionForm(instance=user)

        return direct_to_template(request, 'profile_edit.html', { 'form' : form })
    else:
        return HttpResponseRedirect(reverse('main_page'))

Thanks in advance for help.


回答1:


your ModelForm is bound to UserProfile model, but your are instantiating it with instance=user.

PS: request.user is User.objects.get(pk=request.user.id)




回答2:


https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

your form should have the enctype="multipart/form-data" or request.FILES won't have any data stream associated



来源:https://stackoverflow.com/questions/7241743/django-image-uploading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!