Django抛出异常:ModelForm没有指定模型类

时间:2015-12-30 17:23:05

标签: python django

我正在使用Django Framework并抛出此异常:ModelForm没有指定模型类。

这是我的代码:

views.py

from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect
from DjangoApp1.forms import login_form
from django.shortcuts import render  #For render templates

def login_view(request):    

    form = login_form()
    context = { 'form': form, 'mensaje':'Logeandose'}

    if request.method == 'POST':        
        form = login_form(request.POST)     
        usuario = request.POST.get('username')
        contrase = request.POST.get('password')
    # Hacer el login
        user = authenticate(username=usuario, password=contrase)
        if user is not None and user.is_active:
            login(request, user)
            context['mensaje'] =  u'Logeado como  %s, contraseña %s' % (usuario, contrase)
        else:
            context['mensaje'] =  u'No usuario  o contraseña incorrecta'

    return render (request, 'DjangoApp1/login.html', context)

我在登录表单中的models.py:

models.py

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

class login_form(forms.ModelForm):
    username = forms.SlugField (max_length=8, 
                             label='Usuario: ')
    password = forms.SlugField (max_length=8, 
                        widget=forms.PasswordInput(),  
                        label='Contraseña:',
                        help_text='Hasta 8 letras')

class Meta:
    model  = User
    fields = ('username',  'password')

1 个答案:

答案 0 :(得分:1)

您需要缩进class Meta,因为它是模型表单类定义的一部分:

class login_form(forms.ModelForm):
    username = forms.SlugField (max_length=8, 
                             label='Usuario: ')
    password = forms.SlugField (max_length=8, 
                        widget=forms.PasswordInput(),  
                        label='Contraseña:',
                        help_text='Hasta 8 letras')
    class Meta:
        model  = User
        fields = ('username',  'password')

Django doc详细解释了这一点。