Django使用一个模板创建和编辑页面

2 投票
1 回答
3704 浏览
提问于 2025-04-30 08:30

我遇到了一个问题,每次在编辑页面保存时,它不会跳转到指定的链接,而是让我输入我想要隐藏的字段。

model.py

class Building(models.Model):
 # Name of the project
 name = models.CharField(max_length=25, verbose_name='Project ID')
 # The address of the building
 address = models.CharField(max_length=100, verbose_name='Address')
 # The client name for this project
 client = models.CharField(max_length=50)
 # The contact number for the project
 contact = models.CharField(max_length=50)

forms.py

# The form to edit building details
class UpdateBuildingForm(forms.ModelForm):
  name = forms.CharField(label='Name', max_length=25, widget=forms.TextInput)
  client = forms.CharField(label='Client', max_length=50, widget=forms.TextInput)
  contact = forms.CharField(label='Contact', max_length=50, widget=forms.TextInput)
  address = forms.CharField(label='Address', max_length=100, widget=forms.TextInput)

  class Meta:
     model = Building

urls.py

urlpatterns = patterns('',
                   # e.g: /projectmonitor/
                   url(r'^$', views.BuildingSummary.as_view(), name='buildings'),
                   # url to add new building
                   url(r'building/new/$', views.BuildingCreate.as_view(), name='new_building'),
                   # e.g: /projectmonitor/5
                   url(r'^(?P<pk>\d+)/$', views.BuildingUpdate.as_view(), name='detail'),

views.py:

# The building create view
class BuildingCreate(generic.CreateView):
    model = Building
    form_class = UpdateBuildingForm
    template_name = "buildings/details.html"

    def form_valid(self, form):
       self.object = form.save(commit=False)
       self.object.save()
       return HttpResponseRedirect(reverse('projectmonitor:buildings'))

 # The building update view
class BuildingUpdate(generic.UpdateView):
    model = Building
    form_class = UpdateBuildingForm
    template_name = "buildings/details.html"

    def form_valid(self, form):
       """
       Update the building details after editing
       :param form: The building form
       :return: Redirect to the building summary page
       """
       self.object = form.save(commit=False)
       self.object.save()
       return HttpResponseRedirect(reverse('projectmonitor:buildings'))

还有模板

<form action="{{ action }}" method="post">
        {% csrf_token %}
        {% for error in form.non_field_errors %}
            {{ error }}
        {% endfor %}
        <div class="fieldWrapper">
            {% if not form.name.value  %}
                <p><label class="standard-label" for="id_name">Name:</label>
                {{ form.name|add_field_style:'width: 65%;margin-left: 10px;float:left;' }}</p>
            {% endif %}
            <p><label class="standard-label" for="id_address">Address:</label>
                {{ form.address|add_field_style:'width: 65%;margin-left: 10px;float:left;' }}</p>

            <p><label class="standard-label" for="id_client">Client:</label>
                {{ form.client|add_field_style:'width: 65%;margin-left: 10px;float:left;' }}</p>

            <p><label class="standard-label" for="id_contact">Contact:</label>
                {{ form.contact|add_field_style:'width: 65%;margin-left: 10px;float:left;' }}</p>
        </div>
        <input type="submit" value="Save"/>
    </form>   

编辑和创建使用的是同一个模板。名称字段是每个建筑的唯一标识,一旦用户创建了一个建筑,我不希望他们能更改它,所以我试着在编辑视图中隐藏这个字段。但是,当我更改其他字段并尝试保存时,它总是弹出一个空的名称字段,要求我输入名称。有没有人有什么建议?谢谢!

暂无标签

1 个回答

0

你可以在名称字段上设置 readonly 属性,这样就不能修改这个字段了。

试着在你的 UpdateBuildingForm 类里面添加以下的 __init__ 方法:

def __init__(self, *args, **kwargs):
    super(UpdateBuildingForm, self).__init__(*args, **kwargs)
    instance = getattr(self, 'instance', None)
    if instance and instance.pk:
        self.fields['name'].widget.attrs['readonly'] = True

另外,你也可以设置 disable 属性,这样这个字段就会被禁用,无法编辑。

编辑:根据 @madzohan 的评论,你可以添加一个 clean_name 方法,确保在表单层面上名称字段不会被更改。

def clean_name(self):
    if self.instance: 
        return self.instance.name
    else: 
        return self.fields['name']

撰写回答