gpt4 book ai didi

python - Django get_or_create 未在模型中创建新记录

转载 作者:行者123 更新时间:2023-12-02 00:11:12 26 4
gpt4 key购买 nike

我在 get_or_create 语句方面遇到问题。如果有记录,它会获取记录但不创建记录。我的所有模型字段都有默认值。

我的观点.py

    from django.contrib.auth.decorators import login_required
from django.shortcuts import render, HttpResponseRedirect, Http404, get_object_or_404
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe

# Create your views here.
from .models import UserProfile



@login_required
def profile_view(request):
user = request.user
account = request.user
profile = UserProfile.objects.get_or_create(UserProfile, user=user)
context = {'profile': profile, 'account': account, }
template = 'profiles/profile.html'
return render(request, template, context)

我得到的回溯是:

ypeError at /profiles/
get_or_create() takes exactly 1 argument (3 given)
Request Method: GET
Request URL: http://127.0.0.1:8000/profiles/
Django Version: 1.6.5
Exception Type: TypeError
Exception Value:
get_or_create() takes exactly 1 argument (3 given)

我正在处理的 models.py 是:

class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
city = models.CharField(max_length=120, default="Add your city")
country = models.CharField(max_length=120, default="Add your country") #(max_length=2, choices=[(x[0], x[3]) for x in country.COUNTRIES])
zipcode = models.CharField(max_length=8, default="Add your zip/postcode")
birthyear = models.IntegerField(max_length=4, default="Add your birthyear")
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)

def __unicode__(self):
return str(self.user.username)

class Meta:
ordering = ['-updated', '-timestamp']

最佳答案

您不需要将模型类传递给该方法。

profile = UserProfile.objects.get_or_create(UserProfile, user=user)

应该是

profile, created = UserProfile.objects.get_or_create(user=user)

关于python - Django get_or_create 未在模型中创建新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28867237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com