如何自动将上传的图像分配给用户?

时间:2013-11-18 01:56:04

标签: django image foreign-keys

我是django的新手,并尝试制作一个简单的图片uplad应用程序,用户可以上传图片。

以下是部分:

model.py

class UserPic(models.Model):
    user = models.ForeignKey(User)
    picfile = models.FileField(upload_to=get_uplaod_file_name)

views.py

@login_required
def list(request):
    # Handle file upload
    if request.method == 'POST':
        picform = PicForm(request.POST, request.FILES, instance=request.user)
        if picform.is_valid():

            newpic = UserPic(picfile = request.FILES['picfile'])
            newpic = picform.save(commit=False)
            newpic.user = request.user
            newpic.save()
            message = "file %s is uploaded" % newpic #**returns name of current user instead of the file's name**
            userpics = UserPic.objects.all()
            # Redirect to the document list after POST
            return render_to_response('userpics/listpics.html',
                                      {'userpics': userpics, 'picform': picform},
                                      context_instance=RequestContext(request)
    )

forms.py

class PicForm(forms.ModelForm):

        class Meta:
                model= UserPic
                fields = ( 'picfile',)

listpic.html

<p> Upload pics to your gallery </p>
{% if userpics %}
        <ul>
        {% for pic in userpics %}
            <li><a href="{{ pic.picfile.url }}">{{ pic.picfile.name }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No userpics.</p>
    {% endif %}

        <!-- Upload form. Note enctype attribute! -->
        <form action="/add-pic/" method="post" enctype="multipart/form-data">
            {% csrf_token %}

<ul>
{{picform.as_ul}}
</ul>
            </p>
            <p><input type="submit" value="Upload" /></p>
        </form>

Upade:根据建议,我修改了视图,错误消失但文件没有保存到数据库中。

基本上我的问题是如何自动将用户指定为外键。 我试着几种不同的解决方案但仍然对此有所了解并感谢您帮助解决此问题。

1 个答案:

答案 0 :(得分:0)

您正在尝试创建新对象。要使commit=False生效,您应该使用ModelForm对象。然而,您直接从类创建模型对象,因此出错。

尝试这样的事情:

if request.method == 'POST':
    picform = PicForm(request.POST, request.FILES)
    if picform.is_valid():
        newpic = picform.save(commit=False)
        newpic.user= request.user #user would be undefined. 
        newpic.save()
    #rest of the code. 

详细了解django-modelforms hereTHe save() method in particular