Answer the question
In order to leave comments, you need to log in
How to fix “NOT NULL constraint failed”?
How can I create an object in Django with two OneToOne fields (user, article), I understand how to populate the custom field (self.request.user) but the article field in which should contain the "slug" of the object (article) on which we are, I don't understand I
really count on your support, I'm still quite a beginner.
Thanks in advance
class CreateVote(CreateView):
model = Vote
template_name = 'art_detail.html'
fields = ()
def form_valid(self, form):
form.author_id = self.request.user
form.art_ident = self.kwargs['slug']# проблема вот тут ,как исправить ее , я не знаю
return super(CreateVote, self).form_valid(form)
def get_success_url(self):
return reverse('art_detail')
class Vote(models.Model):
author_id = models.ForeignKey(
MyUser,
on_delete=models.CASCADE
)
art_ident = models.OneToOneField(
Art,
on_delete=models.CASCADE,
)
data_vote = models.DateTimeField(
auto_now=True
)
objects = VoteManager()
class Meta:
unique_together = ('art_ident', 'author_id')
Answer the question
In order to leave comments, you need to log in
It is great for implementing likes (Votes) GenericForeignKey
- it allows you to refer to various objects and in general this solution is more universal.
class Like(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='likes',
on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question