I’m trying to give django a try by developing a simple page where people can ask something about a product
This is my model, i can create products in the admin area, display the product page, and the form shows up with the fields email, and text.
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
But i don’t know how to tell the model which product id the question has to be saved to.
This is my views.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,)))
And the URL
urlpatterns = patterns('products.views',
(r'^products/$', 'index'),
(r'^products/(?P<product_id>\d+)/$', 'detail'),
(r'^products/(?P<product_id>\d+)/question/$', 'question')
)
Righ now it works if i put a “1” in the default attribute for the product foreign key in the question model (where the question mark is), it saves the question to the product id 1. But i don’t know what to do to make it save to the current product.
You can either:
Send
product_idas form valueMake
productforeign key in your form a hidden field and set it’s value to primary key value of the product indetailview. This way you don’t need aproduct_idin yourquestionview URL and arguments since the ID will be passed withPOSTdata. (see link for examples)Id would use this option, since you’d have cleaner
questionURL and you could do more validation in your form on the product.or
Send
product_idthrough URLUse reverse in your
detailview to build the formactionattribute or useurltemplate tag to build theactionattribute in form template. This way you needproduct_idin yourquestionURL and arguments but you don’t needproductfield in yourQuestionForm. Then inquestionview simply get the product instance and set it as FK value onQuestion.Example:
Using
urltemplate tag inproducts/detail.html:Or use
reverseindetailview:your template:
Either way your
questionview would need a line added which actually sets product instance toQuestionattribute: