1

am trying to convert my function based view to class-based view

the problem is that am querying the database twice, the first one is to get all the post in the database from the Post model and the second is to get all the category in the database from the Category model

here is the code

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)

in the 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

pls, how can i do this

1 Answer 1

1

here you go

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")
Sign up to request clarification or add additional context in comments.

2 Comments

it says invalid syntax in def(self, request, **kwargs):
Updated the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.