簡體   English   中英

為Django標記自定義標簽

[英]tagging a custom tag for Django

您好,我正在django中創建我的第一個項目,該項目正在創建reddit克隆。 我不確定如何設置模型,尤其是設置標簽部分。 像reddit一樣,我希望用戶能夠標記他們創建的社區。 我發現了許多標記應用程序,使您可以標記管理員創建的類別。 但是我希望我的用戶標記他們所做的類別。

class Post(models.Model):
       created_at = models.DateTimeField(auto_now_add = True)
       title = models.CharField(max_length = 100)
       content = models.TextField()
       url = models.URLField(max_length=250, blank=True)
       image = models.ImageField(upload_to="images", blank=True, null=True)
       views = models.IntegerField(dfault=0)
       likes = models.IntegerField(dfault=0)




class Category(models.Model): 
    name = models.CharField(max_length=100, unique=True)

您應該在Post模型中添加多對多關系

class Post(models.Model):
       created_at = models.DateTimeField(auto_now_add = True)
       title = models.CharField(max_length = 100)
       content = models.TextField()
       url = models.URLField(max_length=250, blank=True)
       image = models.ImageField(upload_to="images", blank=True, null=True)
       views = models.IntegerField(dfault=0)
       likes = models.IntegerField(dfault=0)
       # Add a m2m field named categories
       categories = models.ManyToManyField(Category)

這樣,您可以使用-獲取與帖子相關的所有相關類別的列表。

post_object.categories.all()

對於添加標簽的表格,您可以使用-

class TagForm(forms.Form):
    tags = forms.MultipleChoiceField(
                                 widget=forms.SelectMultiple,
                                 choices=tag_options,
                                 required=True)

其中tag_options是一個元組的元組,其中包含從Category.objects.all()獲得的各種標簽

根據我的理解,您需要了解的是Many2Many關系。 一個帖子可以有很多類別,一個類別可以有很多帖子。

categories = models.ManyToManyField(
    Category)

要進一步閱讀,請閱讀此 .. :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM