2014-10-29 91 views
1

我遇到了一個問題,每當我在編輯頁面上保存時,它都不會轉到url,而是要求我輸入要隱藏的字段。Django使用一個模板創建和編輯頁面

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> 

兩個編輯和創建共享相同的模板。名稱字段是每個建築物的唯一鍵,一旦用戶創建建築物,我不希望他們改變它,所以我嘗試將其隱藏在編輯視圖上。但是當我更改其他字段並嘗試保存它時,它總是彈出一個空的名稱字段並要求我輸入名稱。有沒有人有什麼建議?在此先感謝

+0

http://stackoverflow.com/a/26492650/3033586 – madzohan 2014-10-29 09:18:12

+0

所以在你的情況下,在更新對象時,你必須提供初始數據此字段或使用另一種形式(與排除字段),並設置它稍後在您的視圖 – madzohan 2014-10-29 09:24:02

回答

0

您可以在名稱字段上設置readonly屬性。

嘗試添加以下__init__方法在UpdateBuildingForm類:

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'] 
+0

添加'def clean_name'並顯示如何爲此字段提供初始數據,這將是正確的答案,謝謝。 – madzohan 2014-10-29 09:31:15

+0

非常感謝。 @dazedconfused – 2014-10-29 10:27:17

+0

不客氣。有關'clean_ ()'的更多信息:[表單和字段驗證](https://docs.djangoproject.com/en/1.7/ref/forms/validation/) – dazedconfused 2014-10-29 10:36:34