Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix ordered list sequence of database in Django?
I create a project that displays the first and last name of the user and email if users goes to the "/users". it is working fine but the issue is I am getting same number in the ordered list when I try to display the data. Kindly refer to the image for details. dj Here is the code for the HTML file... How do I fix this issue? <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>User Page</title> <link rel="stylesheet" href="{% static 'css/usercss.css' %}"/> </head> <body> <h2>Welcome to user page</h2> {% if accessdata %} <ol> {% for elements in accessdata %} <li>UserProfile</li> <ul> <li> {{ elements.firstname }}</li> <li> {{ elements.lastname }}</li> <li> {{ elements.email }}</li> </ul> {% endfor %} </ol> {% else %} <p> No users found</p> {% endif %} </body> </html> -
Redirecting after the conversion is done with Django
I have a website where the user uploads an mp4 and presses the button to convert it. What I need to do is to redirect to another page where he/she can play it. But I need to make sure the conversion is done before redirecting. How can I do this on the back-end side? Thanks in advance -
upload_to attribute returning wrong path
upload_to attribute isn't working correctly. I have no idea what's causing this, instead of uploading a file I'm getting a SuspiciousFileOperation exception. The base path component stated in the exception is correct but joined path is not correct as it should just be 'img/posts'. I'm looking for a reason that's causing this. models.py thumbnail = models.FileField(upload_to='img/posts') Exception value The joined path (/media/tb1.jpg) is located outside of the base path component (/home/user/Documents/project/project/media) -
Im using Django and in my views.py file line 11: user = form.save() is resulting in a UNIQUE constraint failed: auth_user.username error
I've looked at the questions asked and but I cant figure out what I'm missing. When I try to test my register page it throws the UNIQUE constraint failed. I know it has some relation to form.save() in my views. Another questions solution stated that they were attempting to save the form twice. I'm sure I'm not doing that but I could be wrong. Views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, bUserRegisterForm, UserProfileForm from django.contrib.auth import authenticate, login, logout def studentreg(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form .is_valid(): form.save() first_name = form.cleaned_data.get('first_name') messages.success(request, f'account created for {first_name}!') return redirect ('/home/studentlogin.html') else: form = UserRegisterForm() #this will return an empty form return render(request, 'users/studentregisterform.html', {'form': form}) def getstarted(request): return render(request, 'home/getstarted.html') def chooseaccount(request): return render(request, 'home/chooseaccount.html') def businessreg(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = UserProfileForm(request.POST) if form .is_valid () and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() first_name = form.cleaned_data.get('first_name') messages.success(request, f'account created for {first_name}!') return redirect ('admin/') else: form = bUserRegisterForm() profile_form = UserProfileForm() return render(request, 'users/businessregisterform.html', {'form': form, 'profile_form' : profile_form}) def bloginpage(request): if request.method == 'POST': Email_Address = request.POST.get('Email_Address') password = … -
Django UpdateWithInlinesView not saving deleted inlines
I'm using a jQuery plugin (by elo80ka) for adding and deleting inlines from Template. The issue I have is when I'm adding new data all goes well and data gets saved. But once I try to remove existing ones I get a redirect without deleted objects. (once I hit remove, the inline gets removed, I've checked via Inspector) class PlaceUpdateInline(InlineFormSetFactory): model = AdditionalLoadingPlace form_class = AdditionalLoadingPlaceInlineFormSet factory_kwargs = {'extra': 0, 'max_num': 5, 'can_order': False, 'can_delete': True} class PlaceUpdateView(LoginRequiredMixin, UpdateWithInlinesView): model = Place form_class = PlaceCreateForm inlines = [PlaceUpdateInline] def forms_valid(self, form, inlines): form.instance.author = self.request.user self.object = form.save(commit=False) self.object.author = self.request.user form.save(commit=True) for inline in inlines: objects = inline.save(commit=False) for obj in inline.deleted_objects: # never called obj.delete() for object in objects: if object.place: object.save() return HttpResponseRedirect(self.get_success_url()) -
Django, UpdateView deletes a row in the table
i complete remade a script, because i thought, an additional component is deleting a row in my database, which it doesn't. My script somehow manages to do it: Here are the facts: The Model is called "Settings", which is implemented as a Singleton: class Setting(SingletonModel): page = models.IntegerField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=True, null=True, default=None) addmonitored = models.BooleanField(default=True, verbose_name="Add shows as monitored to Sonnar") folders = models.BooleanField(default=True, verbose_name="Subfolders for seasons") def __str__(self): return "Settings" class Meta: verbose_name_plural = "Settings" The base Model looks like this: class SingletonModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): pass @classmethod def load(cls): obj, created = cls.objects.get_or_create(pk=1) return obj The FormView looks like this: class SettingsFormSetView(UpdateView): model = Setting exclude = ['page', 'xxxxxx'] template_name = 'settings.html' def get_object(self): return Setting.objects.get(pk=1) def get_success_url(self): return reverse('settings') I can open the form without any problems, enter the data, save it. I can reload the page and it still shows the data. If i reload it a few times, suddenly the form is empty and the row (pk=1, which is the only row in that table) is also deleted from the database. No other stuff is interfering … -
Using postgres bigserial as autoincrement id field and pk with a more recent version of django
I want to be able to use the bigserial data type for the pk of my django model. I do not want to do it manually with each model i create. Is there any way to change django to use bigserial instead of the serial datatype? All the searches i have done result in having to change the database for each model or a workaround but with an earlier version of django in like the 1.x version. Is there a more recent or better way to do this? -
Django trying to add upload directory for images (E004)
So my current goal is to be able to allow admins to upload images such as thumbnails in certain models . So I started off by creating a folder called uploads in the projects root directory. In my models.py I'm using thumbnail = models.ImageField(name="photo", upload_to='uploads/thumbnails/', null=True, default='default.png') which successfully uploads files to that directory. The problem though is accessing those files once they're uploaded. I edited my urls.py to look like this from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.urls import path from . import views app_name = 'blog' urlpatterns = [ #... static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT), ] and I added the following to my settings.py AUTH_USER_MODEL = "blog.User" MEDIA_URL = "/uploads/" MEDIA_ROOT = os.path.join(BASE_DIR, "uploads") Now I keep getting the following error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern [<URLPattern '^uploads/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of pa th() and/or re_path() instances. I'm fairly new to django so if this question can be improved by all means let me know. -
How can I configure VS Code to work with Prettier HTML formatter?
I am trying to have VS Code format my Django HTML files but I am getting: There is no document formatter for 'django-html'-files installed. The solution I found on the web works with Beautify, not Prettier. How can I make it work with Prettier? -
Django - How can I get form data to my view that handles my ajax calls when the form is rendered in a different view for the same template
I have a form rendered to a page from this view: def foo(request): form = MyForm() return render(request, template_name=template, context={'form': form}) From a different view I handle my ajax calls which loads data from a url to the same template as the view above. I need to use the input from that form to reload the page using Ajax with the filtered results. How can I gain access to the form from my Ajax view? class AjaxView(APIView): authentication_classes = [] permission_classes = [] def get(self, request): form_data = request.GET.get # Need to get form submission data here def handle_new_page_logic(form_data) ... return Response() -
Your requirements.txt is invalid. AWS Elastic Beanstalk, Django
i am new to aws and django. I was tryinh to upload my code to aws elastic beanstalk using code commit while i am getting the folowing error please suggest what to do 2020/03/12 13:42:30.200017 [ERROR] Command timed out after 300 seconds 2020/03/12 13:42:30.202535 [ERROR] Command /bin/sh [-c python3 -m pipenv install -r requirements.txt --skip-lock] failed with error signal: killed 2020/03/12 13:42:30.204812 [ERROR] An error occurred during execution of command [app-deploy] - [SetUpPythonEnvironment]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh [-c python3 -m pipenv install -r requirements.txt --skip-lock] failed with error signal: killed 2020/03/12 13:42:30.204825 [INFO] Executing cleanup logic 2020/03/12 13:42:30.210383 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[]}]} 2020/03/12 13:42:30.211588 [INFO] Platform Engine finished execution on command: app-deploy -
Showing a date range from a set of date objects
I have a two set of dates: Set #1: 1805 Nov. 11 1805 Nov. 12 1805 Nov. 13 Set #2: 1805 Nov. 11 1805 Nov. 13 1805 Nov. 14 What is the easiest way to display a date range. For Set #1: I expect to show: 1805 Nov. 11-13 For Set #2, I want to show: 1805 Nov. 11, 13-14 -
How do I run a function on each post in my list view and pass a boolean variable into my html?
My html {% if is_liked %} <i class="fa fa-check" aria-hidden="true"></i> {% else %} <i class="fa fa-times" aria-hidden="true"></i> {% endif %} My views.py class PostListView(ListView): queryset = Post.objects.filter(created__range=['2020-03-01', '2020-03-31']) template_name = 'main/problems.html' context_object_name = 'posts' ordering = ['-created'] for post in queryset: def get_liked(self): if self.likes.filter(id=self.request.user.id).exists(): is_liked = True else: is_liked = False return is_liked Even if I set both conditionals to return true my html does not read is_liked as true. -
CORS Policy Issue Between React and Django App
I got this issue when trying to get data in my React app from my Django app: Access to XMLHttpRequest at 'https://quiet-retreat-95482.herokuapp.com/api/todos/' from origin 'https://infallible-jackson-111720.netlify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I made a React todo list app and deployed it here: https://infallible-jackson-111720.netlify.com/ I made my Django backend and deployed it on Heroku: https://quiet-retreat-95482.herokuapp.com/ In my backend code, I think I installed and have the correct settings for corsheader: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'todo' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'https://infallible-jackson-111720.netlify.com' ] import django_heroku django_heroku.settings(locals()) I also had requirements.txt and Procfile for heroku and the app was deployed successfully. I was able to get data locally when my backend was running on my localhost: http://127.0.0.1:8000/api/todos/ What was the cause of this error and how can I fix it? If need any other information, please let me know. Thank you a lot! -
Iterate over several querysets in django template with nested loop
I am making a hotell-page, and have made models for bookings and rooms. I want to display the bookings related to a room in a table, and have the related bookings laying under the spesific room. I show the code from the views.py file here: def vaskehjelp(response): available_rooms = Room.objects.filter(available=True) room_nums = [] context = {} for room in available_rooms: related_bookings = Booking.objects.filter(room=room) if related_bookings: room_nums.append(room.room_no) context[room.room_no] = related_bookings context["room_nums"] = room_nums context["available_rooms"] = available_rooms print(context) return render(response, "../templates/se_vaskbare_rom.html", context) and the code from my template file here: <table class="table table-striped table-dark"> <tr class="thead-dark"> <th scope="col">Room No.</th> <th scope="col">Capacity</th> <th scope="col">Room Type</th> </tr> {% for item in available_rooms %} <tr scope="row"> <td>{{ item.room_no }}</td> <td>{{ item.capacity }}</td> <td>{{ item.room_type }}</td> </tr> {% if item.room_no in room_nums %} {% for booking in item.room_no %} <h1></h1> <tr scope="row"> <td>{{ booking.cin_date }}</td> <td>ku</td> <td>{{ booking.cout_date }}</td> </tr> {% endfor %} {% endif %} {% endfor %} </table> The problem is that the booking-element in the template code doesent seem to work. I dont manage to access the lists of bookings related to the current selected room. As you see i have an outer for loop to iterate over the rooms, and then the … -
psycopg2.errors.UndefinedColumn: column ... does not exist
Hello I am trying to migrate an app 'projects'. On my local machine, I had made many changes to the model over time and so I have many different migrations for the app. When I am trying to migrate to my web server, I receive an error on the fourth migration file. Error: Applying projects.0001_initial... OK Applying projects.0002_auto_20200227_1959... OK Applying projects.0003_project_garage... OK Applying projects.0004_auto_20200301_2331...Traceback (most recent call last): File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column projects_project.accessible_to_foreigners does not exist LINE 1: ...opertytype2", "projects_project"."propertytype3", "projects_... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state … -
Python django model validate min and max value
I want to limit the title to between 3 and 25 characters. I could not get MinLengthValidator to work. I'm new to Python. class Video(models.Model): title = models.CharField(max_length=255) url = models.URLField() youtube_id = models.CharField(max_length=255) def clean_title_length(self): data = self.cleaned_data['title'] length= len(data) if length < 3 or length > 25: raise ValidationError("The length of the title must be between 3 and 25 characters") else: return data views.py def add_video(request): form = VideoForm() if request.method == 'POST': filled_form = VideoForm(request.POST) if filled_form.is_valid(): The above form always returns valid. Suggestion on how I can get this range validator to work? TIA -
Django admin for User changes Groups widget when I add a custom admin
I want to use the out-of-the-box User model in Django, but add an action to the admin. Without any custom admin, the User's admin has this many-to-many control for groups: But when I register a custom Admin: class CustomModelAdmin(admin.ModelAdmin): actions = ['custom_action'] def custom_action(self, request, queryset): pass custom_action.short_description = "Custom Action" admin.site.unregister(User) admin.site.register(User, CustomModelAdmin) The control changes to a simpler select. I want the original one, as my list of groups may get large. Why did it change? How do restore it to the former? -
How to get a model's last access date in Django?
I'm building a Django application, and in it I would like to track whenever a particular model was last accessed. I'm opting for this in order to build a user activity history. I know Django provides auto_now and auto_now_add, but these do not do what I want them to do. The latter tracks when a model was created, and the former tracks when it was last modified, which is different from when it was last accessed, mind you. I've tried adding another datetime field to my model's specification: accessed_on = models.DateTimeField() Then I try to update the model's access manually by calling the following after each access: model.accessed_on = datetime.utcnow() model.save() But it still won't work. I've gone through the django documentation for an answer, but couldn't find one. Help would be much appreciated. -
upload_to attribute giving wrong path
upload_to attribute isn't working correctly. I have no idea what's causing this, instead of uploading a file I'm getting a SuspiciousFileOperation exception. The base path component stated in the exception is correct but joined path is not correct as it should just be 'img/posts'. I'm looking for a reason that's causing this. models.py thumbnail = models.FileField(upload_to='img/posts') Exception value The joined path (/media/tb1.jpg) is located outside of the base path component (/home/user/Documents/project/project/media) -
encoded html reportlab python
I am creating a pdf with reportlab in python I have the following problem one of the data has to show is type longText because html strings have been saved, as I decode it to show it in my pdf if the data arrives as follows, sometimes html will come tables and would like to keep them. I do the following but it still looks the same comentatios = '<p><br></p><table class="table table-bordered"><tbody><tr><td>dato 1</td><td>dato 2</td></tr><tr><td>dato 3</td><td>dato 4</td></tr></tbody></table><p><br></p>' from six.moves.html_parser import HTMLParser h = HTMLParser() data = [][enter image description here][1] data.append(['Comentarios',h.unescape(comentarios),'','']) t4 = Table( data, ) -
Why does I get either NoReverseMatch or FieldError
I am working on a project, and want to create a report on a film. (That it doesn´t exist) At the moment I only get error when I try to go to either film// or film//report. Can anybody help me? **models.py** class Report(models.Model): title = models.CharField(default="", max_length=100) comment = models.TextField(default="") reporter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Reporter") # receiver = models.ForeignKey( # User, on_delete=models.CASCADE, related_name="Receiver" # ) reports = models.ForeignKey(Film, on_delete=models.CASCADE) def __str__(self): # pragma: no cover return f"{self.reporter.username} reports {self.reports.title}" **urls.py** urlpatterns = [ path("", views.films_view, name="board-home"), path("film/add", FilmAddView.as_view(), name="film-add"), path("film/<int:pk>/", FilmDetailView.as_view(), name="film-detail"), path("film/<int:pk>/report", FilmReport.as_view(), name="film-report") ] **views.py** class FilmReport(LoginRequiredMixin, UpdateView): model = Report fields = ["title", "reported"] # def __str__(self): # return self.title def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) This should be the page where I can click on "Report", and then be redirected to a report page. **film_detail.html** {% extends "board/base.html" %} {% block content %} <article class="media content-section"> <img class="rounded-circle film-img" src="/media/{{object.poster}}"> <!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. --> <a href=" {% url 'film-add' %}" class="waves-effect waves-light green btn"><i class="material-icons right">rate_review</i>add review</a> <a href=" {% url 'film-report' %}" class="waves-effect waves-light red darken-4"><i class="material-icons right">report</i>report</a> <!-- <a onclick="myFunction()" class="waves-effect … -
Django choices that change automatically based on male/female checkboxes. Categories will be displayed based on the gender choice
I have searched on the internet but did not find anything suitable. I want to have a model that will have a a set of choices of categories which will change based on whether the male or female checkbox/choice (whichever is more appropriate) was selected. In models.py, class MyModel(models.Model): MALE_CATEGORIES = { ('Male Category 1', 'Male Category 1'), ('Male Category 2', 'Male Category 2'), ('Male Category 3', 'Male Category 3'), } FEMALE_CATEGORIES = { ('Female Category 1', 'Female Category 1'), ('Female Category 2', 'Female Category 2'), ('Female Category 3', 'Female Category 3'), } # Male/Female option as either choices or checkboxes depending on whichever one is more suitable gender = # Either MALE_CATEGORIES or FEMALE_CATEGORIES # Depending on gender categories = models.CharField(max_length=18, choices=) In forms.py, class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'gender', 'categories', ] -
Can't create PostGis extension on PostgreSQL database?
I'm trying to create a postgis extension on my PostgreSQL database for a Django project, but when I run CREATE EXTENSION postgis I get this error: ERROR: extension "postgis" has no installation script nor update path for version "3.0.1" I installed all the dependencies with Homebrew on macOS, and this database is not on the 'postgres' user, it's on my own superuser. Homebrew Dependency Versions postgresql@12.2 postgis@3.0.1 gdal@2.4.4 geos@3.8.1 proj@7.0.0 Any help is appreciated!! Been working on this issue for the last week. -
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name
I am trying to create a new post and when I click on the save button, I get error as stated in the image. I am not able to understand the error and where to look for it. I am new at django. Please help! Main-urls.py file: from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog_app.urls', namespace='blog_app')), url(r'^accounts/',include('accounts.urls', namespace='accounts')), #path('accounts/login/', views.LoginView.as_view(template_name='blog_app/login.html'),name='login'), #path('accounts/logout/',views.LogoutView.as_view(template_name='blog_app/base.html'),name='logout'), ] blog_app-urls.py file: from django.conf.urls import url from blog_app import views from django.urls import path app_name = 'blog_app' urlpatterns = [ url(r'^$', views.PostListView.as_view(),name='post_list'), url(r'^about/$', views.AboutView.as_view(),name='about'), url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(),name='post_detail'), url(r'^post/new/$', views.CreatePostView.as_view(),name='new_post'), url(r'^post/(?P<pk>\d+)/edit/$', views.UpdatePostView.as_view(),name='edit_post'), url(r'^drafts/$', views.DraftListView.as_view(),name='draft_post_list'), url(r'^post/(?P<pk>\d+)/remove/$', views.DeletePostView.as_view(),name='delete_post'), # url(r'^post/(?P<pk>\d+)/remove/$', views.post_remove,name='delete_post'), url(r'^post/(?P<pk>\d+)/publish/$', views.post_publish, name='post_publish'), url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'), url(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve, name='comment_approve'), url(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove, name='comment_remove'), # path('register/',views.register,name='register'), ] blog_app-views.py file: from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from django.contrib.auth.decorators import login_required from blog_app.models import Post,Comment from blog_app.forms import PostForm,CommentForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.views.generic import (TemplateView,ListView,DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login,logout,authenticate class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(publish_date__lte = timezone.now()).order_by('-publish_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): …