【发布时间】:2011-05-28 22:29:17
【问题描述】:
我正在尝试通过开发一个简单的页面来尝试 django,人们可以在其中询问有关产品的信息
这是我的模型,我可以在管理区域创建产品,显示产品页面,然后表单会显示字段电子邮件和文本。
class Product(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=100)
text = models.TextField()
class Question(models.Model):
email = models.CharField(max_length=100)
product = models.ForeignKey(Product, default=?, editable=False)
date = models.DateTimeField(auto_now=True, editable=False)
text = models.TextField()
class QuestionForm(ModelForm):
class Meta:
model = Question
但我不知道如何告诉模型问题必须保存到哪个产品 ID。
这是我的观点.py
# other stuff here
def detail(request, product_id):
p = get_object_or_404(Product, pk=product_id)
f = QuestionForm()
return render_to_response('products/detail.html', {'title' : p.title, 'productt': p, 'form' : f},
context_instance = RequestContext(request))
def question(request, product_id):
p = get_object_or_404(Product, pk=product_id)
f = QuestionForm(request.POST)
new_question = f.save()
return HttpResponseRedirect(reverse('products.views.detail', args=(p.id,)))
还有网址
urlpatterns = patterns('products.views',
(r'^products/$', 'index'),
(r'^products/(?P<product_id>\d+)/$', 'detail'),
(r'^products/(?P<product_id>\d+)/question/$', 'question')
)
现在,如果我在问题模型(问号所在的位置)的产品外键的默认属性中输入“1”,它可以工作,它将问题保存到产品 id 1。但我没有知道如何将其保存到当前产品中。
【问题讨论】: