[英]django.db.utils.IntegrityError: UNIQUE constraint failed: mode_setting.user_id
I am new to Javascript, I am currently learning to debug errors that I am receiving in the Console.我是 Javascript 的新手,我目前正在学习调试我在控制台中收到的错误。
In my project, I am adding a theme choosing option for each user logged into the website.在我的项目中,我为每个登录网站的用户添加了一个主题选择选项。 Currently, it is showing the 2 themes when I click the buttons but it is not saving the theme for each user.
目前,当我单击按钮时它显示 2 个主题,但它没有为每个用户保存主题。
I have created an app in my Django Project and everything is as covered in the tutorial I am following except that in the console I am receiving errors every time I select a theme from the buttons:我在我的 Django 项目中创建了一个应用程序,所有内容都在我遵循的教程中进行了介绍,除了在控制台中我每次 select 按钮主题时都会收到错误:
(index):573 POST http://127.0.0.1:8000/update_theme/ 500 (Internal Server Error)
and in the Terminal this error:在终端中出现此错误:
django.db.utils.IntegrityError: UNIQUE constraint failed: mode_setting.user_id
Here is the base template:这是基本模板:
<link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet">
<!-- Mode -->
<div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right">
<button onclick="swapStyles('app-light.css')" type="button" class="btn btn-secondary">Light Mode</button>
<button onclick="swapStyles('app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button>
</div>
<!-- Mode -->
Javascript Javascript
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var cssFile = "{% static 'css' %}"
function swapStyles(sheet){
document.getElementById('mystylesheet').href = cssFile + '/' + sheet
localStorage.setItem('theme', sheet)
updateTheme(sheet)
}
function loadSettings(){
//Call data and set local storage
var url = "{% url 'mode:user_settings' %}"
fetch(url, {
method:'GET',
headers:{
'Content-type':'application/json'
}
})
.then((response) => response.json())
.then(function(data){
console.log('Data:', data)
var theme = data.value;
if (theme == 'light.css' || null){
swapStyles('light.css')
}else if(theme == 'dark.css'){
swapStyles('dark.css')
}
})
}
loadSettings()
function updateTheme(theme){
var url = "{% url 'mode:update_theme' %}"
fetch(url, {
method:'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'theme':theme})
})
}
</script>
Here is the model这是 model
class Setting(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True)
name = models.CharField(max_length=200, null=True)
value = models.CharField(max_length=200)
def __str__(self):
return self.name
Here is the views.py这是views.py
def userSettings(request):
user = request.user
setting = getattr(user, 'setting', None)
if setting:
seralizer = UserSerailizer(setting, many=False)
return JsonResponse(seralizer.data, safe=False)
else:
return JsonResponse({'message': "User don't have a setting."}, safe=False)
def updateTheme(request):
data = json.loads(request.body)
theme = data['theme']
user=request.user
setting = Setting.objects.get_or_create(user=user, value=theme, name=user.username)
setting.save()
print('Request:', theme)
return JsonResponse('Updated..', safe=False)
urls.py网址.py
app_name = 'mode'
urlpatterns = [
path('user_settings/', views.userSettings, name="user_settings"),
path('update_theme/', views.updateTheme, name="update_theme"),
]
serializer.py序列化程序.py
from .models import *
class UserSerailizer(serializers.ModelSerializer):
class Meta:
model = Setting
fields = '__all__'
My question reason I am receiving this error and how to fix it?我的问题是我收到此错误的原因以及如何解决?
You are using get_or_create
wrong as you are filtering by all fields and not finding already existing instance in database which results in get_or_create trying to create another one您正在使用
get_or_create
错误,因为您正在按所有字段进行过滤并且没有在数据库中找到已经存在的实例,这导致 get_or_create 尝试创建另一个实例
So you should move fields that just need to be updated to defaults as documented因此,您应该将只需要更新为记录的默认值的字段移动
setting = Setting.objects.get_or_create(user=user, defaults={'value': theme, 'name'= user.username)
Additionally此外
user.username
as field is data duplication which makes no senseuser.username
存储为字段是没有意义的数据重复setting.save()
after get_or_create
is unnecessary as you can use update_or_create
insteadget_or_create
之后调用setting.save()
是不必要的,因为您可以使用update_or_create
代替
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.