Django:使用AutoField编辑ModelForm

时间:2012-06-12 16:38:31

标签: python django-models django-forms autofield

我正在尝试创建一个视图,用户可以通过模板中的表单编辑数据库记录。我搜索了许多网页(以及Django文档),他们教授如何制作这些视图,但他们总是使用Django为每个模型生成的“id”。在这个特定的模型中,我必须使用AutoField来覆盖“id”。有没有办法使用这个AutoField作为Django记录的“id”?

这是我完整的模型:

class T031003 (models.Model): 
   C003IDCD = AutoField(primary_key=True)
   C003INST = models.IntegerField(unique=True) #usar AutoSlug
   C003TPCD = models.CharField(max_length=1)
   C003CHCD = models.CharField(max_length=14)
   C003MTR = models.CharField(max_length=30, blank=True, null=True)
   C003CTCD = models.CharField(max_length=3)
   C003RZSC = models.CharField(max_length=60, blank=True, null=True)
   C003EML = models.EmailField(max_length = 254, blank=True, null=True)
   C003LOGA = models.CharField(max_length=20)
   C003LOGB = models.DateTimeField()
   C003LOGD = models.CharField(max_length=15, blank=True, null=True)
   C003LOGF = models.CharField(max_length=20, blank=True, null=True)

   def __unicode__(self):
       return '%s' %  self.C003MTR

   class T031003Form(ModelForm):
       class Meta:
          model = T031003
          ordering = ["-C003MTR"]
          exclude = ('C003LOGA','C003LOGB','C003LOGD','C003LOGE','C003LOGF')

这是我试图做的视图,但它给出了错误“No T031003与给定查询匹配”。这是正确的,因为表中没有“id”:

def t031003form_edit(request, id=None):
pin = get_object_or_404(T031003, pk=id)
form = T031003Form(request.POST or None, instance=pin)
if request.method == 'POST':
    if form.is_valid():
        form = form.save(False)
        form.C003LOGA = request.user
        form.C003LOGB = datetime.date.today()
        form.C003LOGD = request.META['REMOTE_ADDR']
        form.C003LOGF = request.META['USERDOMAIN']
        form.save()
        form = T031003Form()
    else:
        return HttpResponseRedirect('/erro/')
return render_to_response('T031003Form_edit.html', {'form': form,}, context_instance=RequestContext(request))

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

如果模型有一个AutoField - 一个自动递增的主键 - 那么当你第一次调用save()时,将计算该自动递增的值并将其保存为对象的属性:

>>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b2.id     # Returns None, because b doesn't have an ID yet.
>>> b2.save()
>>> b2.id     # Returns the ID of your new object.

在调用save()之前无法确定ID的值是什么,因为该值是由数据库计算的,而不是由Django计算的。

参考:https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs

答案 1 :(得分:0)

好吧,感谢亲密朋友的帮助,我可以使用formset来完成这个工作。以下是观点:

def t031002form_edit(request, id_auto):
j = get_object_or_404(T031002, pk=id_auto)

T031003FormSet = modelformset_factory(T031002, can_delete=True, max_num=1)

if request.method == 'POST':
    form = T031002FormSet(request.POST or None, request.FILES or None, queryset=T031002.objects.filter(pk=id_auto)) 
    if form.is_valid():
        instance = form.save(commit=False)
        form.C003LOGA = request.user
        form.C003LOGB = datetime.date.today()
        form.C003LOGD = request.META['REMOTE_ADDR']
        form.C003LOGF = request.META['USERDOMAIN']
        for reform in instance:
            reform.save()
    else:
       return HttpResponseRedirect('/erro/')
else:
    form = T031002FormSet(queryset=T031002.objects.filter(pk=id_auto))  
return render_to_response(('T031002Form_edit.html'), {'form': form,}, context_instance=RequestContext(request))

因此,使用formsets,您可以很好地工作而不必担心。希望通过同样的质疑帮助其他人。