在views.py中返回渲染请求后,自动聚焦于电子邮件字段

时间:2019-02-13 15:41:20

标签: django

我正在使用注册表单,它可以正常工作,但是我想在出现message.error后将重点放在电子邮件字段上。

我是django的新手,只是再次开始编程。

from django.shortcuts import render, redirect    
from django.contrib import messages, auth    
from django.contrib.auth.models import User    
from django.contrib.auth import logout    
from django.http import HttpResponse, HttpResponseRedirect    

def signup(request):        
    if request.method == 'POST':             
        # Get Form Values    
        first_name = request.POST['first_name']    
        last_name = request.POST['last_name']           
        email = request.POST['email']    
        username = email    
        password = request.POST['password']    
        password2 = request.POST['password2']    
        context = {    
        'first_name' : first_name,    
        'last_name' : last_name    
        }    
        # Check if passwords match    
        if password == password2:    
            #Check username                
            if User.objects.filter(username=username).exists():    
                messages.error(request, 'Email is taken and used')                        
                return render(request, 'accounts/signup.html', context)        

            else:                
               #Looks good    
               user = User.objects.create_user(username=username, 
email=email, password=password,first_name=first_name,last_name=last_name)    
               user.save()    
               messages.success(request, 'You are now registered and can log in')    
               return HttpResponseRedirect('/#signin')    
        else:                
            messages.error(request, 'Password do not match')        
            return render(request, 'accounts/signup.html', context)               

    else:                
        return render(request, 'accounts/signup.html')        

我只是想将重点放在电子邮件字段上,是否有一种django方式做到这一点

1 个答案:

答案 0 :(得分:0)

当然有办法!只需在context内切换一个布尔标志,然后根据该标志在模板中启用/禁用autofocus

# views.py

def signup(request):
    # ...your code here...
    context = {    
        'first_name' : first_name,    
        'last_name' : last_name,
        'auto_focus' : False,
    }
    # ...your code here...
    messages.error(request, 'Password do not match')
    context['auto_focus'] = True
    return render(request, 'accounts/signup.html', context)
    # ...your code here...


<!-- html -->
<input type="email" {% if auto_focus %}autofocus{% endif %} />