【问题标题】:How to automatically assign uploaded image to user?如何自动将上传的图像分配给用户?
【发布时间】:2013-11-20 04:45:56
【问题描述】:

我是 django 新手,尝试制作一个简单的图片上传应用,用户可以在其中上传图片。

以下是部分:

模型.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:根据建议,我修改了视图,错误消失了,但文件没有保存到数据库中。

基本上我的问题是如何自动将用户分配为外键。 我尝试了几种不同的解决方案。但仍有库存,感谢您为解决此问题提供的帮助。

【问题讨论】:

    标签: django image foreign-keys


    【解决方案1】:

    您正在尝试创建一个新对象。要使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 here 上阅读更多信息。 THe save() method in particular

    【讨论】:

    • 添加 picform 后我得到 'global name 'user' is not defined'。
    • 完全正确。检查评论。应该是request.user
    • 对不起,错误消失了,但我检查数据库时没有保存图像。 'newpic' 似乎已经变成了一个用户对象,因为当我把它写成一个字符串时,它会打印出当前的用户名。这里有问题。
    • 这是因为您可能在 UserPic 模型上具有 __unicode__ 属性。
    • 我已删除 unicode 但问题仍然存在。像“文件 %s 已上传”这样的打印语句 % newpic 给了我用户名而不是文件名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多