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()
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
ifstatements, and only onereturnright at the most deeply nested bit. What happens if it’s not a POST, or if formais not valid, or formpis not valid? Django expects a view to return a response in all circumstances, so you need a return no matter what happens.