0

I am working on a Hybrid of Quora and StackOverflow clone. I have made an "add_answer" view for letting me add answers to the questions but for some reasons it is showing the integrity error: Here's the error image
But when I add through admin panel then it adds answer in the database. What is wrong? The code is as follows:

  1. models.py:
    class Answer(models.Model):  
        content = models.TextField()  
        user = models.ForeignKey(User,on_delete=models.CASCADE)  
        question = models.ForeignKey(Question,on_delete=models.CASCADE,blank=False)  
        created = models.DateTimeField(auto_now_add=True)  
        upvotes = models.PositiveIntegerField(default=0)  
        is_active = models.BooleanField(default=True)  

        def __str__(self):  
            return '{}\'s Answer'.format(self.user.username)  

        class Meta:  
                ordering = ('-upvotes','-created')  
  1. forms.py:
    class AnswerForm(forms.ModelForm):
        content = forms.CharField(widget=forms.Textarea,help_text='Your Answer in Detail. Note: MarkDown is enabled.')

        class Meta:
            model = Answer
            fields = ['content']

        def __init__(self,author,question,*args,**kwargs):
            super().__init__(*args,**kwargs)
            self.user = author
            self.question = question
  1. "add_answer" view (views.py):
@login_required
def add_answer(request, pk):
    ques = get_object_or_404(Question, pk = pk)
    if request.method == 'POST':
        form = AnswerForm(request.user,ques,request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            answer = form.save(commit=False)
            answer.content = cd['content']
            answer.save()
            messages.success(request,'Success! Your Answer has been added!')
            return redirect('forum')
        else:
            messages.error(request,form.errors)
    else:
        form = AnswerForm(request.user,ques)
    return render(request,'discussion/answer_create.html',{'form':form})  

  1. answer_create.html (template):

{% extends 'base.html' %}
{% load markdownify %}
{% block title %} Add Answer {% endblock %}

{% block header %}    
    <h2 class="display-5" style="font-family: x-locale-heading-primary,zillaslab,Palatino,Palatino Linotype,x-locale-heading-secondary,serif;">
        Add Answer:
    </h2>  
{% endblock %}

{% block content %}
    {% if form.errors %}
    <h4 class="alert alert-primary alert-warning" role="alert">Errors:<br> {{form.errors}}  <hr></h4>
    {% endif %}
    <form action="" method="POST">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit">
    </form>
{% endblock %}

It would be really grateful if somebody helps me out.

1 Answer 1

1

You forgot to assign the question instance to answer model

answer.question = ques

ques = get_object_or_404(Question, pk = pk)
if form.is_valid():
   cd = form.cleaned_data
   answer = form.save(commit=False)
   answer.question = ques
   answer.content = cd['content']
   answer.save()

you can also do the following in model form init

def __init__(self,author,question,*args,**kwargs):
   super().__init__(*args,**kwargs)
   self.form.instance.user = author
   self.form.instance.question = question
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks your solution is working. But can I know the reason why it was not working before because previously, I what I did was I passed question and the user at the time of initialization of form only (like: AnswerForm(request.user,ques,request.POST) ) then why was it not working before?
In the Form, You used self.user = author which set user to form instance, not the actual model, so it should be self.form.instance.user = author.,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.