繁体   English   中英

将当前 product_id 传递给 Django 中的 Model

[英]Pass current product_id to a Model in Django

我正在尝试通过开发一个简单的页面来尝试 django,人们可以在其中询问有关产品的信息

这是我的 model,我可以在管理区域创建产品,显示产品页面,然后表单显示字段 email 和文本。

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

但我不知道如何告诉 model 问题必须保存到哪个产品 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,)))

和 URL

urlpatterns = patterns('products.views',
    (r'^products/$', 'index'),
    (r'^products/(?P<product_id>\d+)/$', 'detail'),
    (r'^products/(?P<product_id>\d+)/question/$', 'question')
)

现在,如果我在问题 model(问号所在的位置)的产品外键的默认属性中输入“1”,它就可以工作,它将问题保存到产品 ID 1。但我不知道该做什么做使它保存到当前产品。

您可以:

发送product_id作为表单值

表单中的product外键设置为隐藏字段,并将其值设置为detail视图中产品的主键值。 这样,您的question视图 URL 和 arguments 中就不需要product_id ,因为 ID 将与POST数据一起传递。 (示例见链接

Id 会使用此选项,因为您会有更清晰的question URL 并且您可以在产品的表单中进行更多验证。

或者

通过 URL 发送product_id

detail视图中使用reverse来构建表单action属性或使用url模板标记在表单模板中构建action属性。 这样,您的question URL 和 arguments 中需要product_id但您的QuestionForm中不需要product字段。 然后在question视图中只需获取产品实例并将其设置为Question上的 FK 值。


例子:

products/detail.html中使用url模板标签:

<form action="{% url question product.pk %}" method="post">
 .... 
</form>

或者在detail视图中使用reverse

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, 
        'product': p, 
        'action': reverse("question", args=[p.pk,]),
        'form' : f},
    context_instance = RequestContext(request))

你的模板:

<form action="{{ action }}" method="post">
 .... 
</form>

无论哪种方式,您的question视图都需要添加一行,该行实际上将产品实例设置为Question属性:

def question(request, product_id):
    ...
    new_question.product = p

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM