使用 django CreateView 更新 onetoone

update onetoone using django CreateView

我正在使用 CreateView 来更新我的 Person 模型。该模型与 Adress 具有一对一关系。尝试更新我的 Person 模型时,我无法同时更新 Adress 模型。它只是给了我现有地址的列表,但无法添加新地址。我可以看到这在管理员中是可能的。在 CreateView 中可以这样做吗?

model.py:

 class Person(Model):
    
        fname=CharField(default="missing",max_length=100)
        lname=CharField(default="missing",max_length=100)
        mobil=PhoneField(default='9999999999')
        mail=EmailField(default='contact@gmail.com')
        padress=OneToOneField(Adress,on_delete=CASCADE,primary_key=True)
    
        def __str__(self):
            return self.fname
    
        class Meta:
            ordering=('fname','lname')
    
    class Adress(Model):
    
        street=CharField(default='missing',max_length=100)
        snumb=CharField(default='missing',max_length=15)
        town=CharField(default='missing',max_length=100)
        postn=CharField(default='99999',max_length=5,validators=[postnvali])
        
        def __str__(self):
            return self.town
    
        class Meta:
            ordering=('street','town')

view.py

    class PCreate(CreateView):
        
        template_name='kammem/create.html'
        model=Person
        fields=['fname','lname','mobil','mail','padress']
        success_url=reverse_lazy('forl')

url.py

    path('pcreate/',PCreate.as_view(),name='pcreate'),

template: 

    {% extends 'edit2.html' %}
    
    {% block add %}
    <form method="post">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Save">
    </form>
    {% endblock %}

any suggestions?

ok, here is an update. I can save both instances and also create the relation. But I still can't exit the function, please look at the following:

class PCreate2(CreateView):
    
    form_class=PersonForm
    template_name='kabmmem/create.html'
    success_url=reverse_lazy('forl')

    def form_valid(self,form):
        # create address and person
        street = form.cleaned_data['street']
        snumb = form.cleaned_data['snumb']
        town = form.cleaned_data['town']
        postn = form.cleaned_data['postn']
        fname = form.cleaned_data['fname']
        lname = form.cleaned_data['lname']
        mobil = form.cleaned_data['mobil']
        mail = form.cleaned_data['mail']
        a=Adress.objects.create(street=street,snumb=snumb,town=town,postn=postn)
        pe=Person.objects.create(fname=fname,lname=lname,mobil=mobil,mail=mail,padress=a)

        return HttpResponseRedirect(self.get_success_url())

return 语句给出:AttributeError: 'NoneType' object has no attribute 'dict'

所以,我还是迷路了...

return 声明

您可以设置一个 PersonForm ModelForm 并在其中定义地址字段。将此表单分配给视图的 form_class 属性将确保地址字段可用于在页面上进行编辑。

验证表单后,您必须手动创建地址对象并将其分配给表单的 padress 字段。您可以在视图的 form_valid 方法中执行此操作。

forms.py

from django import forms

class PersonForm(forms.ModelForm):
    street=forms.CharField(max_length=100)
    snumb=forms.CharField(max_length=15)
    town=forms.CharField(max_length=100)
    postn = forms.CharField(max_length=5, validators=[postnvali])

    class Meta:
        model = Person
        exclude = ['padress']

views.py

class PCreate(CreateView):
    
    form_class=PersonForm
    template_name='kammem/create.html'
    success_url=reverse_lazy('forl')

    def form_valid(self, form):
        # create address
        street = form.cleaned_data['street']
        snumb = form.cleaned_data['snumb']
        town = form.cleaned_data['town']
        postn = form.cleaned_data['postn']
        address = Address.objects.create(street=street, snumb=snumb, town=town, postn=postn)

        # get the response
        response = super().form_valid(form)

        # assign the address to the person object
        self.object.padress = address
        self.object.save()

        # return the response
        return response

好的,经过大量研究终于找到了解决方案。我只是在 CreateView 函数中设置了两个表,return 成功了 url。这是一个丑陋的解决方案。我有谁知道更好的解决方案,请告诉我。更新外部字段是一种很常见的模式,但是涉及到这个的文档我真的很少,

views.py:

class PCreate2(CreateView):
    
    form_class=PersonForm
    template_name='kammem/create.html'

    def form_valid(self,form):
        # create address
        street = form.cleaned_data['street']
        snumb = form.cleaned_data['snumb']
        town = form.cleaned_data['town']
        postn = form.cleaned_data['postn']
        fname = form.cleaned_data['fname']
        lname = form.cleaned_data['lname']
        mobil = form.cleaned_data['mobil']
        mail = form.cleaned_data['mail']
        a=Adress.objects.create(street=street,snumb=snumb,town=town,postn=postn)
        pe=Person.objects.create(fname=fname,lname=lname,mobil=mobil,mail=mail,padress=a)

        return HttpResponseRedirect(reverse_lazy('personer'))