如何在Django中将此基于函数的视图转换为基于类的视图

时间:2019-03-29 08:56:11

标签: python django python-3.x

我试图将基于函数的视图转换为基于类的视图

问题是查询数据库两次,第一个是从Post模型中获取数据库中的所有帖子,第二个是从Category模型中获取数据库中的所有类别

这是代码

view.py

def newPost(request):    
    deyCat = Category.objects.all() 
    if request.method =='POST':
        myForm = NewPostForm(request.POST, request.FILES)
        response_data = {
            'SType': 'danger',
            'message': "An Error Occured, pls try again later"
        }
        if request.POST.get('deyHidden') == 'create_hidden':
            title = request.POST.get('title')
            content = request.POST.get('content')
            category_id = request.POST.get('category')
            image = request.FILES.get('image') 
            if myForm.is_valid():
                if Posts.objects.create(title=title, content=content, category_id=category_id, image=image, author_id=request.user.id):
                    response_data = {
                        'SType': 'success',
                        'message': "Saved Successfully"
                    }   
            return HttpResponse(json.dumps(response_data), content_type="application/json")  
        elif request.POST.get('deyHidden') == 'category_hidden':
            CatNames = request.POST.getlist('CatName[]')
            for CatName in CatNames:
                Category.objects.get_or_create(CatName=CatName)
            response_data = {
                'SType': 'success',
                'message': "Saved Successfully"
            }                
            return HttpResponse(json.dumps(response_data), content_type="application/json")

    context={
        'form':NewPostForm(),
        'title':'Create Post',
        'category': Category.objects.all()
    }
    return render(request, 'blog/form.html', context)

models.py中:

class Category(models.Model):
    CatName = models.CharField(max_length=100)
    def __str__(self):
        return self.CatName

class Posts(models.Model):
    title = models.CharField(max_length=100)
    category = models.ForeignKey(Category, default="1", on_delete=models.CASCADE)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='blog_pics')

    def __str__(self):
        return self.title

请,我该怎么做

1 个答案:

答案 0 :(得分:1)

您去哪里

from django.views.generic import TemplateView
from django.shortcuts import render


class NewPostView(TemplateView):
    template_name = 'blog/form.html'
    deyCat = Category.objects.all()

    def get(self, request, **kwargs):
        context = {
            'form': NewPostForm(),
            'title': 'Create Post',
            'category': self.deyCat
        }
        return render(request, self.template_name, context)

    def post(self, request, **kwargs):
        myForm = NewPostForm(request.POST, request.FILES)
        response_data = {
            'SType': 'danger',
            'message': "An Error Occured, pls try again later"
        }
        if request.POST.get('deyHidden') == 'create_hidden':
            title = request.POST.get('title')
            content = request.POST.get('content')
            category_id = request.POST.get('category')
            image = request.FILES.get('image')
            if myForm.is_valid():
                if Posts.objects.create(title=title, content=content, category_id=category_id, image=image,
                                        author_id=request.user.id):
                    response_data = {
                        'SType': 'success',
                        'message': "Saved Successfully"
                    }
            return HttpResponse(json.dumps(response_data), content_type="application/json")
        elif request.POST.get('deyHidden') == 'category_hidden':
            CatNames = request.POST.getlist('CatName[]')
            for CatName in CatNames:
                Category.objects.get_or_create(CatName=CatName)
            response_data = {
                'SType': 'success',
                'message': "Saved Successfully"
            }
            return HttpResponse(json.dumps(response_data), content_type="application/json")