I do apologise for all the questions I'm posting today, but I'm at my wits end on this one.
I'm trying to make a Q&A thing for a video site, and I'm trying to get the question to submit via AJAX.
Question model:
class Question(models.Model):
user = models.ForeignKey(User, editable=False)
video = models.ForeignKey(Video, editable=False)
section = models.ForeignKey(Section, editable=False)
title = models.CharField(max_length=255)
description = m开发者_如何转开发odels.TextField(null=True, blank=True)
ModelForm:
class QuestionForm(ModelForm):
def __init__(self, video, *args, **kwargs):
super(QuestionForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['section'].queryset = Section.objects.filter(video=video)
class Meta:
model = Question
POST parameters sent by jQuery's AJAX request (the video parameter is added by the Javascript code):
section=6&title=test&description=test&video=1
And finally, here's the view I'm working on to handle the submit:
def question_submit(request):
u = request.user
if u.is_authenticated():
q=QuestionForm(request.POST)
if q.is_valid():
logger.debug("YES!")
else:
logger.debug("NO!")
f=q.save(commit=False)
f.user=u
f.video_id=int(request.POST['video'])
f.save()
return HttpResponse("OK")
else:
return JsonResponse({'failed': 'You are not logged in. Try logging in in a new tab, then re-submit your question.'})
As suggested by the docs, I'm saving with commit=false so that I can modify the object.
I have two problems:
When it reaches q.is_valid(), it throws the error "'QuestionForm' object has no attribute 'cleaned_data'".
If I take out the q.is_valid() bit, f.save() succeeds, but it inserts a blank row into the database.
To anyone who can help, I owe you my sanity.
You aren't passing in video in the view:
forms.py
def __init__(self, video, *args, **kwargs):
views.py
q=QuestionForm(request.POST)
as video is a positional argument, I'd imagine it is interpreting request.POST as the video?
You could change video to a keyword argument:
def __init__(self, video=None, *args, **kwargs):
if video:
...
as mordi metions, you should check if a) it's a valid POST, and b) it's an ajax request
def question_submit(request):
if request.method == "POST" and request.is_ajax():
...
It's look like your request.POST is empty. Are you sure that the data is sent by POST method?, check
if request.method == 'POST:
or use
q=QuestionForm(request.REQUEST)
to get POST/GET data.
精彩评论