简体   繁体   English

编辑表格并保存到数据库

[英]Editing form and saving into database

I have a form that takes information about an item and saves it into the database. 我有一个表单,用于接收有关项目的信息并将其保存到数据库中。 Im trying to allow users to edit that form with new/different information and save it again. 我试图让用户使用新的/不同的信息来编辑该表格并再次保存。 Im having some difficulty trying to get this to work. 我在尝试使其工作时遇到一些困难。 I think the problem is when Django validates the data it sees that the slug and unique id of the item already exist and doesnt allow it to validate the data but im not completely sure about this as well. 我认为问题在于,当Django验证数据时,它看到该项目的数据包和唯一ID已经存在,并且不允许其验证数据,但我对此也不太完全确定。 Would really appreciate the help. 非常感谢您的帮助。 Thanks. 谢谢。

#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()

Update your view function like this to return form for get request as well: 像这样更新您的视图函数,以返回表单以获取请求:

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))

Note: you need to handle case when item with item_id does not exists in the DB. 注意:当数据库中不存在带有item_id item时,您需要处理这种情况。 In that case do not use instance parameter to instantiate the form. 在这种情况下,请勿使用instance参数实例化表单。

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

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