OperationalError 1054,"未知列' xx'在'字段列表'"

时间:2014-03-17 15:10:50

标签: python django

创建注册表单,供用户在注册后填写,但是,在测试期间,从views.py中的注册功能发布的数据会生成操作错误,未知列' realname'在字段列表中。我在models.py和form.py中有真实姓名。我也与django同步并完成了与南方的迁移。需要帮助解决问题!

Models.py:

from django.db import models
from django.contrib.auth.models import User

class ProfileUser(models.Model):
    user = models.OneToOneField(User)
    realname = models.CharField(null=True, max_length=254, blank=True)
    birthday = models.DateField(null=True,blank=True)
    city = models.CharField(max_length=50,blank=True)
    state = models.CharField(max_length=50,blank=True)
    image = models.ImageField(upload_to='user_images/', blank=True)

    #admin level and additional infomation
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    #Override the _unicode_() method to return out something meaningful
    def __unicode__(self):
        return '%s %s %s %s %s' % (self.realname, self.birthday, self.city, self.state, self.image) 


class ProfileStatsUser(models.Model):
    profileuser = models.OneToOneField(ProfileUser)
    user_title = models.CharField(max_length=254, verbose_name="Influencer Level", blank=True)
    user_points = models.IntegerField(null=False, verbose_name="Style Points", blank=True)


    def _unicode_(self):
        return '%s %s' % (self.user_title, self.user_points)

forms.py:

#coding=utf-8
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.forms import extras
from models import ProfileUser, ProfileStatsUser
import time

now=time.localtime()

###### Login for users ###########
class LoginForm(forms.ModelForm):
    username=forms.CharField(label=_(u"username"),max_length=30,widget=forms.TextInput(attrs={'size': 20,}))
    password=forms.CharField(label=_(u"password"),max_length=30,widget=forms.PasswordInput(attrs={'size': 20,}))

    class Meta:
        """docstring for Meta"""
        model = User


###### Signup for users ###########
class SignupForm(forms.ModelForm):
    email=forms.EmailField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Email', 'required':True}))
    username=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Username','required':True}))
    password=forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':True}))
    password2=forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Re-Enter Password','required':True}))


    class Meta:
        """ To Specify the fields from User model from django, and to prevent abstraction"""
        model = User
        fields = ['email', 'username', 'password', 'password2']


    def clean_username(self):
        users = User.objects.filter(username__iexact=self.cleaned_data["username"])
        if not users:
            return self.cleaned_data["username"]
        raise forms.ValidationError("This username already exist")

    def clean_email(self):
        emails = User.objects.filter(email__iexact=self.cleaned_data["email"])
        if not emails:
            return self.cleaned_data["email"]
        raise forms.ValidationError("Email is already registered")

    def clean_password2(self):
        password = self.cleaned_data.get("password")
        password2 = self.cleaned_data.get("password2")

        if not password2:
            raise forms.ValidationError("You must confirm your password")

        if password != password2:
            raise forms.ValidationError("The password does not match ")

        return password2

###### Registration for users ###########
class RegisterForm(forms.ModelForm):
    realname=forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Real Name','required':True}))
    birthday=forms.DateField(label=_(u"birthdate(mm/dd/yy)"),widget=extras.SelectDateWidget(years=range(1900, now[0]+1)),required=False)
    city=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'City','required':True}))
    state=forms.CharField(max_length=2, widget=forms.TextInput(attrs={'placeholder': 'State','required':True}))
    image = forms.ImageField(required=False)

    class Meta:
        """ To Specify the fields from User model and the extension of the user model from django, and to prevent abstraction"""
        model = ProfileUser
        fields = ['realname', 'birthday','city','state','image']



###### Profile for users ###########
class ProfileForm(forms.Form):
    realname=forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Real Name','required':True}))
    email=forms.EmailField(max_length=30, widget=forms.TextInput(attrs={'required':False}))
    username=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'required':False}))
    birthday=forms.DateField(widget=forms.DateInput(attrs={'required':False}))
    city=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'required':False}))
    state=forms.CharField(max_length=2, widget=forms.TextInput(attrs={'required':False}))

    class Meta:
        """ To Specify the fields from User model and the extension of the user model from django, and to prevent abstraction"""
        model = ProfileUser
        fields = ['realname', 'birthday','city', 'state', 'email', 'username']

views.py:

#coding=utf-8
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login as auth_login ,logout as auth_logout
from django.utils.translation import ugettext_lazy as _
from forms import LoginForm, SignupForm, RegisterForm, ProfileForm
from models import ProfileUser, ProfileStatsUser
from PIL import Image


###### Login for users ###########
def login(request):
    template_var={}
    form = LoginForm()
    if request.method == 'POST':
        form = LoginForm(request.POST.copy())
        if form.is_valid():
            login(request,form.cleaned_data["username"],form.cleaned_data["password"])
            return HttpResponseRedirect(reverse("login"))
    template_var["form"]=form
    return render_to_response("registration/login.html",template_var,context_instance=RequestContext(request))

def _login(request,username,password):
    ret=False
    user=authenticate(username=username,password=password)
    if user:
        if user.is_active:
            auth_login(request,user)
            ret=True
        else:
            messages.add_message(request, messages.INFO, _(u'user is not active'))
    else:
        messages.add_message(request, messages.INFO, _(u'user not exsist'))
    return ret


###### Signup for users ###########
def signup(request):
    template_var={}
    form = SignupForm()
    if request.method=="POST":
        form=SignupForm(request.POST.copy())
        if form.is_valid():
            username=form.cleaned_data["username"]
            email=form.cleaned_data["email"]
            password=form.cleaned_data["password"]
            user=User.objects.create_user(username,email,password)
            user.save()
            _login(request,username,password)
            return HttpResponseRedirect("register")
    template_var["form"]=form
    return render_to_response("registration/signup.html",template_var,context_instance=RequestContext(request))

###### Registration for users ###########
def register(request):
    template_var={}
    form = RegisterForm()  
    if request.user.is_authenticated():
        if request.method=="POST":
           form=RegisterForm(request.POST,request.FILES)
           if form.is_valid():
                realname=form.cleaned_data["realname"]
                birthday=form.cleaned_data["birthday"]
                city = form.cleaned_data["city"]
                state = form.cleaned_data["state"]   
                reqfile = request.FILES.get("image", False)
                registeruser=ProfileUser.objects.create(user=request.user, birthday=birthday,
                    city=city, state=state, image=reqfile)
                registeruser.save()
                return HttpResponseRedirect(reverse("dashboard"))          
        template_var["form"]=form        
        return render_to_response("registration/register.html",template_var,context_instance=RequestContext(request))   


###### Profile for users ###########
def dashboard(request):
    template_var={}
    form=ProfileForm()
    if request.user.is_authenticated():
        user = ProfileUser.objects.get(user=request.user)
        first_name=user.first_name
        last_name=user.last_name
        email=user.email
        username=user.username
        birthday=user.birthday
        city=user.city
        state=user.state

        #None form elements
        title=user.user_title
        points=user.user_points
        image=user.image
        template_var["title"]=title
        template_var["points"]=points
        template_var["image"]=image

        template_var["form"]=form  
        template_var["is_authenticated"]= True
    return render_to_response("userprofile/dashboard.html",template_var) 

回溯信息:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/signup/register/

Django Version: 1.6.2
Python Version: 2.7.1
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'home',
 'profiles',
 'south')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/amechiegbe/Desktop/cm_dev/Indieitude/profiles/views.py" in register
  73.                     city=city, state=state, image=reqfile)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/manager.py" in create
  157.         return self.get_queryset().create(**kwargs)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/query.py" in create
  319.         obj.save(force_insert=True, using=self.db)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/base.py" in save
  545.                        force_update=force_update, update_fields=update_fields)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  573.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  654.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  687.                                using=using, raw=raw)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
  232.         return insert_query(self.model, objs, fields, **kwargs)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
  1511.     return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  899.             cursor.execute(sql, params)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/backends/util.py" in execute
  69.             return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/backends/util.py" in execute
  53.                 return self.cursor.execute(sql, params)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  99.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/backends/util.py" in execute
  53.                 return self.cursor.execute(sql, params)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
  124.             return self.cursor.execute(query, args)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/MySQLdb/cursors.py" in execute
  205.             self.errorhandler(self, exc, value)
File "/Users/amechiegbe/Desktop/cm_dev/venv/lib/python2.7/site-packages/MySQLdb/connections.py" in defaulterrorhandler
  36.     raise errorclass, errorvalue

Exception Type: OperationalError at /signup/register/
Exception Value: (1054, "Unknown column 'realname' in 'field list'")

0 个答案:

没有答案