拉出特定的可编辑字段,而其他字段只是在django中显示标题?

时间:2014-06-04 07:03:14

标签: django

我尽力提供这里提供的答案,但它不适合我。我正在尝试创建可以编辑数据库实例的表单。我想在左边显示一个人名,在右边显示一个可编辑的字段。有一次,我成功地成功地做了一次,但我失去了我在那里的运气,无法复制它。我想对数据库中的几个条目执行此操作,而不仅仅是一个。下面是我尝试过的最新内容,如果可以,请提供帮助:

模型:

class listMem(models.Model):
    first_name = models.CharField (max_length = 20)
    last_name = models.CharField (max_length = 20)
    email = models.EmailField ()
    perform = models.BooleanField ()
    field_1 = models.BooleanField ()
    field_2 = models.BooleanField ()
    field_text = models.CharField (max_length = 50)
    field_num = models.CharField (max_length = 50)
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False )
    updated = models.DateTimeField(auto_now_add = False, auto_now = True )

    def __unicode__(self):
        return self.first_name +" " + str(self.perform)

视图:

def comp (request):

    dance_list = listMem.objects.all()

    dancer = listMem.objects.get(pk=1)
    form = listMemForm(instance=dancer)
    if form.is_valid():
        save_it = form.save(commit = False)
        save_it.save()

模板:

 <form method='POST' action='#'> {% csrf_token %} 

        <ul>{% for f in form %}
<li>{% if f.instance.pk %}title: {{ f.instance.first_name }}
    {% endif %} {{ f }}</li>
    {% endfor %}</ul>

    <input type="submit" value="submit">


</form>

形式:

class ListMemForm (forms.ModelForm):

        class Meta:
            model = listMem
            fields = ('last_name')

1 个答案:

答案 0 :(得分:1)

研究使用django modelformset_factory创建一个formset:检查文档。

概述我是如何做到的

  1. 删除dance_list = listMem.objects.all()行,不必要的
  2. 2.Try:      listmemformset = modelformset_factory(listMem, form=ListMemForm) if request.method =='POST': formset=listmemformset(request.POST, request.FILES, queryset=listMem.objects.all() ) if formset.is_valid(): formset.save() else: formset = listmemformset(queryset=listMem.objects.all())

    1. 在您的模板中,请确保在您的for循环和样式之前包含{{formset.management_form}}