Given the example code below, what would be the best way to validate that there are no duplicate code
per account
?
Model
class Post(models.Model):
account = models.ForeignKey('Account', editable=False)
code = models.CharField()
class Meta:
unique_together = ('account', 'code')
Form
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('code',)
View
def post_add(request):
try:
account = Account.objects.get(membership__user=request.user)
except:
login_url = reverse('login') + ('?next=%s') % request.path
return HttpResponseRedirect(login_url)
post = Post()
if request.method == "POST":
post_form = PostForm(request.POST, prefix='post')
if post_form.is_valid():
post = post_form.save(commit=False)
post.account = account
post.save()
# other code
I've found answers suggesting something similar to using clean_code()
but account
doesn't seem to exist at that point. What do you suggest?