Проблема с Django UpdateView и inline_formsets - PullRequest
0 голосов
/ 11 сентября 2018

Я новичок с Django и столкнулся с проблемами с Django UpdateView и Formsets.Я не понимаю, зачем устанавливать fs.instance.be = company в моем пост-методе, но это приводит к новой записи в db, а не к обновлению.Без этой строки, без сохранения.

Что здесь не так?

models.py

from django.db import models
# A base class for Client and Company for joining Address and Telephone etc. here 
class BusinessEntity(models.Model):
        name = models.CharField(max_length=30)

class Address(models.Model):
    be=models.ForeignKey(BusinessEntity,on_delete=models.CASCADE)
    street = models.CharField(max_length=256)
    #some more here

class Telephone(models.Model):
    be=models.ForeignKey(BusinessEntity,on_delete=models.CASCADE)
    number = models.CharField(max_length=30,null=True,blank = True)

class Client(BusinessEntity):
    title       = models.CharField(max_length=30)
    firstname   = models.CharField(max_length=30)

class Company(BusinessEntity):
    customer_no=models.CharField(max_length=20)

forms.py

from django.forms import ModelForm
from django.forms.models import inlineformset_factory
from .models import Address,Telephone,Client,Company

class CompanyForm(forms.ModelForm):
    class Meta:
        model = Company

CompanyAddressFormset = inlineformset_factory(Company, Address )
CompanyTelephoneFormset = inlineformset_factory(Company, Telephone )

views.py

from django.views.generic import  CreateView, UpdateView

class CompanyEditView(UpdateView):
    template_name = 'imsApp/company_edit_form.html'
    model= Company
    form_class = CompanyForm
    success_url = '/imsApp/manage/company/info'

    def get_object(self, queryset=None):
       return Company.objects.get(id=self.kwargs['company_id'])

    def get(self,request,**kwargs):
        self.object = self.get_object()
        form_class = self.get_form_class()
        company_form = self.get_form(form_class)
        address_form = CompanyAddressFormset(instance = self.object) 
        telephone_form = CompanyTelephoneFormset(instance = self.object)
        return self.render_to_response(self.get_context_data(company_form=company_form,address_form=address_form,telephone_form=telephone_form))

    def post(self,request,**kwargs):
        self.object = self.get_object()
        form_class = self.get_form_class()
        company_form = self.get_form(form_class)

        qsAddress = Address.objects.filter(be = self.object)
        qsTelephone = Telephone.objects.filter(be = self.object)
        address_formsets = CompanyAddressFormset(self.request.POST, queryset=qsAddress) 
        telephone_formsets = CompanyTelephoneFormset(self.request.POST, queryset=qsTelephone)

        if company_form.is_valid():
            company = company_form.save()

            for fs in address_formsets:
                if fs.is_valid():

                    #Without the line below => no update
                    #With line => new line created instead of update the old one
                    fs.instance.be = company  #

                    addr = fs.save()
                    print("ADRESS: ",addr)
                else:
                     print('address -> INVALID !!!! ')
            for fs in telephone_formsets:
                if fs.is_valid():
                    #see above
                    fs.instance.be = company
                    fs.save()
                else:
                     print('telephone -> INVALID !!!! ')

            return self.form_valid(company_form, address_formsets, telephone_formsets)
        return self.form_invalid(company_form, address_formsets, telephone_formsets

    def form_valid(self, company_form, address_formsets, telephone_formsets):
            return HttpResponseRedirect(self.get_success_url()
        )


    def form_invalid(self, company_form, address_formsets, telephone_formsets):
            return self.render_to_response(
                 self.get_context_data(company_form=company_form, address_form=address_formsets, telephone_form=telephone_formsets)
        )

company_edit_form.html (выдержка)

......
{% block content %}
<p>
    {% if company_form %}
    <form action="" method="post">
        {% csrf_token %}

        <fieldset>
            <legend>Firma</legend>
                {{ company_form.non_field_errors }}

                {% for field in company_form %}
                <div class="row">
                    <div class="col-md-3">{% bootstrap_label field.label %}</div>
                    <div class="col-md-8">{% bootstrap_field field show_label=False %}</div>
                </div>
                {% endfor %}
        </fieldset>

        <fieldset>
                <legend>Adressen</legend>
                {{ address_form.management_form }}
                {{ address_form.non_form_errors }}
                    {% for form in address_form %}             

                        <div class="inline {{ address_form.prefix }}">     
                        <div>{{ form.id }}</div>    
                        {% for field in form.visible_fields %}                           
                                <div class="row">
                                        <div class="col-md-3">{% bootstrap_label field.label %}</div>
                                        <div class="col-md-8">{% bootstrap_field field show_label=False %}</div>
                                </div>
                        {% endfor %}
                        </div>
                {% endfor %}
        </fieldset>

        <fieldset>
                <legend>Telefon</legend>
                {{ telephone_form.management_form }}
                {{ telephone_form.non_form_errors }}
                    {% for form in telephone_form %}
                        <div class="inline {{ telephone_form.prefix }}">
                        <div>{{ form.id }}</div>

                        {% for field in form.visible_fields %}
                                <div class="row">
                                        <div class="col-md-3">{% bootstrap_label field.label %}</div>
                                        <div class="col-md-8">{% bootstrap_field field show_label=False %}</div>
                                </div>
                        {% endfor %}
                        </div>
                {% endfor %}
        </fieldset>
        </form>
    {% endif%}
{% endblock %}
...