[英]Dynamically add fields to a ModelForm in Django
我有幾種型號:產品,評論和評論。 產品有評論,評論有評論。 我寫的代碼如下:
class Comment(models.Model):
author = models.CharField(max_length=50)
content = models.TextField(max_length = 200)
date = models.DateTimeField(auto_now_add=True, blank = True)
def __unicode__(self):
return '%s on %s' % (self.author, self.date)
class Review(models.Model):
stars = models.FloatField()
author = models.CharField(max_length = 50)
title = models.CharField(max_length = 50)
description = models.TextField(max_length = 500)
date = models.DateTimeField(auto_now_add = True, blank = True)
video = models.FileField(upload_to='upload', null = True, blank = True)
image = models.FileField(upload_to='upload', null = True, blank = True)
comments = models.ManyToManyField(Comment)
def __unicode__(self):
return '%s by %s' % (self.author, self.title)
class Product(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(max_length = 500)
image = models.FileField(upload_to='upload', null = True, blank = True)
reviews = models.ManyToManyField(Review)
def __unicode__(self):
return '%s' % (self.name)
同樣,我有基於模型的ModelForms,如下所示:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
exclude = ['author']
labels = {
'content': _('Comment:'),
}
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = ['reviews']
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
exclude = ['author', 'comments']
直到這里,一切都很好。 現在,我希望能夠動態地向產品添加問題。 因此,當管理員創建新產品時,他將能夠向其添加產品特定的問題(例如,產品的顏色如何等)(他想要多少個問題-動態的)。 然后,當用戶去查看產品時,他將看到管理員詢問的產品特定問題,他將能夠回答這些問題。
因此,我的主要問題是: 如何動態地向數據庫模型添加字段? b。 如何在評論中處理這些問題? 一個產品可能有多個評論,每個評論都由不同的人撰寫,每個評論都應顯示這些特定於產品的問題。
謝謝!
為了讓您快速舉例說明我發表的評論(使用記事本完成,也許有錯字):
class Comment(models.Model):
pass
class Review(models.Model):
comments = models.ManyToManyField(Comment)
class Product(models.Model):
reviews = models.ManyToManyField(Review)
class Question(models.Model):.
content = models.TextField(max_length = 500)
product = models.ForeignKey(Product)
class QuestionAnswer(models.Model):
content = models.TextField(max_length = 500)
review = models.ForeignKey(Review)
question = models.ForeignKey(Question)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.