1

I have created a simple blog using DJANGO with three classes in views.py

views.py

def blog(request):
    posts=blog.objects.filter(createddate__lte=timezone.now()).order_by('-createddate')
    if request.method == "POST":
       name = request.POST.get('name')
       message = request.POST.get('message')
       contact.objects.create(name=name message=message)
    return render(request, 'base.html'{'posts':posts})

def blog_details(request,slug):
    posts=blog..objects.filter(createddate__lte=timezone.now()).order_by('-createddate')
    pos=get_object_or_404(app_descripts, slug_title=slug)
    if request.method == "POST":
       name = request.POST.get('name')
       message = request.POST.get('message')
       contact.objects.create(name=name message=message)
    return render(request, 'blog_details.html'{'posts':posts,'pos':pos})

def about(request):
    posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate')
    if request.method == "POST":
       name = request.POST.get('name')
       message = request.POST.get('message')
       contact.objects.create(name=name message=message)
    return render(request, 'about.html'{'posts':posts})

in the html I use this way because I have some code:

{% extends 'blog/base.html' %}
    {% block content %}
         .......................
        {% endblock %}

In the base.html out of block content I have a simple contain where I have code for all post (

posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate') ).

but to view the that posts in all pages(blog,blog_details,about) must write this code (

posts=blog..filter(createddate__lte=timezone.now()).order_by('-createddate'))

in all views to work fine. that happen and for my html contact form because is out of content.

how can avoid to execute same code in all views ?

v.coder
  • 1,822
  • 2
  • 15
  • 24
Mar
  • 683
  • 2
  • 11
  • 26
  • make sure that you've imported your model classes. e.g. `from .models import Blog, Contact`. Also, please elaborate your question and fix your format, e.g. instead of `blog.objects.filter. ...` you should write `Blog.objects.filter. ...`. code corrections: `contact.objects.create(name=name, message=message)`, `return render(request, 'blog_details.html', {'posts':posts,'pos':pos})` – Dhaval Savalia Jan 29 '18 at 03:31
  • 2
    You should use class-based views, they handle all this stuff automatically for you. – spectras Jan 29 '18 at 03:44

1 Answers1

1

I suggest you write the repetitive code inside another function, and call it from every view where you need it.

def get_posts():
    # Here you write your repeated code

And call it from your views

def my_view(request):
    posts = get_posts()
    return render(request, 'template.html', {'posts': posts})
JPYamamoto
  • 496
  • 6
  • 17