Django form and upload image on one page

I am trying to figure out how to upload an image and get user input in one form. My models:

class Image(models.Model):
    artist = models.ForeignKey('Artist')
    image = models.ImageField(upload_to="assets/images")

class Album(models.Model):
    artist = models.ForeignKey(Artist,null=True)
    notes = models.CharField(max_length = 50)
    display = models.BooleanField()
    date_created = models.DateTimeField(auto_now_add=True)

My forms

class AlbumForm(forms.ModelForm):
    class Meta:
        model = Album
        fields = ('notes',)

class ImageForm(forms.ModelForm):
    class Meta:
        model = Image
    exclude = ('artist')`

I think my opinion is wrong and how can I convey two forms to a template? What would a template look like to render two forms? I want to use one submit button.

def create(request):
    form1 = ImageForm(request.POST, request.FILES or None)
    form2= AlbumForm(request.POST or None)
    if form2.is_valid() and form1.is_valid():
        image = form1.save(commit=False)
        image.artist = Artist.objects.get(pk=3)
        image.save()
        album = form2.save(commit=False)

        album.save()
        if 'next' in request.POST:
            next = request.POST['next']
        else:
            next = reverse('art_show')
        return HttpResponseRedirect(next)
    return render_to_response(
        'art/create.html',
        {'ImageForm':form1},
        { 'AlbumForm': form2},
        context_instance = RequestContext(request)
)
+3
source share
1 answer

Perhaps you could do something like this:

<form action="." method="post" enctype="multipart/form-data">
    {{ImageForm.image}} <br />
    {{AlbumForm.notes}} <br />
    {{AlbumForm.display}} <br />
    ...
    <input type="submit" value="Save" />
</form>

This will return the form1 and form2 objects in your request.POST object.

views.py:

...
return render_to_response('art/create.html', 
    {'ImageForm': form1, 'AlbumForm': form2}, 
    context_instance = RequestContext(request)
)

Or you can do it:

...
return render_to_response('art/create.html',
    locals(), 
    context_instance = RequestContext(request)
)

, , , , , - . , .

EDIT: ​​ , , . .

+3

All Articles