2015-05-28 117 views
0

假設我有一個Pen的數據模型。筆可以由金屬或木材製成。 金屬筆可以是銀色或白色 木製筆可以是藍色或綠色。 所以不得有藍色的金屬筆。Django - 自定義管理頁面的添加視圖

有沒有辦法在添加按鈕中替換材質選擇以顯示材質名稱/顏色的組合? 我認爲這些字段集必須有一個技巧。

# model.py 
from django.db import models 
class Color(models.Model): 
    color = models.CharField(max_length=20, primary_key=True) 
    def __unicode__(self): 
     return self.color 

class Material(models.Model): 
    type = models.CharField(max_length=20) 
    color = models.OneToOneField(Color) 
    def __unicode__(self): 
     return "%s_%s" % (str(self.color), self.type) 

class Pen(models.Model): 
    id = models.AutoField(primary_key=True) 
    label = models.CharField(max_length=20) 
    material = models.ForeignKey(Material) 
    def __unicode__(self): 
     return "%s_%s" % (str(self.material), self.label) 

# admin.py 
from django.contrib import admin 
from .models import Material, Color, Pen 

class PenAdmin(admin.ModelAdmin): 
    list_display = ('label', 'material', 'get_color',) 
    fieldsets = (
     (None, { 
      'fields': ('label', 'material') 
     }), 
    ) 
    def get_color(self, obj): 
     return obj.material.color 
    get_color.short_description = 'Color' 

admin.site.register(Pen, PenAdmin) 
admin.site.register(Material) 
admin.site.register(Color) 

回答

0

我最終沒有使用fieldset。我認爲這是非常簡單的改動。 下面是完成它的步驟:

  1. 覆蓋的URL地址:

    url(r'^admin/penshop/pen/add/$', 'penshop.views.add_pen'), 
    url(r'^admin/save_pen/$', 'penshop.views.save_pen'), 
    url(r'^admin/', include(admin.site.urls)), 
    
  2. 使其中有您的自定義頁面add_pen.html模板。確保表單包含{% csrf_token %}

  3. 切入點添加到您的views.py處理表單請求:

    @staff_member_required 
    def save_pen(request): 
        if request.method == 'POST': 
         values = request.META.items() 
         label = request.POST.get("label", "") 
         color = request.POST.get("color", "") 
         material = request.POST.get("material", "") 
         if len(label) > 0 and len(color) > 0 and len(material) > 0 and\ 
          not color.startswith('-') and not material.startswith('-'): 
          import pdb;pdb.set_trace 
          col_obj = Color.objects.filter(color=color)[0] 
          mat_obj = Material.objects.filter(type=material, color=col_obj)[0] 
          pen_obj = Pen(label=label, material=mat_obj) 
          pen_obj.save() 
          return HttpResponseRedirect('/admin/penshop/pen/') 
         else: 
          raise Exception('Bad data. It is not going to be saved!') 
        else: 
         return HttpResponseRedirect('/admin/') 
    
        return render(request, 'index.html', {'form': form}) 
    
相關問題