Django - Как использовать 'create' и 'update' вместе в одной форме/URL/View?

TrimType's Create and Update will be implemented together by modal in Car's DetailView.

Car's DetailView

Модал CreateView от TrimType

Модал UpdateView от TrimType


  • models.py :
class Car(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200, null=False, blank=False)

class TrimType(models.Model):
    id = models.AutoField(primary_key=True)
    car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True)
    typeName = models.CharField(max_length=50, blank=False, null=False)

  • urls.py :
app_name = 'brand'
urlpatterns = [
    ...
    url(r'^car/(?P<car_id>\d+)/$', car_views.CarDetailView.as_view(), name='car_detail'),
    # TrimType_id is transmitted by GET method.
    ...
]

  • forms.py :
class TrimTypeForm(forms.ModelForm):
    class Meta:
        model = TrimType
        fields = ('car', 'typeName')

        typeName = forms.CharField(
            widget=forms.TextInput(attrs={'class': 'form-control'}),
            label='TrimType'
        )

  • car_detail.html :
<div class="col-8">
  <div class="text-right mt-3 mb-3">
    <select class="form-control" id="slct_trim_type">
      <option value="0">*TrimType*</option>
      {% for trimType in trimType_list %}
      <option value="{{ trimType.id }}" data-car-idx="{{ car.id }}" {% if trimTypeID == trimType.id %}selected{% endif %}>{{ trimType.typeName }}</option>
      {% endfor %}
    </select>
  </div>
</div>

<div class="col-4">
  <div class="text-right mt-3 mb-3">
    <a id="btn_trimtype_add" class="btn btn-primary btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="" data-original-title="add"></a>
    <a id="btn_trimtype_modify" class="btn btn-info btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="" data-original-title="modify"></a>
    <a id="btn_trimtype_delete" class="btn btn-danger btn-icon waves-effect waves-themed" data-toggle="tooltip" title="" data-original-title="delete"></a>
  </div>
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-body">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
          <h3 class="modal-title">*TrimType* UpdateView</h3>
          <form method="post" class="form-horizontal" enctype="multipart/form-data">
            # form contents
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

  • views.py : I referred to the URL.
class CarDetailView(FormView):
    model = TrimType
    form_class = TrimTypeForm
    template_name = 'car/car_detail.html'
    
    def get_success_url(self):
        car_id = int(self.kwargs.get('car_id', 0))
        self.get_success_url = reverse_lazy('brand:car_detail', kwargs={'car_id': car_id})
        return self.get_success_url

    def get_form(self, form_class=None):
        if form_class is None:
            form_class = self.get_form_class()

        trimType_id = self.request.GET.get('tirmType', 0)

        try:
            trimType = TrimType.objects.get(id=trimType_id)
            return form_class(instance=trimType, **self.get_form_kwargs())
        except TrimType.DoesNotExist:
            return form_class(**self.get_form_kwargs())

    def form_valid(self, form):
        parent = Car.objects.get(pk=self.kwargs.get('car_id', 0))
        form.instance.car = parent
        form.save()
        return super(CarDetailView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        car_id = self.kwargs.get('car_id', 0)
        trimType_id = int(self.request.GET.get('trimType', 0))

        car = Car.objects.get(id=self.kwargs.get('car_id', 0))
        trimType = ''
        trimType_list = TrimType.objects.filter(car__id=car_id)

        if trimType_id > 0:
            trimType = TrimType.objects.get(id=trimType_id)

        context = super(CarDetailView, self).get_context_data(**kwargs)
        context['carID'] = car_id
        context['trimTypeID'] = trimType_id
        context['car'] = car
        context['trimType'] = trimType
        context['trimType_list'] = trimType_list
        return context

But, only create works, and update does not work.

Вернуться на верх