Reputation: 2270
I have following model:
class ArticleUser(models.Model):
email = models.EmailField(max_length=200)
fullname = models.CharField(max_length=200)
article = models.ForeignKey(Article)
create_time =models.DateTimeField()
def save(self, *args, **kwargs):
''' On save, update timestamps '''
self.create_time = datetime.datetime.utcnow().replace(tzinfo=utc)
super(ArticleUser, self).save(*args, **kwargs)
class Meta:
unique_together = (('email','article'),)
I am passing the article_id through the url:
url(r'^articlebuffer/(?P<mid>\d+)/$',views.articlebuffer, name="articlebuffer"),
I need to use the article_id in the validation of the form so that article and email are unique together. How can I achieve it in the formset as well as in form
Here is my view using formset:
def articlebuffer(request,mid):
ArticleBufferFormSet = modelformset_factory(ArticleUser,exclude=('article','create_time'))
if request.method == 'POST':
formset = ArticleBufferFormSet(request.POST)
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.article_id = mid
try:
instance.save()
except:
error="Unique Constraint Error"
return HttpResponseRedirect('')
else:
formset = ArticleBufferFormSet(queryset= ArticleUser.objects.none())
return render (request, 'tracking/createarticlebuffer.html',{'formset':formset,
})
Upvotes: 0
Views: 67
Reputation: 2872
Include it with your POST data when you create a new ArticleBufferFormSet
formset = ArticleBufferFormSet(dict(request.POST.items() + {'article_id': article_id}))
Upvotes: 1