Django Formset重定向与pk / id

时间:2018-01-21 05:07:04

标签: python django

我试图将一个formset的父ID传递给一个视图,但由于某种原因它似乎并不适合我。我在其他应用程序中执行此操作没有问题但是这个特定的应用程序返回"无"作为一个PK。唯一的区别是我的formset模型通常不包含外键关系。如果我自己渲染父级,我可以通过pk就好了。请帮助:)

  

例外价值:反向公司细节'用关键字   争论' {' pk':无}'未找到。尝试过1种模式:   ['客户/(P [0-9A-Z - ] +?)/细节/ $']

''' urls.py '''

   url(r'^(?P<pk>[0-9a-z-]+)/detail/$', CompanyDetailView.as_view(),
       name='company-detail'),

&#39;&#39;&#39; forms.py &#39;&#39;&#39;

class CompanyCreateForm(forms.ModelForm):
    class Meta:
        model = CompanyModel
        fields = [
            'name',
            'website',
            'rate',
        ]
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': ''}),
            'website': forms.URLInput(attrs={
                'class': 'form-control',
                'placeholder': ''}),
            'rate': forms.NumberInput(attrs={
                'class': 'form-control',
                'placeholder': ''}),
        }


SitesFormSet = inlineformset_factory(
    CompanyModel,
    SiteModel,
    fields=('street1',
            'street2',
            'city',
            'state',
            'zipcode',
            'country',
            'phone',
            'distance',
           ),
    widgets={
            'street1': forms.TextInput(attrs={
                'class': 'form-control'
            }),
            'street2': forms.TextInput(attrs={
                'class': 'form-control'
            }),
            'city': forms.TextInput(attrs={
                'class': 'form-control'
            }),
            'state': forms.TextInput(attrs={
                'class': 'form-control'
            }),
            'zipcode': forms.NumberInput(attrs={
                'class': 'form-control'
            }),
            'country': forms.TextInput(attrs={
                'class': 'form-control'
            }),
            'phone': forms.TextInput(attrs={
                'class': 'form-control'
            }),
            'distance': forms.NumberInput(attrs={
                'class': 'form-control'
            })
    },
    extra=1
)

&#39;&#39;&#39; views.py &#39;&#39;&#39;

def companycreateview(request):
    if request.method == 'POST':
        companyform = CompanyCreateForm(request.POST)
        if companyform.is_valid():
            company = companyform.save(commit=False)
            sitesform = SitesFormSet(request.POST, request.FILES, instance=company)
            if sitesform.is_valid():
                company.save()
                sitesform.save()
        return redirect('customers:company-detail', pk=company.pk)
    else:
        companyform = CompanyCreateForm()
        sitesform = SitesFormSet()
    context = {
        'company': companyform,
        'sites': sitesform,
        }
    return render(request, 'customers/new-company.html', context)

class CompanyDetailView(DetailView):
    model = CompanyModel
    context_object_name = 'company'
    template_name = 'customers/company-detail.html'

    def get_context_data(self, **kwargs):
            context = super(CompanyDetailView, self).get_context_data(**kwargs)
            context['sites'] = SiteModel.objects.filter(company=self.get_object())
            context['contacts'] = ContactModel.objects.filter(site__company=self.get_object())
            context['reports'] = ServiceReportModel.objects.filter(site__company=self.get_object())
            return context

&#39;&#39;&#39; 新company.html.html &#39;&#39;&#39;

<form action="" method="post">
        {% csrf_token %}
        <div class="form-row">
            <div class="form-group col-md-12 form-col-md form-col-right-just {% if report.equipment.errors %}bg-danger{% endif %}">
                <label for="{{ company.name.id_for_label }}"><Strong>Company Name</Strong></label></a>
                {{ company.name }}
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-12 form-col-md form-col-right-just {% if report.equipment.errors %}bg-danger{% endif %}">
                <label for="{{ company.website.id_for_label }}"><Strong>Website</Strong></label></a>
                {{ company.website }}
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-12 form-col-md form-col-right-just {% if report.equipment.errors %}bg-danger{% endif %}">
                <label for="{{ company.rate.id_for_label }}"><Strong>Hourly Rate</Strong></label></a>
                {{ company.rate }}
            </div>
        </div>

        {{ sites.management_form }}
        {{ sites.non_form_errors }}

        {% for child_form in sites %}
            {{ child_form.sites_id.as_hidden }}
            {{ child_form.company.as_hidden }}

            <div class="form-row">
                <div class="form-group col-md-12 form-col-md">
                    <label for="{{ child_form.id_for_label }}"><Strong>{{ child_form.label }}</Strong></label>
                    {{ child_form }}
                    {% if child_form.errors %}
                        {% for error in child_form.errors %}
                            {{ error|escape }}
                        {% endfor %}
                    {% endif %}
                </div>
            </div>
        {% endfor %}

        <div class="form-row">
            <div class="form-group col-md-12 form-col-md form-col-left-just">
                <button type="submit" class="btn btn-primary btn-detail"><Strong>Submit</Strong></button>
            </div>
        </div>
    </form>

2 个答案:

答案 0 :(得分:0)

我认为您需要对网址模式进行一些小改动。该错误显示以下模式未找到匹配项:

['customers/(?P[0-9a-z-]+)/detail/$']

尝试在<pk>之后直接添加?P

customers/(?P<pk>[0-9a-z-]+)/detail/$

答案 1 :(得分:0)

urls.py中: 我想你错过了urlpatterns中的pk

url('customers/(?P<pk>[0-9a-z-]+)/detail/$',.......)

在你views.py

如果你的编码缩进sitesform无效,那么它会尝试重定向。但company尚未保存到数据库中。因此pkNone。代码应如下所示:

if companyform.is_valid():
    company = companyform.save(commit=False)
    sitesform = SitesFormSet(request.POST, request.FILES, instance=company)
    if sitesform.is_valid():
        company.save()
        sitesform.save()
        return redirect('customers:company-detail', pk=company.pk)