Django内联formset工厂的JavaScript

时间:2013-07-22 11:21:38

标签: django django-forms django-templates django-views

我只是想像Django admin一样动态添加字段。 (+)( - )按钮必须使用javascript执行添加和删除 img_formset

以下代码取自我从网上获得的教程,并且工作正常。但是现在我只需要知道如何扩展这段代码。

models.py

from django.db import models

class Pet(models.Model):
    name = models.CharField(max_length=100)
    breed = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

class PetImage(models.Model):
    image = models.ImageField(upload_to='pets')
    pet = models.ForeignKey(Pet)
    created = models.DateTimeField(auto_now_add=True)

    #Delete Path
    def delete(self, *args, **kwargs):
        self.image.delete(False)
        super(PetImage, self).delete(*args, **kwargs)

forms.py

from django.forms.models import inlineformset_factory
from django import forms

from .models import Pet, PetImage

class PetForm(forms.ModelForm):
    class Meta:
        model = Pet

PetImageFormset = inlineformset_factory(Pet, PetImage, 
    fields=('image',), can_delete=True)

urls.py

from django.conf.urls import *

urlpatterns = patterns('pets.views',
    url(r'^add/$', 'add_pet', name='add_pet'),
    url(r'^update/(\d+)/$', 'update_pet', name='update_pet'),
)

views.py

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render

from .forms import PetForm, PetImageFormset
from .models import Pet, PetImage


def add_pet(request):
    form = PetForm()
    img_formset = PetImageFormset(instance=Pet())

    if request.method == 'POST':
        form = PetForm(request.POST)
        if form.is_valid():
            pet = form.save()
            img_formset = PetImageFormset(request.POST, 
                request.FILES, instance=pet)
            if img_formset.is_valid():
                img_formset.save()
                return HttpResponseRedirect(reverse('pets:home'))

    return render(request, "form.html", {
        'form': form, 
        'img_formset': img_formset,
        'action': "Create" 
    })


    def update_pet(request, pet_id):
        pet = get_object_or_404(Pet, pk=pet_id)

        form = PetForm(instance=pet)
        img_formset = PetImageFormset(instance=pet)

        if request.method == 'POST':
            form = PetForm(request.POST, instance=pet)
            if form.is_valid():
                pet = form.save(commit=False)
                img_formset = PetImageFormset(request.POST, 
                                request.FILES, instance=pet)
                if img_formset.is_valid():
                    pet.save()
                    img_formset.save()
                    return HttpResponseRedirect(reverse('pets:home'))

        return render(request, "form.html", {
            'form': form, 
            'img_formset': img_formset,
            'action': "Update" 
        })

form.html

{% extend "base.html" %}

{% block title %}Pet{% endblock title %}

{% block content %}
<h4>{{ action }}</h4>

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    {{ img_formset.as_p }}
</form>
{% endblock content %}

0 个答案:

没有答案