简体   繁体   中英

Django get_or_create not creating new record in the model

I'm having issue with the get_or_create statement. It gets the record if there is one but isnt creating a record. I have defaults in all of my model fields.

My view.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)

The traceback im getting is:

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)

The models.py im working on is:

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']

You don't need to pass the model class to the method.

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

should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM