Question

I'm having really hard time trying to make this code work. I'm using Python 2.7 and Django 1.3

When I try to submit the form, it leads me to the error page, like the form has something wrong.

I have a model class with an image field:

class Livro (models.Model):
    Titulo = models.CharField(max_length=200)
    Autor = models.CharField(max_length=200)
    Genero = models.CharField(max_length=100)
    Editora = models.CharField(max_length=200)
    Capa = models.ImageField(upload_to='media', blank=True, null=True)
    ISBN = models.CharField(max_length=200)
    Serie = models.CharField(max_length=200)
    Data = models.DateField()
    Tipocapa = models.CharField(max_length=100)
    Lingua = models.ForeignKey(PropObra,'Lingua', related_name="lingualivro")

    def __unicode__(self):
        return self.Titulo

This is the view I have implemented:

def salvalivro(request):
    if request.method == 'POST': 
        form = LivroForm(request.POST, request.FILES)
    if form.is_valid():
        form = LivroForm()
        if not form.is_valid(): 
            return HttpResponseRedirect('/erro/')
    return render_to_response('salvalivro.html', {'form': form,}, context_instance=RequestContext(request))

And this is the code I have inside the template:

<form enctype="multipart/form-data" method="POST" action="/salvalivro/" >{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Salvar" />
</form>

Maybe the error is in front of my nose, but I've been working on this for about three days and had no result. I've read Django's documentation and many other questions around StackOverflow, but still got nothing. I really need some help...

Was it helpful?

Solution

Your view code doesn't make a whole lot of sense. You're creating a new instance of the form after checking that the previously created one is valid, then redirecting to an error page if it's not. So, your code looks to me like it's working as expected as described in your question.

Try this view instead (assumes Django 1.3):

def salvalivro(request):
    form = LivroForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            form.save() #or whatever else you need
    return render(request, 'salvalivro.html', {'form': form})

OTHER TIPS

Your view is very odd. If it's a post, you instantiate the form using the post data. Then, you check it's valid: then you re-instantiate the form with no data and check if it isn't valid! Of course, at that point it can't ever be valid, because the second instantiation has no data. So, naturally, it always redirects - but again, because you're redirecting to a different view, you'll never see the actual error messages generated by the form.

You should look more closely at the standard documentation on using a form in a view - it has the exact pattern you should follow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top