Django内联添加'客户端。客户端'没有ForeignKey来声称.Claim''

时间:2015-11-09 10:52:53

标签: python django

我正在尝试在我的CreateView中添加内联添加。就像它在管理中的工作方式一样。我正在接待客户。客户'没有ForeignKey来声明。声明'。这是我的第一次尝试,因此遵循在线指南。我还尝试使用crispy表单来处理表单的模板渲染。

修改

有几个人提到我需要切换ForeignKey。管理方式是正确的,有一个内联添加索赔。

models.py

class Claim(models.Model):
    client = models.ForeignKey(Client)

class Client(models.Model):
    ...

forms.py

class ClaimForm(forms.ModelForm):
    class Meta:
        model = Claim
        exclude = ('creation', 'last_modified')

class ClientForm(forms.ModelForm):
    class Meta:
        model = Client
        exclude = ('creation', 'last_modified')

ClientFormSet = inlineformset_factory(Claim, Client)

views.py

class ClaimCreate(CreateView):
    form_class = ClaimForm
    model = Claim
    success_url = '/claims/list'

    def get_context_data(self, **kwargs):
        context = super(ClaimCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            context['formset'] = ClientFormSet(self.request.POST)
        else:
            context['formset'] = ClientFormSet()
        return context

    def form_valid(self, form):
        context = self.get_context_data()
        formset = context['formset']
        if formset.is_valid():
            self.object = form.save()
            formset.instance = self.object
            formset.save()
            return redirect(self.object.get_absolute_url())  
        else:
            return self.render_to_response(self.get_context_data(form=form))

template.html

<form method="POST" action="">{% csrf_token %}
                            {{ form|crispy }}
                            {% crispy formset formset.form.helper %}
                            <input class="btn btn-primary" type="submit" value="Submit" />
                            <a href="{% url 'claims' %}"><button type="button" class="btn btn-danger">Cancel</button></a>
                        </form>                           

2 个答案:

答案 0 :(得分:1)

    ClientFormSet = inlineformset_factory(Client, Claim)

答案 1 :(得分:0)

内联模型应该具有父模型的ForeinKey。