1

我正在创建一个 Django Web 应用程序,并希望通过传入用户的主键来使用通用 UpdateView。它适用于 DetailView,但不适用于 UpdateView。

我尝试指定模板名称,更改我的 urls.py 文件中的路径顺序。我还没有尝试过使用 slug,但我知道我应该能够使用 pk。

我正在使用来自 django.contrib.auth 的内置用户模型作为我的个人资料。

视图.py:

class Profile(generic.TemplateView):
    template_name = 'accounts/profile.html'

class ProfileUpdate(generic.UpdateView):
    model = User
    fields = ['first_name']
    template_name = 'accounts/profile_update_form.html'

模型.py

from django.db import models
from django.contrib import auth

# Create your models here.

class User(auth.models.User,auth.models.PermissionsMixin):
    readonly_fields = ('id',)

    def __str__(self):
        return self.username

class UserProfile(models.Model):
    user = models.OneToOneField(auth.models.User,on_delete=models.CASCADE)
    join_date = models.DateTimeField(auto_now=True)
    profile_pic = models.ImageField(upload_to='profile_pics',default='media/block-m.png')
    skills = models.TextField()
    major = models.CharField(max_length=128)
    grad_year = models.CharField(max_length=4)
    clubs = models.TextField() #make FK to Clubs
    opt_in = models.BooleanField(default=True)

    def __str__(self):
        return self.user.username

我的 urls.py 是最让我沮丧的。地址http://127.0.0.1:8000/accounts/profile/5/工作正常,但http://127.0.0.1:8000/accounts/profile/5/edit/返回 404 错误“找不到匹配的用户询问”。所以我知道 pk=5 存在,但不适用于以 /edit/ 结尾的网址。

网址.py:

from django.urls import path,include
from django.contrib.auth import views as auth_views
from . import views

app_name = 'accounts'

urlpatterns = [
    path('login/',auth_views.LoginView.as_view(template_name='accounts/login.html'),name='login'),
    path('logout',auth_views.LogoutView.as_view(),name='logout'),
    path('signup/',views.SignUp,name='signup'),
    path('profile/<int:pk>/',views.Profile.as_view(),name='profile'),
    path('profile/<int:pk>/edit/',views.ProfileUpdate.as_view(),name='profile_update'),
]

profile_update_form.html:

{% extends 'base.html' %}
{% load bootstrap4 %}

{% block content %}

<div class="container">
    <h2>Sign Up</h2>
    <form method="POST" enctype="multipart/form-data">
      {% csrf_token %}
      {% bootstrap_form form layout='inline' %}
      <input type="submit" class="btn btn-primary" value="Sign Up">
    </form>
</div>

{% endblock %}
4

2 回答 2

0

那是因为 user.pk 与同一用户 userprofile 的主键不同,如果您检查他们在数据库中可敬的表,您会看到差异,是的,起初我所做的最简单的解决方案是使用信号,这令人困惑:

 def profile_creation_signal(sender, instance, created, **kwargs) :

    if created:
        UserProfile.objects.create(pk=instance.id, user=instance)

post_save.connect(profile_creation_signal, sender=User)
于 2021-04-01T04:17:14.807 回答
0

它应该工作!

path('<username>/', ProfileView.as_view(), name="public_profile"),

class ProfileView(DetailView):
    model = User
    template_name = "pages/public_profile.html"
    context_object_name = "profile"
    slug_field = "username"
    slug_url_kwarg = "username"

您可以将 -username- 替换为唯一字段

于 2021-08-13T17:22:39.127 回答