django upload to image model with foreign key to u

2019-04-16 16:48发布

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 %}

1条回答
看我几分像从前
2楼-- · 2019-04-16 17:10

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.

查看更多
登录 后发表回答