Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在django中将参数传递给基于类的视图?_Django - Fatal编程技术网

如何在django中将参数传递给基于类的视图?

如何在django中将参数传递给基于类的视图?,django,Django,我有一个显示登录表单的基于类的视图。 问题是我无法显示错误消息。我试图在URL中的一个参数中发送一条错误消息,以便在HTML模板文件中显示它。但它不起作用 以下是我目前的代码: forms.py # a class which act as a view - it displays the login-form class LoginForm(AuthenticationForm, BaseLoginView): username=forms.CharField(widget=forms

我有一个显示登录表单的基于类的视图。 问题是我无法显示错误消息。我试图在URL中的一个参数中发送一条错误消息,以便在HTML模板文件中显示它。但它不起作用

以下是我目前的代码:

forms.py

# a class which act as a view - it displays the login-form
class LoginForm(AuthenticationForm, BaseLoginView):
    username=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    password=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))

    def get_context_data(self, **kwargs):
        context = super(LoginForm, self).get_context_data(**kwargs)
        context['error'] = ''
        return context
urlpatterns = [
    path('login/', views_auth.LoginView.as_view(form_class=LoginForm, redirect_authenticated_user=True), name='login'), # login-page
]
# login functionality for the user
def custom_user_login(request):
    if request.method == 'GET':
        error_message = ''
        return redirect('home')

    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        error_message = ''        

        # if the username & password is correct
        user = authenticate(request, username=username, password=password)
        if user is not None:

            # Redirecting to the required login according to user type (admin / regular-user)
            if user.is_superuser or user.is_staff:
                login(request, user)
                return redirect('admin_section/')
            else:
                login(request, user)
                return redirect('/') 

        # display error message
        else:
            base_url = reverse('login')  # /login/
            query_string =  urlencode({'error': 'The username & password combination are incorrect - please try again!'})  # error=The username & password combination are incorrect - please try again!
            url = '{}?{}'.format(base_url, query_string) # /login/?error=The username & password combination are incorrect - please try again!
            return redirect(url)  # redirects to the login page with an error-message
url.py

# a class which act as a view - it displays the login-form
class LoginForm(AuthenticationForm, BaseLoginView):
    username=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    password=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))

    def get_context_data(self, **kwargs):
        context = super(LoginForm, self).get_context_data(**kwargs)
        context['error'] = ''
        return context
urlpatterns = [
    path('login/', views_auth.LoginView.as_view(form_class=LoginForm, redirect_authenticated_user=True), name='login'), # login-page
]
# login functionality for the user
def custom_user_login(request):
    if request.method == 'GET':
        error_message = ''
        return redirect('home')

    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        error_message = ''        

        # if the username & password is correct
        user = authenticate(request, username=username, password=password)
        if user is not None:

            # Redirecting to the required login according to user type (admin / regular-user)
            if user.is_superuser or user.is_staff:
                login(request, user)
                return redirect('admin_section/')
            else:
                login(request, user)
                return redirect('/') 

        # display error message
        else:
            base_url = reverse('login')  # /login/
            query_string =  urlencode({'error': 'The username & password combination are incorrect - please try again!'})  # error=The username & password combination are incorrect - please try again!
            url = '{}?{}'.format(base_url, query_string) # /login/?error=The username & password combination are incorrect - please try again!
            return redirect(url)  # redirects to the login page with an error-message
视图.py

# a class which act as a view - it displays the login-form
class LoginForm(AuthenticationForm, BaseLoginView):
    username=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    password=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))

    def get_context_data(self, **kwargs):
        context = super(LoginForm, self).get_context_data(**kwargs)
        context['error'] = ''
        return context
urlpatterns = [
    path('login/', views_auth.LoginView.as_view(form_class=LoginForm, redirect_authenticated_user=True), name='login'), # login-page
]
# login functionality for the user
def custom_user_login(request):
    if request.method == 'GET':
        error_message = ''
        return redirect('home')

    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        error_message = ''        

        # if the username & password is correct
        user = authenticate(request, username=username, password=password)
        if user is not None:

            # Redirecting to the required login according to user type (admin / regular-user)
            if user.is_superuser or user.is_staff:
                login(request, user)
                return redirect('admin_section/')
            else:
                login(request, user)
                return redirect('/') 

        # display error message
        else:
            base_url = reverse('login')  # /login/
            query_string =  urlencode({'error': 'The username & password combination are incorrect - please try again!'})  # error=The username & password combination are incorrect - please try again!
            url = '{}?{}'.format(base_url, query_string) # /login/?error=The username & password combination are incorrect - please try again!
            return redirect(url)  # redirects to the login page with an error-message
login.html

<!-- error message -->
<div id="error" class="alert alert-danger alert-dismissible" role="alert">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    {{ view.error }}
</div> 





<form method="post" action="{% url 'custom_login' %}">
  {% csrf_token %}

  {% for field in form %}

  <div class="form-group row">
     {{ field.errors }}
     <label for="{{ field.name }}" class="col-md-4 col-form-label text-md-right">{{ field.label }}</label>
     <div class="col-md-6">
        {{ field }}
     </div>
  </div>  

  {% endfor %}

  <div class="col-md-6 offset-md-4">
      <button type="submit" class="btn btn-primary">
         Login
      </button>
  </div>                                          
</form>

{{view.error}}
{%csrf_令牌%}
{%形式的字段为%}
{{field.errors}}
{{field.label}
{{field}}
{%endfor%}
登录

您不需要手动收集、添加到上下文和显示错误。表单本身存储错误。调用模板中的
field.errors
,您已经收到字段特定错误,但您也可以通过
form.errors
获得非字段特定错误。有关更多详细信息,请参阅


另外,您可以在模板中显示来自url的GET变量。只需使用
{{request.GET.error}
。同样,不需要在url本身中对错误消息进行编码。这不是解决这个问题的好方法,Django已经为您解决了这个问题。

谢谢。{{request.GET.error}}正在工作。但是我不能用field.errors显示字段特定的错误。默认错误未显示??您知道原因吗?您希望出现哪些字段特定的错误?你确定有吗?我相信使用
AuthenticationForm
,无效登录错误消息应该在
表单中。错误