如何修复django的modelform保存问题?

时间:2012-07-03 11:56:33

标签: django view model save modelform

我希望能够根据通过引用产品的url传递的参数来保存表单提交的数据(而不是让用户通过下拉列表指定产品)。有关如何实现这一目标的任何想法?

url(r'^products/(?P<product_id>\d+)/reviews/$', 'view_reviews'),
url(r'^products/(?P<product_id>\d+)/add_review/$', 'add_review'), 

def add_review(request, product_id):
    p = get_object_or_404(Productbackup, pk=product_id)
    if request.method == 'POST':
        form = ReviewbackupForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('reserve.views.view_reviews', kwargs={'product_id':p.id}))
    else:
        form = ReviewbackupForm()
    variables = RequestContext(request, {'form': form, 'product_id': product_id})
    return render_to_response('reserve/templates/create_review.html', variables)

RATING_OPTIONS = (
    (1, '1'),
    (2, '2'),
    (3, '3'),
    (4, '4'),
    (5, '5'),
    (6, '6'),
    (7, '7'),
    (8, '8'),
    (9, '9'),
    (10, '10'),
)
class Reviewbackup(models.Model):
    review = models.CharField('Review', max_length = 2000)
    date = models.DateField('date')
    created_on = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    user = models.CharField('Username', max_length =  200)
    rating = models.IntegerField(max_length=2, choices=RATING_OPTIONS)
    product = models.ForeignKey(Productbackup)
    def __unicode__(self):
        return self.review

class ReviewbackupForm(ModelForm):
    class Meta:
        model = Reviewbackup
        fields = ('review', 'rating', 'user', 'date')
        widgets = {
            'review': Textarea(attrs={'cols': 80, 'rows': 7}),
        }

class Productbackup(models.Model):
    website = models.CharField('Product name', max_length = 200)
    website_url = models.URLField('Product URL')
    category = models.ForeignKey(Categories)
    created_on = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    def __unicode__(self):
        return self.website

1 个答案:

答案 0 :(得分:4)

您可以使用form.save(commit=False),并在实例中设置模型的其他属性并再次保存。

在您看来,保存表单时:

if form.is_valid():
    review = form.save(commit=False)
    review.product = p
    review.save()