首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我的UserProfile模型表单拒绝使用用户id来更新和填充updateview类中的表单:

我的UserProfile模型表单拒绝使用用户id来更新和填充updateview类中的表单:
EN

Stack Overflow用户
提问于 2019-03-04 02:42:51
回答 1查看 47关注 0票数 0

我觉得将用户模型和用户配置文件模型分开来生成两个单独的视图和应用程序是很困难的。它对user有效,但对user无效,我对user使用了userchangeform,对userprofile使用了forms.modelforms。我正在尝试使用updateview,这样用户就可以看到并更新他的信息。代码:

代码语言:javascript
复制
#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

用户配置文件表单

代码语言:javascript
复制
from django import forms
from .models import UserProfile

class EditProfileForm(forms.ModelForm):

 class Meta:
        model = UserProfile
        fields = ('picture', 'bio', 'location', 'birth_date', 'website',)

用户配置文件视图

代码语言:javascript
复制
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?

请查看模板:

代码语言:javascript
复制
{% 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:

代码语言:javascript
复制
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。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-04 03:12:02

您需要使用配置文件的pk链接到编辑视图,而不是用户。

代码语言:javascript
复制
{% url 'profile_update' UserProfile_pk=user.userprofile.pk %}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54972378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档