繁体   English   中英

转换 function 视图 Class 基础视图 Django

[英]Transform function view in Class Based View in Django

我有一个存档页面,其中包含 2 个 select 选项输入和年份和月份,我想从数据库中 select 从页面中选择年份和月份创建的对象,我有这个 function 视图工作正常但是我需要 CBV 版本,我尝试使用 View 但它不起作用,请提供一些帮助。

def archive(request):
    if request.method == 'POST':
        year = datetime.strptime(request.POST.get('year'), '%Y')
        month = datetime.strptime(request.POST.get('month'), '%m')
        incomes = Income.objects.filter(
            user=request.user, created_date__year=year.year, created_date__month=month.month)
        spendings = Spending.objects.filter(
            user=request.user, created_date__year=year.year, created_date__month=month.month)
    else:
        incomes = Income.objects.filter(user=request.user)
        spendings = Spending.objects.filter(user=request.user)
        year, month = False, False

    context = {
        'title': 'Archive',
        'spendings': spendings,
        'incomes': incomes,
        'currency': Profile.objects.get(user=request.user).currency,
        'total_incomes': round(assembly(incomes), 2),
        'total_spendings': round(assembly(spendings), 2),
        'total_savings': round(assembly(incomes) - assembly(spendings), 2),
        'year': year,
        'month': month,
    }
    return render(request, 'users/archive.html', context)

尝试如下编写 class:-

class MyView(View):
    template_name = 'mytemplate.html'
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        # change context in case of get method / other code
        return render(request, self.template_name, context)
    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        # change context in case of post method / other code
        return render(request, self.template_name, context)
    def get_context_data(self, **kwargs):
        context = {}
        # common code to run in case of any method
        return context

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM