django上传到用户的外键图像模型 [英] django upload to image model with foreign key to user

查看:151
本文介绍了django上传到用户的外键图像模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django的扩展用户配置文件,而不是有许多图像字段,我想在我的模型中创建一个新的图像类,我可以上传自动分配给正确的用户的许多图像。然后用户可以查看和编辑他们的所有图像。我基本上停留在最后一部分(查看和编辑)。



我的应用程序被称为ve



models.py

  class Profile(models.Model):
user = models.OneToOneField(User,on_delete = models .CASCADE)
bio = models.TextField(max_length = 500,blank = True)
... etc
$ b $ class图片(models.Model):
image = models.ImageField(upload_to ='profile_image',null = True,default ='profile_image / none / no-img.png')
user = models.ForeignKey(User,on_delete = models.CASCADE,null = True )

forms.py

  class ImagesForm(forms.ModelForm):
image = forms.ImageField(widget = forms.ClearableFileInput(attrs = {'multiple':True}))
class Meta:
model = Images
fields =(
'image',

1。编辑图片



这个设置,上传图片(管理员),但不分配用户。另一个问题是我只能上传/编辑1张图片。

views.py

  @login_required 
@ transaction.atomic
def edit_images(request):$ b $ if request.method =='POST':
images_form = ImagesForm(request.POST, request.FILES)
if image_form.is_valid():
images_form.save()
return redirect('ve:index_account')
else:
pass

else:
images_form = ImagesForm(request.POST,request.FILES)

return render(request,'ve / cp / edit_images_account.html',{
'images_form':images_form,
})

edit_images_account.html

 < form method =postenctype =multipart / form-data> 
{%csrf_token%}
{{images_form.as_p}}
< button type =submit>上传< / button>
< / form>

2。查看图片



views.py

  @login_required 
def index_account(request):
args = {'user':request.user}
return render(request,'ve / cp / index_account.html',args)

index_account.html

 < p>< a href ={%url've:edit_images'%}>编辑您的图片< / a>< / p> 
{%if user.images.images%}
{%for img in user.images%}
< img src ={{user.images.image.url}} ><峰; br>
{%endfor%}
{%else%}
< p>没有图片< / p>

{%endif%}


解决方案

<这里有很多事情要做。所以我们一步一个脚印吧。

首先,您现在已经将图像的用户FK设置为​​null。有这样的用例吗?如果不是,我会建议删除。每个图像应该属于一个用户,对不对?所以删除null。

  user = models.ForeignKey(User,on_delete = models.CASCADE)

其次,一旦你做了这个改变,你可能会注意到表单不再有效,因为它也需要一个用户。您可以执行以下操作:

  images_form = ImagesForm(request.POST,request.FILES,initial = {'user':request。用户})

这应该填写表单中的用户FK,您可以上传一个与用户绑定的图像。但是既然你最终想要上传几个文件,我鼓励你只使用一个正常的形式(如链接的例子),而不是一个的ModelForm 按照说明给出提示如何上传表单中的多个文件。所以当你循环访问列表中的文件时,你必须将每个文件保存在模型中。由于 ModelForm 特别绑定到一个模型实例,所以最好使用一个常规的表单,并编写额外的代码来将文件保存在多个实例中,因为这就是你所需要的。

I'm using Django's Extended User Profile and instead of having many image fields I want to make a new Images class in my models that I can upload many images which automatically get assigned to the right user. Then the user can view and edit all their images. I'm basically stuck on the last part (view and edit).

My app is called ve

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    ... etc   

class Images(models.Model):
    image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png')
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

forms.py

class ImagesForm(forms.ModelForm):
    image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    class Meta:
        model = Images
        fields = (
            'image',
        )

1. Edit Image(s)

This setup, uploads image (in admin) but doesn't assign the user. Another problem is I can only upload/edit 1 image.

views.py

@login_required
@transaction.atomic
def edit_images(request):
    if request.method == 'POST':
        images_form = ImagesForm(request.POST, request.FILES)
        if images_form.is_valid():
            images_form.save()
            return redirect('ve:index_account')
        else:
            pass

    else:
        images_form = ImagesForm(request.POST, request.FILES)

    return render(request, 've/cp/edit_images_account.html', {
        'images_form': images_form,
    })

edit_images_account.html

    <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ images_form.as_p }}
    <button type="submit">Upload</button>
    </form>

2. View Image(s)

views.py

@login_required
def index_account(request):
    args = {'user': request.user}
    return render(request, 've/cp/index_account.html', args)

index_account.html

<p><a href="{% url 've:edit_images' %}">Edit your images</a></p>
            {% if user.images.images %}
                {% for img in user.images %}
                <img src="{{ user.images.image.url }}"><br>
                {% endfor %}
            {% else %}
            <p>No images</p>

            {% endif %}

解决方案

There is a lot going on here. So let's take things one step at a time.

First, you currently have set user FK for the image to null. Is there a use case for this? If not I would recommend that remove that. Each image should belong to a user, right? So remove null.

user = models.ForeignKey(User, on_delete=models.CASCADE)

Second, once you make that change you'll probably notice that the form no longer is valid, because it requires a user as well. You can do the following

images_form = ImagesForm(request.POST, request.FILES, initial={'user': request.user})

That should fill in the user FK in the form and you'd be able to upload one image which is tied to a user.

But since you ultimately wanted to upload several files I'd encourage you to just use a normal form (like in the link example) instead of a ModelForm. The following instructions gives a hint on how to upload several files in a form. So when you loop through the files in the list you'd have to save each one in the model. Since the ModelForm is specifically tied to a single model instance it's better to use a a regular form and write the extra code to save the files in multiple instances, since that's what you need.

这篇关于django上传到用户的外键图像模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆