为什么不以验证的形式工作?

时间:2014-05-08 06:43:40

标签: python django

请帮助纠正形状。

我创建了一个表单来输入AuthenticationCustomForm(从AuthenticationForm继承它):

from django.contrib.auth.forms import AuthenticationForm

class AuthenticationCustomForm(AuthenticationForm):
    username = forms.CharField(
        label='Имя пользователя',
        widget=forms.TextInput(attrs={
            'placeholder': 'Логин',
        }),     
    )

    password = forms.CharField(
        label='Пароль', 
        widget=forms.PasswordInput(attrs={
            'placeholder': 'Пароль',
        }),
    )

然后在views.py中创建:

def login(request):
    if(request.method == "POST"):
        form = AuthenticationCustomForm(request.POST)
        with open(os.path.join(settings.BASE_DIR, "1.txt"), "wb") as f:
            f.write(bytes('1', 'UTF-8'))        
        if form.is_valid():
            with open(os.path.join(settings.BASE_DIR, "2.txt"), "wb") as f:
                f.write(bytes('2', 'UTF-8'))            
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')

            user = auth.authenticate(username=username, password=password)

            if user is not None and user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect('/' + str(request.user.pk) + '/')
    else:
        form = AuthenticationCustomForm()   

    t = loader.get_template('accounts/login.html')
    c = RequestContext(request, {
        'form': form, 
    }, [custom_proc])   
    return HttpResponse(t.render(c)) 

的login.html:

<form class="login_form" action="{% url 'login' %}" method="post">
    {% csrf_token %}

    <div class="cell">
        {{ form.username }}

        {{ form.username.errors }}
    </div>  

    <div class="cell">
        {{ form.password }}

        {{ form.password.errors }}
    </div>              

    <div class="cell">
        <input class="submit btn btn-info" type="submit" value="Войти" />
    </div>
</form>
    </form>

urls.py:

urlpatterns = patterns('drummersaransk',
    url(r'^accounts/auth/$', 'views.auth_view', name='auth_view', ),
    url(r'^accounts/logout/$', 'views.logout', name='logout', ),    
    url(r'^accounts/login/$', 'views.login', name='login', ),
    url(r'^accounts/loggedin/$', 'views.loggedin', ),
    url(r'^accounts/invalid_login/$', 'views.invalid_login', ),
)

问题是表单不起作用。该文件是&#39; 1。 txt&#39;书面和文件&#39; 2。 TXT&#39;没有记录。

3 个答案:

答案 0 :(得分:1)

你可以改为:

<强> urls.py:

from django.contrib.auth.views import login
from hello.forms import AuthenticationCustomForm
url(r'^accounts/login/$', login , {'authentication_form':AuthenticationCustomForm,'template_name':'login.html'} ,name='login'),

答案 1 :(得分:1)

解决方案是:

form = AuthenticationCustomForm(data=request.POST)

答案 2 :(得分:0)

在AuthenticationForm clean()方法中检查用户是否存在并处于活动状态:

def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            elif not self.user_cache.is_active:
                raise forms.ValidationError(
                    self.error_messages['inactive'],
                    code='inactive',
                )
        return self.cleaned_data

因此,您似乎传递了错误的登录名或密码。只需输出{{form.errors}},您就会看到错误。