我应该如何在功能视图中调用基于类的通用视图

时间:2017-07-25 16:24:16

标签: django django-views django-generic-views

我想在功能视图中调用基于类的索引视图 我在登录功能视图中渲染索引模板,但是当我在索引模板中添加额外的上下文时,我从函数视图中添加了它,它只渲染了额外的上下文而不是已经由基于类的索引视图呈现的上下文。

所以我想如果我可以从函数中调用基于类的索引视图,这样我就可以在基于类的视图中添加额外的上下文并同时渲染它。

简言之,我想从功能视图中添加额外的上下文并进行渲染。

这是我在索引模板中列出对象的基于类的通用视图。

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    title = 'hello'
    num_visit = 'a'
    context_object_name = 'question_list'

    def get_queryset(self):
        """Return the last five published questions."""
           return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

这是我的登录视图,它呈现与基于类的索引视图相同的模板

def login_view(request):
    user = authenticate(request,username=request.POST['username'],password=request.POST['password'])
    if user is not None:
        login(request, user)
        return redirect('polls:index')
    return render_to_response('polls/index.html', {'error_message': 'wrong credentials'})

............................................... ..

现在我可以登录索引模板,但看看代码上下文添加不起作用也许它工作但我觉得它与默认对象列表上下文混淆。

class IndexView(generic.ListView):
template_name = 'polls/index.html'
title = 'sdasd'
num_visit = 'a'
context_object_name = 'question_list'
error_message = None

def get_queryset(self):
    """Return the last five published questions."""
    return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

def post(self, request, **kwargs):
    user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
    if user is not None:
        login(request, user)
        return redirect('polls:index')
    error_message = 'i love jesus'
    context = self.get_context_data(request, error_message, **kwargs)
    return render(request, 'polls:index', context)



def get_context_data(self, *args, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    context['error_message'] = self.args
    return context

模板代码.............. 不能添加模板代码'这是我在这里添加的复杂 https://codeshare.io/5zXYJb

引用错误https://ibb.co/jdA7Ek

1 个答案:

答案 0 :(得分:1)

您不应该将逻辑从一个视图调用到另一个视图。创建登录逻辑。您没有发布任何代码,因此我不太确定您的程序是如何工作的,但您可以这样做:

在forms.py

class MyLoginForm(Form):
    username = forms.TextField(...)
    password = forms.PasswordField(...)

在utils.py

def login(request, user_name, password):
    user = authenticate(request, username=user_name, password=password)
    if user is not None:
        login(request, user)
        return True
    return False

def index_context(...):
    context = {}
    # do context stuff here
    return context

在views.py

class Index(View):
    def post(self, request, *args, **kwargs):
        # The logging_in part is optional but it's used to know when a post request is a login post or for something else. Just add a hidden field in your login form that has this name and a value of True.
        if request.POST.get("logging_in", False):
            authenticated = utils.login(request, request.POST.get("username", ""), request.POST.get("password", ""))

            if authenticated:
                # refresh the page
            else:
                # refresh the page with error
        else:
            # do other POST actions.

    def get(self, request, *args, **kwargs):
        # add a username and password form to context along with whatever other context you need.
        context = utils.index_context(...)
        context["login_form"] = MyLoginForm
        return render(request, "index.html", context)

def login_view(request):
    # Used if you also want a separate login page too.
    if request.method == "POST":
        loggedin = utils.login(request, request.POST.get("username", ""), request.POST.get("password", ""))
        if loggedin:
            return redirect('polls:login')
        return render_to_response('polls/login.html', {'error_message': 'wrong credentials'})
    else:
        # render template with username and password field
        context = {}
        context["login_form"] = MyLoginForm
        return render(request, "login.html", context)

你也可以只有一个API视图,只是登录的东西,并让ajax调用此视图。无论哪种方式,登录的实际逻辑应该在一个单独的全局函数中。