Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution(models.Model):
- '''
- Represents a solution to a specific problem.
- '''
- name = models.CharField(max_length=50)
- problem = models.ForeignKey(Problem)
- description = models.TextField(blank=True)
- date = models.DateTimeField(auto_now_add=True)
- class Meta:
- unique_together = ("name", "problem")
- class SolutionForm(forms.ModelForm):
- class Meta:
- model = Solution
- exclude = ['problem']
- def validate_unique(self):
- exclude = self._get_validation_exclusions()
- exclude.remove('problem') # allow checking against the missing attribute
- try:
- self.instance.validate_unique(exclude=exclude)
- except ValidationError, e:
- self._update_errors(e.message_dict)
- class SolutionForm(forms.ModelForm):
- class Meta:
- model = Solution
- exclude = ['problem']
- def clean(self):
- cleaned_data = self.cleaned_data
- try:
- Solution.objects.get(name=cleaned_data['name'], problem=self.problem)
- except Solution.DoesNotExist:
- pass
- else:
- raise ValidationError('Solution with this Name already exists for this problem')
- # Always return cleaned_data
- return cleaned_data
- class SolutionForm(forms.ModelForm):
- class Meta:
- model = Solution
- exclude = ['problem']
- def clean(self):
- cleaned_data = self.cleaned_data
- if Solution.objects.filter(name=cleaned_data['name'],
- problem=self.problem).exists():
- raise ValidationError(
- 'Solution with this Name already exists for this problem')
- # Always return cleaned_data
- return cleaned_data
- class SolutionForm(forms.ModelForm):
- class Meta:
- model = Solution
- exclude = ['problem']
- def _get_validation_exclusions(self):
- exclude = super(SolutionForm, self)._get_validation_exclusions()
- exclude.remove('problem')
- return exclude
- def your_view(request):
- if request.method == 'GET':
- form = SolutionForm()
- elif request.method == 'POST':
- problem = ... # logic to find the problem instance
- solution = Solution(problem=problem) # or solution.problem = problem
- form = SolutionForm(request.POST, instance=solution)
- # the form will validate because the problem has been provided on solution instance
- if form.is_valid():
- solution = form.save()
- # redirect or return other response
- # show the form
- class Solution(models.Model):
- ...
- def save(self, *args, **kwargs):
- self.clean()
- return super(Solution, self).save(*args, **kwargs)
- def clean():
- # have your custom model field checks here
- # They can raise Validation Error
- # Now this is the key to enforcing unique constraint
- self.validate_unique()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement