我希望使用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'
感谢您的时间。
答案 0 :(得分:0)
您必须在管理文件中将地址定义为嵌入式。
# 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,)