2

我有一个表单,它获取有关项目的信息并将其保存到数据库中。我试图允许用户使用新的/不同的信息编辑该表单并再次保存。我在尝试让它工作时遇到了一些困难。我认为问题在于,当 Django 验证数据时,它发现项目的 slug 和唯一 id 已经存在并且不允许它验证数据,但我也不完全确定这一点。非常感谢您的帮助。谢谢。

#view
def edit_item(request, item_id):
    if request.method == 'POST':
        item = Item.objects.get(id=item_id)
        form = AddItem(request.POST,instance=item)
        if form.is_valid():
            item = form.save(commit=False)
            item.user = request.user
            item.is_active = True
            item.slug = slugify(item.name)
            item.save()
            return HttpResponseRedirect('thanks.html')
        else:
            form = AddItem(instance=item )
            return render_to_response('forsale.html', locals(), context_instance=RequestContext(request))

#form
class AddItem(forms.ModelForm):
    name = forms.CharField(label="Title")

    class Meta:
        model = Item
        exclude = ('user','slug','is_active',)

#model
class Item(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=30)
    slug = models.SlugField(max_length=50, unique=True)
    is_active = models.BooleanField(default=True, blank=True)
    image1 =  models.ImageField(upload_to='img')
    image2 =  models.ImageField(upload_to='img', blank=True)
    image3 =  models.ImageField(upload_to='img', blank=True)
    image_caption1 = models.CharField(max_length=200, blank=True)
    image_caption2 = models.CharField(max_length=200, blank=True)
    image_caption3 = models.CharField(max_length=200, blank=True)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    quantity = models.IntegerField(default=1)
    description = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    shipping_price = models.DecimalField(decimal_places=2, max_digits=6)
    categories = models.ManyToManyField(Category)

    def save(self, *args, **kwargs):
        super(Item, self).save(*args, **kwargs)
        if not self.slug:
            self.slug = slugify(self.product.title) + "-" + str(self.id)
            self.save()
4

1 回答 1

0

像这样更新您的视图函数以返回获取请求的表单:

def edit_item(request, item_id):
    if request.method == 'POST':
        item = Item.objects.get(id=item_id)
        ....
        #your existing code
   else: #if its GET request
        item = Item.objects.get(id=item_id)
        form = AddItem(instance=item )
        return render_to_response('forsale.html', locals(), 
                   context_instance=RequestContext(request))

注意:您需要处理item_id数据库中不存在项目的情况。在这种情况下,不要使用instance参数来实例化表单。

于 2012-08-19T08:44:02.537 回答