Django form for multiple models failed to return HttpResponse
I am going mad trying to figure this problem out. I have a form which has multiple models. Basically someone writes a story and then puts their username in and this username is associated with that story. It's all pretty basic...apparently not for django. Aside from searching for hours to find something that helps with what are essentially multiple SQL inserts it seems to be impossible. I get the error failed to return HTTPResponseOBject even though I've verified the indentation.
Here is my view:
def submit_story(request):
if request.method == 'POST':
f = request.POST.copy()
sdata = {
'author': f['username']
}
a = AuthorForm()
p = StoryForm(sdata)
if a.is_valid():
a.save()
if p.is_valid():
p.save开发者_如何学Go()
return HttpResponseRedirect('/thanks/')
Here are my models:
class Author(models.Model):
username = models.CharField(max_length=120, unique="True")
email = models.EmailField()
firstname = models.CharField(max_length=500)
lastname = models.CharField(max_length=500)
class Story(models.Model):
title = models.CharField(max_length=1000)
text = models.CharField(max_length=5000)
date = models.DateField()
likes = models.IntegerField()
dislikes = models.IntegerField()
views = models.IntegerField()
author = models.ForeignKey('Author')
Thanks in advance. I changed to django from PHP thinking this would be simpler but this multiple form submission is just plain irritating.
This has nothing to do with multiple models or inserts. The issue should be obvious: you have a set of nested if
statements, and only one return
right at the most deeply nested bit. What happens if it's not a POST, or if form a
is not valid, or form p
is not valid? Django expects a view to return a response in all circumstances, so you need a return no matter what happens.
I agree with Daniel's answer that you need to return a response for all your if branches.
The other problem is that you're not binding the AuthorForm
to any data. In your code, a.is_valid()
will always be False.
Instead of
a = AuthorForm()
You need something like
a = AuthorForm(sdata)
精彩评论