Ich versuche eine Social Web App mit django zu erstellen. Ich habe ein Formular erstellt, mit dem ein Benutzer eine Frage beantworten kann. Alles funktionierte gut, aber wenn ich Form ohne Inhalt (leere Form) einreichen, ich habe einen Fehlerdjango: UnboundLocalError lokale Variable, auf die vor der Zuweisung verwiesen wird
(Unbound Local error "local variable 'new_answer' referenced before assignment")
Ich bin neu zu django und ich weiß nicht viel über diese so dass jede Hilfe wird sehr nett. hier ist meine Ansicht Code:
def question_detail(request, pk):
question=get_object_or_404(Question, pk=pk)
#list of active answers for this question
answers = question.answers.filter(active=True)
answer_form = AnswerForm()
if request.method=='POST':
#a comment was posted
answer_form = AnswerForm(data=request.POST or None)
if answer_form.is_valid():
new_answer= answer_form.save(commit=False)
new_answer.question = question
u=request.user
new_answer.name = u
new_answer.save()
else:
answer_form = AnswerForm()
new_answer = False
question_tags_ids = question.tags.values_list('id', flat=True)
similar_questions = Question.objects.filter(tags__in = question_tags_ids)\
.exclude(id=question.id)
similar_questions = similar_questions.annotate(same_tags=Count('tags'))\
.order_by('-same_tags','-created')[:4]
return render(request,'dashboard/post/detail.html',
{'question':question,
'answer_form':answer_form,
'new_answer': new_answer,
'similar_questions':similar_questions})
dank ich Ihren Vorschlag versucht, und es funktioniert jetzt Gut. – Ali