There is a question, under it a form for adding comments. I try to implement through AJAX. I do not know to pass the id of the current post to get the id of the post to which the response is added.
models.py:
class Question(models.Model): title = models.CharField(max_length=200) text = models.TextField() class Answer(models.Model): text = models.TextField() added_at = models.DateTimeField(auto_now=True) question = models.ForeignKey(Question) author = models.ForeignKey(User, blank=True, null=True)
forms.py
class AnswerForm(forms.Form): text = forms.CharField(widget=forms.Textarea, label='Text', max_length=100, required=True, min_length=2) question = forms.IntegerField(label='Text Answer', widget=forms.HiddenInput, required=False)
views.py
def question_details(request, id): question = get_object_or_404(Question, id=int(id)) form = AnswerForm(initial={'question': question.id}) return render(request, 'question/question.html', {'question': question, 'form': form, 'answers': question.answer_set.all(), 'username': request.user, 'tags': get_all_tags(), }) def add_answer(request): if request.method == 'POST': answer_text = request.POST.get('text') response_data = {} answer = Answer(text=answer_text, author=request.user, question= ???) answer.save() response_data['result'] = 'Create post successful!' response_data['answerpk'] = answer.pk response_data['text'] = answer.text response_data['author'] = answer.author.username return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" )
urls.py
... url(r'^question/(?P<id>[0-9]+)/$', views.question_details, name='question' url(r'^add-answer/$', views.add_answer, name='adding new answer via ajax requests'),), ....
main.js
.... $('#answer-form').on('submit', function(event) { event.preventDefault(); console.log("form submitted!"); add_comment(); }); function add_comment() { console.log("create post is working!");// sanity check $.ajax({ url : "add-answer/", // the endpoint type : "POST", // http method data : { text : $('#id_text').val() }, // data sent with the post request ....