[Answer]-Django โ€“ customizing the add view of the admin page

1๐Ÿ‘

โœ…

I ended up not using the fieldsets. I think that is meant for very simple alterations.
Here are the steps to accomplish it:

  1. override the url for the add:

    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. make a add_pen.html template which has your custom page. Make sure the form contains {% csrf_token %}

  3. add an entry point to your views.py to handle the form request:

    @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})
    
๐Ÿ‘คmax

Leave a comment