开发者

Django Form and Image Upload on same page

I'm trying to figure out how to upload an image and get user input on a single form. My models:

class Image(models.Model):
    artist = models.ForeignKey('Artist')
    image = model开发者_开发百科s.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 view is wrong and how would I pass the two forms to the template? What would the template look like to render the two forms? I want to use a single 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)
)


You could probably 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 both 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 could do this:

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

Although, the second one will add all variables your function uses so you should make sure that if you use it that your function won't be using any builtin names. Usually uncommon, but you should just make sure.

EDIT: Added a submit button to make it clear you only need one. Also added the view's response.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜