- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我将此作为我的用户应用程序 urls.py:
from django.conf.urls import url
from users import views
app_name = 'users'
urlpatterns = [
url(r'^$',views.UserListView.as_view(),name='user_list'),
url(r'^(?P<pk>\d+)/$',views.UserProfileView.as_view(),name='user_profile'),
url(r'^(?P<pk>\d+)/edit$',views.UserEditProfileView.as_view(),name='user-profile-edit'),
url(r'^login/$',views.user_login,name='user_login'),
url(r'^logout/$',views.user_logout,name='user_logout'),
url(r'^register/$',views.register,name='register'),
]
此网址模式 url(r'^(?P<pk>\d+)/$',views.UserProfileView.as_view(),name='user_profile'),
适用于此网址 http://127.0.0.1:8000/user/1/
但是当我创建一个新用户(用户 2)并登录时,我得到 page not found (404)
当我点击与该模式相关的按钮时
这些不是错误,但这就是它告诉我的内容:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/user/3/
Raised by: users.views.UserProfileView
No user profile info found matching the query
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
所以基本上 pk 3 用户的个人资料位于 http://127.0.0.1:8000/user/2/
而不是http://127.0.0.1:8000/user/3/
(或者反过来,不太确定)。
这也是我的项目网址:
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from users import views
from feed import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.HomeView.as_view(),name='index'),
url(r'^user/',include('users.urls',namespace='users')),
url(r'^feed/',include('feed.urls',namespace='feed')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
用户应用 View .py:
from django.shortcuts import render,get_object_or_404
from users.forms import UserForm,UserProfileForm
from users.models import UserProfileInfo
from feed.models import UserPost
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account now active")
else:
print("Login Unsuccessful")
return HttpResponse("Username and/or password are not correct")
else:
return render(request,'login.html',{})
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request,'register.html',{
'user_form':user_form,
'profile_form':profile_form,
'registered':registered
})
@login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
class UserListView(ListView):
model = UserProfileInfo
ordering = ['-join_date']
def get_context_data(self, **kwargs):
context = super(UserListView, self).get_context_data(**kwargs)
context['user_list'] = User.objects.all()
return context
class UserProfileView(DetailView):
model = UserProfileInfo
template = 'users/userprofile.html'
def get_context_data(self, **kwargs):
context = super(UserProfileView, self).get_context_data(**kwargs)
context['user_post'] = UserPost.objects.all()
return context
class UserEditProfileView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = '/users_detail.html'
form_class = UserProfileForm
model = UserProfileInfo
用户应用模型.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from users.choices import *
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(max_length=50,default='User')
join_date = models.DateTimeField(default=timezone.now)
profile_pic = models.ImageField(upload_to='profile_pics',blank=True)
location = models.CharField(max_length=150)
title = models.CharField(max_length=250)
user_type = models.IntegerField(choices=USER_TYPE_CHOICES,default=1)
website = models.URLField(max_length=100,blank=True)
about = models.TextField(max_length=500,default='about')
twitter = models.CharField(max_length=50,blank=True)
dribbble = models.CharField(max_length=50,blank=True)
github = models.CharField(max_length=50,blank=True)
def __str__(self):
return self.user.username
更新:
新用户应用模型.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(max_length=50,default='User')
join_date = models.DateTimeField(default=timezone.now)
profile_pic = models.ImageField(upload_to='profile_pics',blank=True)
location = models.CharField(max_length=150)
title = models.CharField(max_length=250)
user_type = models.IntegerField(choices=USER_TYPE_CHOICES,default=1)
website = models.URLField(max_length=100,blank=True)
about = models.TextField(max_length=500,default='about')
twitter = models.CharField(max_length=50,blank=True)
dribbble = models.CharField(max_length=50,blank=True)
github = models.CharField(max_length=50,blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
def __str__(self):
return self.user.username
新错误:
IntegrityError at /user/register/
UNIQUE constraint failed: users_userprofile.user_id
错误回溯:
Traceback (most recent call last):
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: users_userprofile.user_id
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/garrettlove/Desktop/evverest/users/views.py", line 58, in register
profile.save()
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save
force_update=force_update, update_fields=update_fields)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert
using=using, raw=raw)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/models/query.py", line 1076, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/anaconda/envs/test/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: users_userprofile.user_id
最佳答案
你所做的一切都是正确的。但是错误是不言自明的。您的 UserProfileInfo
与 User
模型一对一相关。所以一旦你创建了一个新用户。将创建一个新的用户配置文件信息,但不会自动创建。因此它给出了错误。
You need to send a signal to create a new userprofileinfo whenever a new user is created.
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(max_length=50,default='User')
. . . . . . . .
. . . . . . . .
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
最后,我更改了模型名称,因此请相应地更改它。现在,它将完美地工作。
关于python - URL 中的 Django (?P<pk>\d+) 部分工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46127428/
甲骨文: create table t7(c1 number primary key,c2 number); insert into t7 values (1,3); insert into t
谁能告诉我为什么点击模板链接生成的url是/.pk。我想了解 url 是如何工作的。这里是 Django 新手。 Traceback (most recent call last): File "
我有以下 MySQL 触发器。它因 tbl_users 的更新而被触发。如果当天已经存在记录,它将用一些信息更新 tbl_user_stats;如果当天没有记录,它将在 tbl_user_stats
已知:tX_1.name 永远不能为 NULL,长度可变,最多 45 个字符,并且必须始终是唯一的。 哪些因素会影响是否应使用代理 PK 加唯一列(架构 1)或 PK 自然键是否使用第一个表的唯一列作
我有一个包含复合 PK(code_id、user_id)的表,它已经有 100k 条记录。从复合 PK 移动到单个 PK 是否安全,如下例所示? ALTER TABLE orders DROP C
为什么这个模型没有创建 pk 并提示相关模型的 pk 的完整性? 创建 UserProfile 的新实例时,它不会创建主键。 我正在遵循一对一的说明 in this tutorial (这就是所有 @
注意:我是 JPA 开发的新手,正在快速学习试用,所以请原谅我可能遗漏的任何明显内容。 以下是相关的 JPA 实体。地址未列出,但它是一个非常简单的实体,具有一个名为 id 的 @Id。 ShipTo
我们的系统中有两个实体,如下所示: Invoice:[InvoiceID, OrgID] 是表示为 bean 的主键,并使用 @IdClass 注释与 Invoice 相关联 WorkflowStat
场景:我遇到了一些在事务中将 JPA 与 JDBC 混合的代码。 JDBC 正在对基本上是空白行的表执行 INSERT,将主键设置为 (SELECT MAX(PK) + 1) 并将 middleNam
我有一个包含 3 个表的数据库:类别、项目、关系。 categories 包含类别。商品存储在items中,relation是一个绑定(bind)表,它存储了产品id和类别id或类别。 对于给定的项目
问题 当我尝试导入 CSV 文件时,我收到 key “PRIMARY”的重复条目“x-x-xx-x-x-x” - PK 错误。 PK 本身是两个连接的 varchar。据我所知,连接永远不会重复。 我
我正在尝试使用连接从两个大表中进行选择: EXPLAIN SELECT SQL_NO_CACHE e.* FROM `table_A` e JOIN (SELECT id FROM
我有这个 post_list.html 文件:(忽略第二个 'blog:post_detail' url) {% for post in post_list %} {{ post.title }}
我需要使用 JPA 处理现有数据库表。这些表使用复合主键。外键属性与表的主键重叠。 简化示例,每个“订单”都有许多“OrderItems” Table Order
据我所知,每当我在 JPA/Hibernate 实体内的 Long 字段上使用 @Id 和 @GeneratedValue 时,我实际上是在使用代理键,我认为这是定义主键的一种非常好的方式,考虑到我在
所以我有这段代码: request = self.factory.get(reverse('portal-edit-automation', args=(self.rule.id,))) respon
当在MySQL中使用InnoDB存储引擎时,如果在创建表时不指定PRIMARY KEY,则使用隐藏唯一索引作为聚集索引。由于数据字典上的互斥锁,我了解到这些隐藏索引可能会导致争用。 我的问题是 - 如
我正在尝试删除 table1 中与 table2 中具有匹配 PK 的所有行。尽管我的 WHERE 子句使用了键,但我收到错误 1175。我熟悉切换安全模式,但这不应该成为问题,因为我的 WHERE
我正在尝试更新具有外键字段的 View 的记录,因此出现错误,因为我尝试更新没有外键字段的另一个模型并且效果很好。 还有其他类似的问题,但就我而言,我通过了 pk。 urls.py urlpatte
Beeferman 的 PK 和 WindowDIFF 的 Python NLTK 实现从两者的 python segeval 实现中得到完全不同的结果。 使用相同的参数。 hyp: 01001000
我是一名优秀的程序员,十分优秀!