gpt4 book ai didi

django - 如何将 ModelForm 与 django-address 一起使用?

转载 作者:行者123 更新时间:2023-12-02 19:53:03 25 4
gpt4 key购买 nike

我正在寻找使用django-address根据配置文件存储地址。通过我的网页和 Django 管理员输入地址会导致保存地址,但是,该地址不会存储在配置文件中,即配置文件对象最终不会包含地址。如何获取要根据配置文件模型保存的地址?

# profiles/forms.py
from django import forms
from profiles.models import Profile
from address.forms import AddressField, AddressWidget


class ProfileUpdateForm(forms.ModelForm):

class Meta:
model = Profile
fields = ['somefieldsthatsave',
'address',
]
field_classes = {
'address': AddressField,
}
widgets = {
'address': AddressWidget,
}

-

# profiles/models.py
import datetime
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

from guardian.shortcuts import assign_perm
from address.models import AddressField


class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
address = AddressField(blank=True, null=True, on_delete=models.CASCADE)

class Meta:
ordering = ["-id"]
permissions = (
('view_profile', 'View profile'),
)

def save(self, *args, **kwargs):
super().save(*args, **kwargs)
assign_perm('view_profile', self.user, self)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()

-

# profiles/views.py
from django.views.generic.edit import UpdateView
from guardian.mixins import PermissionRequiredMixin

from profiles.models import Profile
from profiles.forms import ProfileUpdateForm


class ProfileOverview(PermissionRequiredMixin, UpdateView):
model = Profile
form_class = ProfileUpdateForm
permission_required = 'view_profile'

感谢您的宝贵时间。

最佳答案

您必须在管理文件中将地址定义为内联地址。

# admin.py
from django.contrib import admin
from address.models import Address
from profiles.models import Profile

class AddressInline(admin.StackedInline):
model = Address

@admin.site.register(Profile)
class UserProfile(admin.ModelAdmin):
inlines = (AddressInline,)


关于django - 如何将 ModelForm 与 django-address 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54851010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com