簡體   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