- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试创建一个视频博客,用户可以在其中创建自己的帐户和个人资料。我还添加了用于注册的电子邮件验证。但问题是当我尝试使用 Django 2.2.5 开发服务器注册新用户时出现此错误(“重复键值违反唯一约束”“account_profile_mobile_number_key”详细信息: key (移动编号)=()已经存在。 ) 重复。我想如果我删除数据库这可能会解决问题。我删除了数据库并创建了另一个数据库。然后我已经能够创建一个用户,但再次出现该问题。我再次删除了数据库。这样,我试了很多次都无法解决问题。我在谷歌上搜索了解决方案并得到了很多答案,但由于我只是在学习过程中,所以它们对我来说很难理解。我在 Ubuntu 18.04 上使用 Python 3.6、Django 2.2.5、Postgresql 11。伙计们,你能看看我的代码并告诉我解决问题的最简单方法吗?提前致谢!
这是回溯
IntegrityError at /account/register/
duplicate key value violates unique constraint
"account_profile_mobile_number_key"
DETAIL: Key (mobile_number)=() already exists.
Request Method: POST
Request URL: http://127.0.0.1:8000/account/register/
Django Version: 2.2.5
Exception Type: IntegrityError
Exception Value:
duplicate key value violates unique constraint "account_profile_mobile_number_key"
DETAIL: Key (mobile_number)=() already exists.
Exception Location: /media/coduser/2NDTB/ProgramingPROJ/WebDevelopment/DjangoProject/MY-PROJECT/alternative/ex1/myvenv/lib/python3.6/site-packages/django/db/backends/utils.py in _execute, line 84
Python Executable: /media/coduser/2NDTB/ProgramingPROJ/WebDevelopment/DjangoProject/MY-PROJECT/alternative/ex1/myvenv/bin/python
Python Version: 3.6.8
Python Path:
['/media/coduser/2NDTB/ProgramingPROJ/WebDevelopment/DjangoProject/MY-PROJECT/alternative/ex1',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/media/coduser/2NDTB/ProgramingPROJ/WebDevelopment/DjangoProject/MY-PROJECT/alternative/ex1/myvenv/lib/python3.6/site-packages']
Server time: Wed, 11 Sep 2019 01:11:15 +0000
这里是账户模型
from django.db import models
from django.conf import settings
from PIL import Image
class Profile(models.Model):
GENDER_CHOICES = (
('male', 'Male'),
('female', 'Female'),
('other', 'Other'),
('tell you later', 'Tell you later')
)
MARITAL_CHOICES = (
('married', 'Married'),
('unmarried', 'Unmarried'),
('single', 'Single'),
('divorced', 'Divorced'),
('tell you later', 'Tell you later')
)
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
date_of_birth = models.DateField(blank=True, null=True)
gender = models.CharField(
max_length = 14,
choices = GENDER_CHOICES,
default = 'tell you later'
)
marital_status = models.CharField(
max_length = 14,
choices = MARITAL_CHOICES,
default = 'tell you later'
)
name_of_father = models.CharField(max_length = 30)
name_of_mother = models.CharField(max_length = 30)
present_address = models.CharField(max_length = 200)
permanent_address = models.CharField(max_length = 200)
mobile_number = models.CharField(max_length = 14, unique = True, db_index=True)
emergency_contact_number = models.CharField(max_length = 14)
smart_nid = models.CharField(max_length = 14, unique = True, db_index=True)
nationality = models.CharField(max_length = 20)
profile_picture = models.ImageField(default = 'default_profile.jpg', upload_to='users/%Y/%m/%d/')
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.profile_picture.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.profile_picture.path)
这是forms.py
from django import forms
from django.contrib.auth.models import User
from .models import Profile
class BaseForm(forms.Form):
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', '')
super(BaseForm, self).__init__(*args, **kwargs)
class BaseModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', '')
super(BaseModelForm, self).__init__(*args, **kwargs)
class LoginForm(forms.Form):
username = forms.CharField(label_suffix='')
password = forms.CharField(widget=forms.PasswordInput, label_suffix='')
# BaseModelForm has been used instead of forms.ModelForm to remove the colon
class UserRegistrationForm(BaseModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
help_texts = {
'username': 'Letters, digits and @/./+/-/_ only',
}
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError(
'Please use another Email, that is already taken')
return email
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
# This will let user to edit their profile
class UserEditForm(BaseModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
# This will let user to edit their profile
class ProfileEditForm(BaseModelForm):
class Meta:
model = Profile
fields = ('date_of_birth', 'gender', 'marital_status', 'profile_picture',
'name_of_father', 'name_of_mother', 'present_address',
'permanent_address', 'mobile_number', 'emergency_contact_number',
'smart_nid', 'nationality')
这里是account app的views.py
from django.http import HttpResponse
from django.shortcuts import render , redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from .forms import LoginForm, UserRegistrationForm, \
UserEditForm, ProfileEditForm
# For email verification
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from .token_generator import account_activation_token
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
# end of email verification
# User Profile
from .models import Profile
# For flash message
from django.contrib import messages
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request,
username=cd['username'],
password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated '\
'successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
def register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
new_user.is_active = False # line for email verification
# Set the chosen password
new_user.set_password(
user_form.cleaned_data['password']
)
# Save the User object
new_user.save()
# Create the user profile
Profile.objects.create(user = new_user)
current_site = get_current_site(request)
email_subject = ' Activate Your Account'
message = render_to_string('account/activate_account.html', {
'user': new_user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(new_user.pk)),
'token': account_activation_token.make_token(new_user),
})
to_email = user_form.cleaned_data.get('email')
email = EmailMessage(email_subject, message, to=[to_email])
email.send()
return redirect('account_activation_sent')
else:
user_form = UserRegistrationForm()
return render(request,
'account/register.html',
{'user_form': user_form})
def account_activation_sent(request):
return render(request, 'account/account_activation_sent.html')
def account_activation_invalid(request):
return render(request, 'account/account_activation_invalid.html')
def activate_account(request, uidb64, token):
try:
uid = force_bytes(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
return redirect('blog-home')
else:
return render(request, 'account_activation_invalid.html')
@login_required
def edit(request):
if request.method == 'POST':
user_form = UserEditForm(instance=request.user,
data=request.POST)
profile_form = ProfileEditForm(instance=request.user.profile,
data=request.POST,
files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Profile updated successfully')
else:
messages.error(request, 'Error updating your profile')
else:
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(instance=request.user.profile)
return render(request,
'account/profile.html',
{'user_form': user_form,
'profile_form': profile_form})
这是 token 生成器
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active)
)
account_activation_token = TokenGenerator()
最佳答案
使用空字符串而不将它们转换为 null 是我的错误。其实我对Django不是很了解,但是我正在学习。根据 -mu is too short 在评论部分提供的解决方案,我已经能够解决问题。所以归功于 -mu 太短了
对于解决方案,我刚刚在 mobile_number 字段中添加了一个额外的参数 - null = True。就是这样。它解决了我的问题。
这是解决方案
mobile_number = models.CharField(max_length = 14, unique = True, db_index=True, null = True)
关于django - 这个问题 "duplicate key value violates unique constraint"困扰了我将近一个星期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57881034/
我正在尝试使用 flot 绘制 SQL 数据库中的数据图表,这是使用 php 收集的,然后使用 json 编码的。 目前看起来像: [{"month":"February","data":482},
我有一个来自 php 行的 json 结果,类似于 ["value"]["value"] 我尝试使用内爆函数,但得到的结果是“value”“value” |id_kategori|created_at
脚本 1 将记录 two 但浏览器仍会将 select 元素呈现为 One。该表单还将提交值 one。 脚本 2 将记录、呈现和提交 两个。我希望它们是同义词并做同样的事情。请解释它们为何不同,以及我
我的python字典结构是这样的: ips[host][ip] 每行 ips[host][ip] 看起来像这样: [host, ip, network, mask, broadcast, mac, g
在 C# 中 我正在关注的一本书对设置和获取属性提出了这样的建议: double pri_test; public double Test { get { return pri_test; }
您可能熟悉 enum 位掩码方案,例如: enum Flags { FLAG1 = 0x1, FLAG2 = 0x2, FLAG3 = 0x4, FLAG4 = 0x8
在一些地方我看到了(String)value。在一些地方value.toString() 这两者有什么区别,在什么情况下我需要使用哪一个。 new Long(value) 和 (Long)value
有没有什么时候 var result = !value ? null : value[0]; 不会等同于 var result = value ? value[0] : null; 最佳答案 在此处将
我正在使用扫描仪检测设备。目前,我的条形码的值为 2345345 A1。因此,当我扫描到记事本或文本编辑器时,输出将类似于 2345345 A1,这是正确的条形码值。 问题是: 当我第一次将条形码扫描
我正在读取 C# 中的资源文件并将其转换为 JSON 字符串格式。现在我想将该 JSON 字符串的值转换为键。 例子, [ { "key": "CreateAccount", "text":
我有以下问题: 我有一个数据框,最多可能有 600 万行左右。此数据框中的一列包含某些 ID。 ID NaN NaN D1 D1 D1 NaN D1 D1 NaN NaN NaN NaN D2 NaN
import java.util.*; import java.lang.*; class Main { public static void main (String[] args) thr
我目前正在开发我的应用程序,使其设计基于 Holo 主题。在全局范围内我想做的是工作,但我对文件夹 values、values-v11 和 values-v14. 所以我知道: values 的目标是
我遇到了一个非常奇怪的问题。 我的公司为我们的各种 Assets 使用集中式用户注册网络服务。我们一般通过HttpURLConnection使用请求方法GET向Web服务发送请求,通过qs设置参数。这
查询: UPDATE nominees SET votes = ( SELECT votes FROM nominees WHERE ID =1 ) +1 错误: You can't specify
如果我运行一段代码: obj = {}; obj['number'] = 1; obj['expressionS'] = 'Sin(0.5 * c1)'; obj['c
我正在为我的应用创建一个带有 Twitter 帐户的登录页面。当我构建我的项目时会发生上述错误。 values/strings.xml @dimen/abc_text_size_medium
我在搜索引擎中使用以下 View : CREATE VIEW msr_joined_view AS SELECT table1.id AS msr_id, table1.msr_number, tab
为什么验证会返回此错误。如何解决? ul#navigation li#navigation-3 a.current Value Error : background-position Too
我有一个数据名如下 import pandas as pd d = { 'Name' : ['James', 'John', 'Peter', 'Thomas', 'Jacob', 'Andr
我是一名优秀的程序员,十分优秀!