我觉得将用户模型和用户配置文件模型分开来生成两个单独的视图和应用程序是很困难的。它对user有效,但对user无效,我对user使用了userchangeform,对userprofile使用了forms.modelforms。我正在尝试使用updateview,这样用户就可以看到并更新他的信息。代码:
#user profile models file
from django.db import models
from easyinstall import settings
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
picture = models.ImageField(upload_to='uploads/profile_images', blank=True)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
website = models.URLField(blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'users profiles'
def __str__(self):
return self.user.username
用户配置文件表单
from django import forms
from .models import UserProfile
class EditProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('picture', 'bio', 'location', 'birth_date', 'website',)
用户配置文件视图
from .models import UserProfile
from django.views.generic import UpdateView
from django.urls import reverse_lazy
from .forms import EditProfileForm
class ProfileUpdateView(UpdateView):
model = UserProfile
form_class = EditProfileForm
template_name = 'profiles/profileupdate.html'
success_urls = reverse_lazy('profiles')
pk_url_kwarg = 'UserProfile_pk'
context_object_name = 'UserProfile'
我真的坚持" pk“的事情,如何获得用户配置文件的pk并使用它?是否可以在profile表中包含id和user_id?
请查看模板:
{% load socialaccount %}
<h1>Django Allauth Tutorial</h1>
{% if user.is_authenticated %}
<p>Welcome {{ user.username }} !!!</p>
<li><a href="{% url 'settings' %}">change settings</a></li>
<li><a href="{% url 'profile_update' UserProfile_pk=user.pk %}">Edit Profile</a></li>
{% else %}
{% csrf_token %}
<ul>
<li><a href="{% provider_login_url 'linkedin' %}">Sign Up</a></li>
</ul>
{% endif %}
和urls:
from django.urls import path
from .views import UsersList, ProfileUpdateView
urlpatterns = [
path('', UsersList.as_view(), name='profiles'),
path('profile/(?P<UserProfile_pk>\d+)/edit/', ProfileUpdateView.as_view(), name='profile_update'),
]
我使用的是Django2.1,python3。
谢谢
发布于 2019-03-04 03:12:02
您需要使用配置文件的pk链接到编辑视图,而不是用户。
{% url 'profile_update' UserProfile_pk=user.userprofile.pk %}
https://stackoverflow.com/questions/54972378
复制相似问题