表单django中与模型数据库的自动关系

问题描述 投票:0回答:1

我需要为电影添加评论

电影模特:

class Film(models.Model):
    AGE = ((0, "0+"), (1, "6+"), (2, "12+"), (3, "16+"), (4, "18+"))
    name = models.CharField(max_length=50)
    description = models.TextField()
    year = models.PositiveIntegerField()
    age = models.IntegerField(, choices=AGE, default=0)
    slug = models.SlugField(max_length=50, unique=True, blank=True)
    image = models.ImageField()
    image.short_description = "Image"
    genre = models.ManyToManyField("Genre", related_name="films")
    trailer = models.URLField(, blank=True)
    time = models.PositiveIntegerField()

    def save(self, *args, **kwargs):
        def slug_create(name, year):
            return "".join((slugify(name), str(year)))
        self.slug = slug_create(self.name, self.year)
        super().save(*args, **kwargs)

评论模型:

class Comment(models.Model):
   user_name = models.CharField(max_length=25)
    text_comment = models.TextField()
    data = models.DateField(auto_now_add=True)
    vefiried = models.BooleanField(blank=True, default=False)
    film = models.ForeignKey(to='Film', on_delete=models.CASCADE, blank=True, null=True)

和评论表:

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['user_name', 'text_comment']
        widgets = {
            'user_name': forms.TextInput(attrs={'class': 'form-control col-3', 'placeholder': 'Name'}),
            'text_comment': forms.Textarea(attrs={'class': 'col-12 my-2', 'rows': '10', 'placeholder': 'Comment'}),
    }

我有自动创建关系电影与评论的问题。用户只能在电影下写评论,所以我每次都有slug,我不知道如何联系它。

python django
1个回答
1
投票

你应该从你的角度看你的电影pk。然后从save覆盖CommentForm方法以链接您的电影。

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['user_name', 'text_comment']
        widgets = {
            'user_name': forms.TextInput(attrs={'class': 'form-control col-3', 'placeholder': 'Name'}),
            'text_comment': forms.Textarea(attrs={'class': 'col-12 my-2', 'rows': '10', 'placeholder': 'Comment'}),
        }

    def save(self, film=None):
        self.instance.film = film
        super().save()

在你看来,在form.save(film)之后调用form.is_valid()

© www.soinside.com 2019 - 2024. All rights reserved.