Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UnitTesting: 'AnonymousUser' object has no attribute
I have the following code: class CampaignModelTests(TestCase): # https://docs.djangoproject.com/en/4.1/topics/testing/advanced/ def setUp(self): # create some test campaigns shop = Shop.objects.create(name='Test Shop') self.factory = RequestFactory() self.user = User.objects.create(shop_username='testuser', shop=shop) self.merchant = User.objects.create(username='merchant', password='merchant123', is_merchant=True, shop=shop) self.campaign = Campaign.objects.create(name='Test Campaign', shop=shop) def test_campaign_creation(self): request = self.factory.get(reverse('create-campaign'), { 'name': 'Test Campaign -1', 'shop': Shop(name='Test Shop').sid }) request.user = self.merchant print('request.user: ', request.user.is_merchant) response = CampaignCreate.as_view()(request) self.assertEqual(response.status_code, 200) And I am getting the following error: return request.user.is_merchant or request.user.is_superuser AttributeError: 'AnonymousUser' object has no attribute 'is_merchant' I have tried using self.client as well but still the same error. self.client.force_login(self.merchant) # send a request to the view response = self.client.post(reverse('create-campaign'), { 'name': 'Test Campaign -1', 'shop': Shop(name='Test Shop').sid }) self.assertEqual(response.status_code, 200) -
Django combine queries with and (&) in m2m field
I have such models: class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() tags = models.ManyToManyField(to="tag", related_name="tags", blank=True) def __str__(self): return self.title class Tag(models.Model): value = models.CharField(max_length=50) parent = models.ManyToManyField("Tag", related_name="children", blank=True) image = models.ImageField(upload_to="tags", null=True, blank=True) def __str__(self): return self.value And I have an object, for example, post C which has tag 2 and tag 3 Currently I cannot create a combined ( q1 & q2 ) query, where I will be able to filter by that condition. I am using combined queries because the case is more complex(so double filter won't do), I want to be able to filter by such queries as " 2 or ( 3 and 4 ) ", "(1 or 2) and (3 or 4)" >>> q1 <Q: (AND: ('tags__in', '2'))> >>> q2 <Q: (AND: ('tags__in', '3'))> >>> Post.objects.filter(q1) <QuerySet [<Post: post_B>, <Post: post C>, <Post: post D>]> >>> Post.objects.filter(q2) <QuerySet [<Post: post C>, <Post: post D>]> >>> Post.objects.filter(q1 & q2) <QuerySet []> >>> str(Post.objects.filter(q1).query) 'SELECT "posts_post"."id", "posts_post"."title", "posts_post"."content" FROM "posts_post" INNER JOIN "posts_post_tags" ON ("posts_post"."id" = "posts_post_tags"."post_id") WHERE "posts_post_tags"."tag_id" IN (2)' >>> str(Post.objects.filter(q2).query) 'SELECT "posts_post"."id", "posts_post"."title", "posts_post"."content" FROM "posts_post" INNER JOIN "posts_post_tags" ON ("posts_post"."id" = "posts_post_tags"."post_id") WHERE "posts_post_tags"."tag_id" IN (3)' >>> str(Post.objects.filter(q1 & q2).query) … -
How to get webhook data in python
I have a webhook url from messagebird, and post requests are being sent from the LINE Messaging API to that url when some events occur. I need to get the data of those webhooks (JSON data). I'm using Python (it's a Django app). How can I get the data from the webhook? -
Recommendations for DRF lectures in udemy
Which udemy course is best for django rest framework that follows whole django documentation? Main purpose is to learn drf in detail by following its documentation. -
How to Configuration for wgsi conf file for fjango without virtual enviroment?
i wanna host django application using apache2 with mod_wsgi without virtual enviroment so i am not able to config .conf file here is my configuration file. <VirtualHost *:80> ServerName example.in ServerAdmin info@example.in ServerAlias example.in DocumentRoot /home/MyMedbookMain/django Alias /static /home/MyMedbookMain/django/static <Directory /home/TransportDemo/static> Require all granted </Directory> <Directory /home/MyMedbookMain/django/qm> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mymedbook python-home=/usr/local/bin/pip3 python-path=/home/MyMedbookMain/django WSGIProcessGroup mymedbook WSGIScriptAlias / /home/MyMedbookMain/django/qm/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] after reload apache2 it not loading -
Django makemigrations : IndexError: list index out of range
When I attempt to run python3.8 makemigrations, I get the following : File "/usr/lib/python3.8/gettext.py", line 436, in _parse plural = v[1].split('plural=')[1] IndexError: list index out of range Upon detailed inspection by running python3.8 manage.py runserver , I observed the following: 2023-01-05 03:33:22,179 django.utils.autoreload INFO Watching for file changes with StatReloader 2023-01-05 03:33:22,180 django.utils.autoreload DEBUG Waiting for apps ready_event. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/earthling/myEnv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/earthling/myEnv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/earthling/myEnv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/earthling/myEnv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/earthling/myEnv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/earthling/myEnv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/earthling/myEnv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/earthling/myEnv/lib/python3.8/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/earthling/myEnv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 92, in … -
Django ORM model to sync with db record changed by external
In Django model, is there anyway for instant sync of loaded model object with db records updated by external? Here is sample scenario. I load record in Django model by get method. book = Book.objects.get(id=1) print(book.title) # It will print '21 century' I update relevant db data manually in database using query in PGAdmin update book set title='22 century' where id=1 the model obj loaded in 1st step still retains old data instead of latest update from 2 step print(book.title) # It still print '21 century' instead of '22 century' I have no solution yet and need help for this -
Cannot import .py file into settings.py
I have created a separate file test.py to interface with Azure Key Vault. When I run just the test.py file it works as expected. However, I cannot import it in settings.py for its values to be used there. I cannot import any file into settings.py for that matter or it causes an internal 500 error on Apache. For instance I want to add these lines to my settings.py import test Pass = test.Pass However, when adding that and restarting the Apache server is gives an error 500 page until I remove the lines and restart. test.py has no syntax errors because I can run it on its own and produce the result I am looking for but bringing any file into settings.py causes the crash. The error logs have been no help. Why would I not be able to import a file into settings.py? The file I am importing is successful a part of the PYTHONPATH variable and I have checked that by printing sys.path. Also the file is located in the same directory as settings.py mysite/ settings,py test.py urls.py wsgi.py init.py -
(Python) How to Connect/Integrate Django with website
my problem is 60% similar to this one How to retrieve data from MySQL database in Django and display it in html page? Goal: I want Connect Django with website , I see most of the result is showing create new website by Django, for now I already have website done/build separately, and wish to connect with Django environment: mySQL, python, windows and exist website to connect that for now I connect mySQL and Django and the screenshot of .py page in Django , I'm not sure what .py script should add to achive my goal https://imgur.com/a/lmj61pJ with init.py , asgi.py , settings.py , urls.py , wsgi.py -
Curly Bracket Mysteriously Appearing in Django App
I am following a Django tutorial and getting a weird bug: I have models hooked up to views hooked up to templates, but when I view the page I get a weird closing curly bracket inside the table above "Site Name". I cannot figure out where this comes from. How do I make it go away? My html Template code is: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <style>{% include "</style> <link rel="stylesheet" href="{% static "CSS/simple_style.css"%}"/> <title>Django Level Two</title> </head> <body> <h1>Hi and Welcome to Django Level Two</h1> <h2>Here are your access records:</h2> <div class="djangotwo"> {% if access_records %} <table> <thead> <th>Site Name</th> <th>Date Accessed</th> </thead> {% for acc in access_records %} <tr> <td>{{ acc.name }}</td> <td>{{ acc.date }}</td> </tr> {% endfor %}} </table> {% else %} <p>NO ACCESS RECORDS FOUND!</p> {% endif %} </div> </body> </html> My CSS code is as follows: h1{ color: #011627; } h2{ color: #191063; } .djangotwo{ border: 2px solid black; } Views code is: from django.shortcuts import render from django.http import HttpResponse from AppTwo.models import Topic, Webpage, AccessRecord # Create your views here. def home(request): webpages_list = AccessRecord.objects.order_by("date") date_dict = {"access_records": webpages_list} return render(request, "AppTwo/index.html", context=date_dict) def help_page(request): help_dict = … -
Applying django-filter settings
From django-filter documentation I can see that there is a setting to disable the empty choice under heading FILTERS_EMPTY_CHOICE_LABEL. I am attempting to apply that setting however cannot get the the correct syntax. In my settings.py file I have EMPTY_CHOICE_LABEL = [ { 'ChoiceFilter.empty_label': 'None' } ] However this returns error FILTERS_ NameError: name 'FILTERS_' is not defined What is the correct syntax to apply this setting? -
Wrong Version of Django Running in Virtual Environment
I have two versions of Python installed (OS: Windows 10). The original version is 3.8.2. I installed 3.11.1 and did not have it added to PYTHONPATH. I created a virtual env using py -m venv .env. Despite using py, the virtual environment runs both Python 3.8.2 and 3.11.1 depending on whether I type python or py. Inside the virtual environment I installed a newer version of Django (4.1.5) using py -m pip install django, which successfully installed Django within the Python311 folder on my system. However, no django-admin.py file was installed, just django-admin.exe. To ensure I created my project using the newer version of Django, I navigated to the folder where the django-admin.exe file exists and ran the following: py django-admin.exe startproject <*project_name*> <*full_path_to_project_folder*> The settings.py file shows it was created using Django 4.1.5, but whenever I start my project it runs using Django 3.0.4 (the pre-existing version). I am starting it using py manage.py runserver, to ensure Python 3.11.1 is being used. I have tried it both inside and outside my virtual environment. I have added the python311\Scripts folder at the top of my Path environment variables, and have uninstalled and reinstalled Django 4.1.5. At this point I am … -
Django Formset display currently images in BlogUpdate
i want to display currently images in BlogUpdate with custum label how can i show blog related image in BlogUpdate display currently images path with url but not display currently images in img tag i want to display currently images in blog_update.html {{ img.media_files }} display currently images path <img src="{{ img.media_files.url }}"> but not display currently images in img tag forms.py class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ['title', 'text', ] class BlogImagesForm(forms.ModelForm): class Meta: model = BlogImages fields = ['media_files', ] media_files = forms.ImageField( widget=forms.ClearableFileInput(attrs={'multiple': False,})) BlogImagesFormSet = inlineformset_factory( Blog, BlogImages, form=BlogImagesForm, extra=6, max_num=6, can_delete=False, can_order=False ) views.py class BlogUpdate(LoginRequiredMixin, UpdateView): model = Blog form_class = BlogForm template_name = 'blog/blog_update.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['images'] = BlogImagesFormSet( self.request.POST or None, self.request.FILES or None, instance=self.object ) else: data['images'] = BlogImagesFormSet(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() images = context['images'] with transaction.atomic(): form.instance.owner = self.request.user self.object = form.save() if images.is_valid(): images.instance = self.object images.save() return super(BlogUpdate, self).form_valid(form) blog_update.html <form method="POST" enctype="multipart/form-data"> <div class="girdbox"> {% for img in images.forms %} <label for="{{ img.media_files.auto_id }}" class="blurfix"> <img src="{{ img.media_files.url }}"> <div style="padding-bottom: 50%;"></div> </label> {% endfor %} </div> {% csrf_token %} {{ form|crispy }} … -
How to generate a querylist in Django, which needs to be generated only once?
guys. I hope you are doing well. So, I am developing a language website now and I have a Django view, called ExerciseView. My idea is next - go to the page (views triggers) --> querylist is generated in a random order --> declare sessions --> change them to dictionary to access easier --> and conditionals starts. My question is - how to generate the querylist only once and keep it the same until the training is finished. Every time a person clicks the buttons, new GET request is made and new querylist is generated. How can I make it constant and random list, which is not changing like that? The first time it generates this [<Exercise: Я пью чай без лимона >, <Exercise: Это дом папы >, <Exercise: У Тимофея день рождения сегодня!>] The next time I make a POST request and then again GET happens and this querylist is already different: [<Exercise: Я иду домой с работы >, <Exercise: Я пью чай без лимона >, <Exercise: У меня нет друга >] class ExerciseView(View): def get(self, request, **kwargs): data = list(Exercise.objects.filter(topic_type__slug=kwargs['slug_exercise']).all().order_by('?'))[:3] id = request.session.setdefault('sentence_id', 0) score = request.session.setdefault('score', 0) sentences = request.session.setdefault('sentences', {}) for i in range(0, len(data)): sentences[i] … -
Getting django accept phpBB users
My Problem is, I want to create a extra website on a phpBB forum to provide extra stuff and registration for meeting. No problem I know django and python, so this is no problem. But I would be nice, if I could accept a session from a user or import the phpBB users so that they can login to my app. I found django-phpBB, but I don't want to access the data. If I read correctly, my case is not the use case of django-phpBB. Can anybody give me a good advice? -
Generating new HTML rows for each Document from firestore in python Django
I have a collection of documents in a Firestore database. I want to create a web form to display all the documents and their fields. I started by streaming all the documents using: docs = db.collection(u'users').stream() and then appending all the docs IDs to a list and pass it to the HTML file as follows def index(request): myIDs =[] db = firestore.Client() docs = db.collection(u'users').stream() for doc in docs: myIDs.append(f'{doc.id}') return render(request, 'index.html', { "weight":"abc", "firstRow":myIDs[0], "secondRow":myIDs[1], "thirdRow":myIDs[2], "fourthRow":myIDs[3], "fifthRow":myIDs[4], "sixthRow":myIDs[5], "seventhRow":myIDs[6], }) After that, I created a very basic HTML code just to display the document IDs as follows: <html> <body> <table border="1" cellpadding = "5" cellspacing="5"> <tr> <td>{{ firstRow }}</td> <tr> <td>{{ secondRow }}</td> </tr> <tr> <td>{{ thirdRow }}</td> </tr> <tr> <td>{{ fourthRow }}</td> </tr> <tr> <td>{{ fifthRow }}</td> </tr> <tr> <td>{{ sixthRow }}</td> </tr> <tr> <td>{{ seventhRow }}</td> </tr> </tr> </table> </body> </html> Till this point I am just doing very basic stuff. But I am new to Django and Python for the Web, so my question is: how can I make it so that the HTML rows become adaptive based on the number of documents? For example, if I have 20 documents, I want to make … -
The current path, accounts/<int:id>/, didn’t match any of these ( for django application)
This is a book exchange system I'm trying to create. The challlenge I'm having is trying to redirect the user to a dynamic url consisting of there personal details after log in. Here is my urs.py for my project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('exchange/',include('exchange.urls')), path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ] Here is my urs.py for my app from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('', views.base, name='base'), path('register/', views.register_request, name='register'), path('accounts/<int:id>/', views.user_view, name='userview'), #path('login/', views.login_request, name='login'), path('login/', auth_views.LoginView.as_view(template_name='exchange/login.html', redirect_field_name='user_view')), ] Here is my views.py for my app from django.shortcuts import render, redirect from exchange.forms import user_login_form, user_register_form from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.contrib import messages # Create your views here. #Base index view def base(request): return render(request, 'exchange/base.html',{}) #registration view def register_request(request): if request.method=='POST': form = user_register_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('login') else: messages.error(request, 'Invalid form') render(request, 'exchange/register.html',{'form':form}) else: form = user_register_form() return render(request, 'exchange/register.html',{'form':form}) #login view def login_request(request): if request.method=='POST': form = user_login_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user … -
I want to build table like this format in datatable
I want to build table like this format in datatable. enter image description here -
Django - models field join to django-table2
I have a django-tables2 table created with data from model Data. Model Data is linked to model Kategorie with "jmeno" (name of Category). And I would like to link field "jmeno" to my table PuDetailTable as category field. Table definition: class PuDetailTable(tables.Table): class Meta: model = Data fields = ("datum", "doklad", "cislo", "popis", "amount", "partner", "zakazka", "stredisko", "ucet", "company", "category") sequence = ("datum", "doklad", "cislo", "popis", "partner", "zakazka", "stredisko", "ucet", "category", "company", "amount") attrs = {'a': {"class": "a2"}, 'th': {'class': 'headline'}} ... category = tables.Column(verbose_name="Kategorie", accessor="ucet__mustek__kategorie__jmeno", attrs = {"td": {'class': 'text-center'}}) Models: class Data(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE, null=True, blank=True) class Ucty(models.Model): cislo = models.IntegerField("Účet", blank=True, null=True) class Mustek(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE) kategorie = models.ForeignKey(Kategorie, on_delete=models.CASCADE) class Kategorie(models.Model): jmeno = models.CharField("Kategorie", max_length=20, blank=True, null=True) And I need help with correct accessor to get "jmeno" (category name) to the table as the accessor accessor="ucet__mustek__kategorie__jmeno" is not working. I have tried different variants like accessor="ucet_ucty__mustek__kategorie__jmeno", but this is also not working. So any idea what should be the correct accessor? -
Quick method to view formatted html in a variable or property during debugging
I am debugging a Django app. During debugging, I've set a breakpoint so I can see a rendered html string stored in a variable. The variable has a property called content and within is a html string which is enclose din b''. I know I can copy the value from the debugger and open a text window and paste it in. Then I can formatted so I can read it. This is time-consuming though and I wonder if there is a simple trick or alternative that will allow me to quickly view the formatted html? -
how to access chield model from parent model (using Multi-table inheritance)
I have this model from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) how to accsees serves_pizza from parent moddel (Place) my use case , i need to access serves_pizza from parent serilizer (PlaceSerializer) class PlaceSerializer(serializers.ModelSerializer): serves_pizza = serializers.SerializerMethodField() class Meta: model = Place fields = '__all__' def get_serves_pizza (self, obj): serves_pizza = Restaurant.objects.get(**???**) return serves_pizza -
How to push data in a model whose one column is a forign key Django Rest Framework?
I'm trying to assign data against specific user using DRF but getting some strange errors. I want your help/ guidance. I'm a beginner but I searched this problem a lot but not able to find any solution. model.py class Category(TrackingModels): name =models.CharField(default='Learning',max_length=150,unique=True,null=False) person=models.ForeignKey(to=User,on_delete=models.CASCADE) def __str__(self): return self.name serializer.py class CategorySerializer(ModelSerializer): person = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model=Category fields=('id','name','person') views.py class CategoryAPIView(CreateAPIView): serializer_class=CategorySerializer permission_classes=(IsAuthenticated,) def post(self,request): data={ "person":request.user.id, "name":request.data.get('category') } serializer=CategorySerializer(data=data) if serializer.is_valid(): serializer.save() return Response({"message":"Category is created sucessfully!"},status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) Here is Postman request: Asking help here is the only option for me now. I will really appreciate your answers. regards, I followed this solution but that didn't fixed. I searched a lot on medium and other platforms but all in vein. -
how to send frontend error to a django view for getting log?
I want to implement logging system with django but in my front i have some errors: $.ajax({ method: 'post', processData: false, contentType: false, cache: false, data: data, enctype: 'multipart/form-data', url: endpoint, success: function (response) { if (response.track_code !== null) { redirectToRRRDetailPage(response.track_code); } if (response.general_error) { showErrorMessage(response.general_error); hideGeneralLoader(); } else { showFieldErrorMessages(response.input_errors); hideGeneralLoader(); } }, error: function (error) { showErrorMessage("خطایی در ارتباط با سرور به وجود آماده است. لطفا جهت بررسی با پشتیبان تماس حاصل فرمائید.") hideGeneralLoader(); } }); } how can i send this erros detail to an end point for logging with this error detail? -
Django How to Load Static and Media files
I am unable to load both static and media images at the same time. My static/images/ folder contains a default profile picture and my media folder contains images uploaded by users. Currently, i am getting the image from the user model and my media folder is working where any uploaded profile images from a user is displayed correctly. However, loading the default profile picture does not work. I have tried setting the default for the imagefield to include the static/images directory and this still does not work. I had a look in the admin panel and found that it returns "http://127.0.0.1:8000/media/static/images/default_profile_picture.jpg". What should happen is something like "http://127.0.0.1:8000/static/images/default_profile_picture.jpg". When loading the default picture it should go straight to the static folder then the images folder and if it is not looking for the default profile picture, it should look in the media folder (which is what it is currently doing). However, it is going straight to the media folder looking for the default profile picture. Any ideas on how to go straight to the static folder to look for the default profile picture whilst also be able to view user uploaded images in the media folder? It is also important … -
Django python: no such column:
I used a form to create a django post with a single "text" field. Then I modified the post model. Now there are three forms "author", "body" and "title". Also changed the mentions in home.html and other files. Logically, it should work, but it gives an error in the file home.html there is no such column: pages_posts.title error in line 5 Some files from my project: views.py from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views.generic import TemplateView, CreateView, DetailView from django.views.generic import ListView from .models import Posts class HomePageView(ListView): model = Posts template_name = 'home.html' # post_list = Posts.title # context_object_name = 'all_posts_list' class AboutPageView(TemplateView): template_name = 'about.html' class SignUpView(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class NewPostUpView(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class BlogDetailView(DetailView): model = Posts template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Posts template_name = 'post_new.html' fields = ['title', 'author', 'body'] models.py from django.db import models class Posts(models.Model): title = models.CharField(max_length=200, default='False') author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title class Meta: verbose_name = 'Пост' verbose_name_plural = 'Посты' home.html {% extends 'base.html' %} {% block content %} {% for post in object_list %} …