H
H
happiva2019-06-20 12:39:21
Django
happiva, 2019-06-20 12:39:21

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')

Vote Model
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

1 answer(s)
A
Andrew, 2019-06-20
@happiva

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')

I recommend to see how the like system works here (* may be blocked in Russia)
If the link above does not work (and there is no VPN), the option is to look at GitHub
Here are the source codes of the application from the link above.
Perhaps, without explanation, it will not be very clear what is implemented here and why exactly,
but the project is good as a sample.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question