Я играю с django-survey из jessykate (https://github.com/jessykate/django-survey) и изменяет models.py. Теперь метод save() больше не работает, и я не понимаю, почему это так.ModelForm save() не работает после смены модели
models.py (см комментарий #)
class Response(models.Model):
'''
a response object is just a collection of questions and answers with a
unique interview uuid
'''
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
survey = models.ForeignKey(Survey)
# interviewer = models.CharField('Name of Interviewer', max_length=400)
# interviewee = models.CharField('Name of Interviewee', max_length=400)
# conditions = models.TextField('Conditions during interview', blank=True, null=True)
# comments = models.TextField('Any additional Comments', blank=True, null=True)
interview_uuid = models.CharField("Interview unique identifier", max_length=36)
def __unicode__(self):
return ("response %s" % self.interview_uuid)
views.py (оригинал)
def SurveyDetail(request, id):
survey = Survey.objects.get(id=id)
category_items = Category.objects.filter(survey=survey)
categories = [c.name for c in category_items]
print 'categories for this survey:'
print categories
if request.method == 'POST':
form = ResponseForm(request.POST, survey=survey)
if form.is_valid():
response = form.save()
return HttpResponseRedirect("/confirm/%s" % response.interview_uuid)
else:
form = ResponseForm(survey=survey)
print form
# TODO sort by category
return render(request, 'survey.html', {'response_form': form, 'survey': survey, 'categories': categories})
forms.py (см комментарий #)
class ResponseForm(models.ModelForm):
class Meta:
model = Response
# fields = ('interviewer', 'interviewee', 'conditions', 'comments')
[...]
def save(self, commit=True):
''' save the response object '''
response = super(ResponseForm, self).save(commit=False)
response.survey = self.survey
response.interview_uuid = self.uuid
response.save()
'''
create an answer object for each question and associate it with this
response.
'''
for field_name, field_value in self.cleaned_data.iteritems():
if field_name.startswith("question_"):
# warning: this way of extracting the id is very fragile and
# entirely dependent on the way the question_id is encoded in the
# field name in the __init__ method of this form class.
q_id = int(field_name.split("_")[1])
q = Question.objects.get(pk=q_id)
if q.question_type == Question.TEXT:
a = AnswerText(question = q)
a.body = field_value
elif q.question_type == Question.RADIO:
a = AnswerRadio(question = q)
a.body = field_value
elif q.question_type == Question.SELECT:
a = AnswerSelect(question = q)
a.body = field_value
elif q.question_type == Question.SELECT_MULTIPLE:
a = AnswerSelectMultiple(question = q)
a.body = field_value
elif q.question_type == Question.INTEGER:
a = AnswerInteger(question = q)
a.body = field_value
print "creating answer to question %d of type %s" % (q_id, a.question.question_type)
print a.question.text
print 'answer value:'
print field_value
a.response = response
a.save()
return response
Так что же происходит когда я сохраняю опрос, я получу ту же самую страницу со всеми моими вводами вместо страницы подтверждения.
Любые подсказки?
Похоже, ваша форма недействительна, поэтому, когда она попадает в 'if form.is_valid()' условно, она пропускает ее (chuck in a assert для подтверждения этого), и поэтому метод save() даже не называемый. Если это действительно неверная форма, вам нужно проверить ошибки формы, чтобы узнать, почему. – ptr
Проблема заключается в 'fields = ('интервьюер', 'интервьюируемый', 'условия', 'комментарии')'. Если я добавлю интервьюера и собеседника обратно в models.py и задаю поля в forms.py, это сработает. Являются ли 'fields' обязательными в forms.py? –
«Я добавляю это, и проблема уходит» не означает, что проблема сосредоточена вокруг строки, которую вы добавляете/удаляете, это всего лишь показатель того, с чего начать искать. Я хотел знать ошибки формы, потому что без обратной трассировки, это самая описательная информация, которую вы получите, почему форма не использует 'save()'. Я добавлю более подробный ответ в качестве ответа. – ptr