Search code examples
djangodjango-modelsdjango-viewsdjango-formsdjango-generic-views

how to stop create view if already created django


please help me in making this application in django project

Here is models.py file code

from django.db import models
from bio.models import Profile

class Question(models.Model):
   name = models.TextField(max_length=500)

   def __str__(self):
     return self.name

class Answer(models.Model):
  question = models.ForeignKey(Question, related_name='question', on_delete=models.CASCADE)
  profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE)
  text = models.TextField(max_length=400)
  created_on = models.DateTimeField(auto_now_add=True,null=True)

  def __str__(self):
    return "{0} on {1}".format(self.question, self.profile)
  
  class Meta:
    db_table = 'answer'
    constraints = [
        models.UniqueConstraint(fields=['profile', 'text', 'question'], name='unique answer')
    ]

  

here is views.py file code

class DetailViewMixin(object):
  details_model = None
  context_detail_object_name = None

  def get_context_data(self, **kwargs):
    context = super(DetailViewMixin, self).get_context_data(**kwargs)
    context[self.context_detail_object_name] = self.get_detail_object()
    return context

  def get_detail_object(self):
    return self.details_model._default_manager.get(pk=self.kwargs['pk'])


class AnswerCreate(DetailViewMixin, CreateView):
  details_model = Question
  context_detail_object_name = 'question'
  model = Answer
  form_class = NewAnswerForm
  template_name = "qna/answer.html"
  success_url = reverse_lazy('qna:list')

  def form_valid(self, form):
    form.instance.profile_id = self.kwargs.get('pk')
    form.instance.question_id = self.kwargs.get('pk')
    return super().form_valid(form)

here is my forms.py code

from django import forms
from .models import Answer

class NewAnswerForm(forms.ModelForm):
  class Meta:
    model = Answer
    fields = ['text',]

  def clean(self):
    try:
        Answer.objects.get(text=self.cleaned_data['text'].lower())
        raise forms.ValidationError('Answer exists!')
    except Answer.DoesNotExist:
        pass

    return self.cleaned_data

where am I going wrong????

I want that if user answers one question then he couldn't answer it again

how can i do form validation if object is already created


Solution

  • Add a UniqueConstraint to Answer so no combination of Question and Profile can be repeated: https://docs.djangoproject.com/en/3.1/ref/models/constraints/#django.db.models.UniqueConstraint