我有
models.py
......
class CatalogGroup(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
def __unicode__(self):
return self.name
class Place(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
def __unicode__(self):
return self.name
class Scale(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
def __unicode__(self):
return self.name
class ProductsTbl(models.Model):
model_number = models.CharField(max_length=255, blank=True, unique=True,error_messages={'unique':"This model number has already been registered."})
name = models.CharField(max_length=255, blank=True, null=True)
material = models.CharField(max_length=255,blank=True, null=True)
color = models.CharField(max_length=255, blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
suggest = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
cataloggroup = models.ManyToManyField(CatalogGroup)
place = models.ManyToManyField(Place)
scale = models.ManyToManyField(Scale)
slug = models.SlugField(unique=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
image = models.ImageField(upload_to=get_imagep_Product, blank=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
.....
如果有任何用户修改了表单中的数据,我需要更新数据库,所以我有:
views.py
.......
@login_required
def edit_thing(request, slug):
# grab the object...
thing = ProductsTbl.objects.get(slug=slug)
if thing.user != request.user:
raise Http404
# set the form we're using...
form_class = ProductsTblForm
if request.method == 'POST':
# grab the data from the submitted form
form = form_class(data=request.POST,files=request.FILES,instance=thing)
if form.is_valid():
form = form.save(commit=False)
form.useredit = request.user.username
form.save()
return redirect('thing_detail', slug=thing.slug)
# otherwise just create the form
else:
form = form_class(instance=thing)
# and render the template
return render(request, 'things/edit_thing.html', {
'thing': thing,
'form': form,
})
.........
然而,在我提交数据后,它只有部分数据可以保存在数据库中,下面这三个数据无法保存
cataloggroup = models.ManyToManyField(CatalogGroup)
place = models.ManyToManyField(Place)
scale = models.ManyToManyField(Scale)
我不知道为什么这三个数据无法保存?
如果我删除了
form = form.save(commit = False)
来自
views.py
,
form.useredit = request.user.username
不起作用,但可以将这三个数据保存到数据库,但是我必须让useredit更新到修改数据的用户。
答案 0 :(得分:0)
我弄明白该怎么做,,,我在上面添加了一个“form.save()”,它可以保存所有数据
views.py
....
if form.is_valid():
form.save()
form = form.save(commit=False)
form.useredit = request.user.username
form.save()
return redirect('thing_detail', slug=thing.slug)
....