【发布时间】:2018-12-12 00:29:23
【问题描述】:
以下更新和解决方案。
我一直在寻找解决方案,但没有发现任何突出的问题。
我创建了一个配置文件模型,该模型通过在管理员中工作的一对一字段链接到标准用户模型。我想将两个模型的所有字段/数据都拉到一个查询集中。我正在尝试创建一个用户编辑表单,我想根据当前登录的用户提取用户和个人资料的所有字段,并显示那些我将有一个页面来编辑和保存这些字段的字段。
实现这一目标的最佳选择是什么,越简单越好。
class Profile(models.Model):
address = models.blablabla
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
def profile_edit(request):
form = UserProfileForm(request.POST or None)
instance = Profile.objects.all().filter(user__username=request.user).values # This is the place I need to create a single queryset.
if request.method == "POST" and form.is_valid():
form = UserProfileForm(request.POST, instance=instance)
user_form = form.save()
print("POST event")
else:
form = UserProfileForm(instance=instance)
print(form)
return render(request, 'frontend/profile_edit.html', {'form': form})
我在模板中手动创建表单,所以我想要像 {{ form.username }} {{ form.profile.address }} 或类似的东西。我可能做得不好,我是 django 的新手。
更新 完整的解决方案
完成在代码和模板中访问用户和配置文件模型的步骤。
我决定不使用我自己的模型替换 User 模型,以防我错过了 django 提供的功能。这似乎也使以后可能会受到伤害的事情复杂化。因此,我使用了单独的 UserProfile 模型并将其附加到 User 模型中。这是我为未来的读者所做的。
models.py
from django.db.models.signals import post_save
class UserProfile(models.Model):
#take note of the related_name='profile' this is used to reference the fields in code and template.
#Each field of type 'text' I added default='' at the end, I got an error when it was int based so I removed the flag for that field. I read this might cause an error when you try and auto-create the profile, see what works for you and you might not want it.
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
country = models.CharField(max_length=2, blank=True, null=True, default='')
...
# Auto-create the profile upon user account creation. It's important to start with a fresh database so the user and profile ID's match.
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
# Create your models here.
#In code, you can access your user and profile field data like so.
request.user.profile.fieldname
request.user.fieldname
In template you can do the same
{{ user.fieldname }}
{{ user.profile.fieldname }}
【问题讨论】:
标签: python django python-3.6 django-2.0