Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django 4.1 async orm in FastAPi
In verson 4.1 some async stuff was added to orm part of Django. I want to use Django orm in fastAPi, I created a small setting file for using Django orm like this: import os import sys import django from django.conf import settings BASE_DIR = os.path.dirname(os.path.abspath(__file__)) INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'orm', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '127.0.0.1', 'PORT': '5432', } } settings.configure( DATABASES = DATABASES, INSTALLED_APPS = INSTALLED_APPS, ) django.setup() if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) I want to run a query is main file like this in FastApi: @app.get("/test-orm") async def test_django_orm(): results = await User.objects.filter(username="user0") paginator = Paginator(results, 2) paginated = json.loads(serializers.serialize('json', paginator.page(1))) return {"data": paginated} This code simple doesn't work! If I remove async and await it works perfectly, but I write to use async friendly code! Any help and ideas appreciated :) -
How to make raw text file (to edit robots.txt) editor in Django Wagtail admin
The goal is to create a text file editor within the Wagtail admin site. Specifically for robots.txt file. I want the admin to update the file from the admin. How can I do that? -
Need Solution regarding Django
I have been going through Django-admin. but I am getting this error. Here is views.py from django.http import HttpResponse def Milton(request): print("This is a test page") return("<h1>Index</h1>") urls.py """Medical URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from pathlib import Path from django.contrib import admin from django.urls import path from django.views import Milton urlpatterns = [ path('admin/', admin.site.urls), path('Milton/', Milton.site.urls), ] Here is the Powershell Command Line error: Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Try the new cross-platform PowerShell https://aka.ms/pscore6 spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + conda activate base + ~~~~~ + CategoryInfo : ObjectNotFound: (conda:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\milto\Desktop\Med\Medical> python -m venv .venv PS C:\Users\milto\Desktop\Med\Medical> python .\manage.py … -
How to remove port number from url in production server in django project?
I am deploying my project in production server but the port number is coming in the url. So is there any way to remove the port number from url in Django http://domain_name:8586/admin/login?next=/ -
django If don't have a model, Redirect to createview. If there is, I would like to do it in detail view
class KcalDetailView(DetailView): model = User context_object_name = 'target_kcal' template_name = 'kcalculatorapp/detail.html' def dispatch(self, request, *args, **kwargs): if not self.request.user.kcal: return HttpResponseRedirect(reverse('kcalculatorapp:create')) return super(KcalDetailView, self).dispatch(request, *args, **kwargs) If you go into the detail view, User has no kcal. error That's what it says What should I do? -
Getting error while creating hitting /admin endpoint
I am trying be build an Token Authentication using DRF AuthToken. I want my own customisation for USER model, and this is how I have done. Now I want to login into Django Admin Panel, but when I hit that endpoint I get an error django.db.utils.ProgrammingError: (1146, "Table 'roadmap.tutor_authuser' doesn't exist") and when I am trying to createsuperuser its asks for my email and after entering that I am getting same error. This is how my custom USER Model is, class AuthUser(AbstractUser): ADMIN = 'A' STUDENT = 'S' TUTOR = 'T' ROLE_CHOICES = ( (ADMIN, 'Superuser'), (STUDENT, 'Student'), (TUTOR, 'Tutor'), ) username = None first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=254, unique=True) role = models.CharField(max_length=1, choices=ROLE_CHOICES, default=STUDENT) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] I also have done make migration and migrate successfully. And this is how my migration file looks like # Generated by Django 4.1 on 2022-08-09 04:40 import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='Roadmap', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('course_name', models.CharField(max_length=255)), ('course_title', models.CharField(max_length=255)), ('course_description', models.TextField()), ], ), migrations.CreateModel( name='Section', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, … -
How can I display the added Friends to their respective user friends list?
I am developing a feature same like Facebook. means a user can send a friend request and then that specific user will accept the friend request. so it means they both become friends with each other. Now how can I display them in such a way that user A is a friend of User B and vice versa? That's how I have developed it but can't display both of the users in the friend's list. models.py: class AddToNetwork(models.Model): NETWORK_CHOICES = ( ('ADD', 'Add'), ('ACCEPT', 'Accept'), ('DELETE', 'Delete'), ) id = models.UUIDField( primary_key = True, default = uuid.uuid4,editable = False) add_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name="add_to", null=True, blank=True) added_from = models.ForeignKey(User, on_delete=models.CASCADE, related_name="add_from", null=True, blank=True) network_status = models.CharField(max_length=30, choices = NETWORK_CHOICES) added_at = models.DateTimeField(auto_now_add = True) deleted_at = models.DateTimeField(auto_now = True) def __str__(self): return str(self.add_to) Sending a friend request using the following method/logic: def addToNetwork(request, id): try: add_to = User.objects.get(id = id) current_user = User.objects.get(id = request.user.id) network = AddToNetwork.objects.create(add_to = add_to, added_from=current_user,network_status = 'ADD') messages.success(request,f'Request Sent to {add_to.first_name} {add_to.last_name}') return redirect('userProfileDetail', id) except User.DoesNotExist: add_to = None return render(request,'network/network_userProfile.html') Accepting a friend request using the following logic: def acceptNetworkRequest(request, id): try: # if 'accept_friendRequest' in request.GET: friend_request = AddToNetwork.objects.get(id = id) … -
Getting django.db.utils.DatabaseError
I am using Django==3.1.9 with djongo==1.3.6. When saving user in database I am getting django.db.utils.DatabaseError. I think the issue is with the model file. I have forked the code from GitHub which uses Postgres DB. I have only changed the DB configuration to mongo in settings.py Here is the error log Internal Server Error: /signup/ Traceback (most recent call last): File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\djongo\sql2mongo\query.py", line 929, in _insert query.execute() File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\djongo\sql2mongo\query.py", line 397, in execute res = self.db[self.left_table].insert_many(docs, ordered=False) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\pymongo\collection.py", line 770, in insert_many blk.execute(write_concern, session=session) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\pymongo\bulk.py", line 533, in execute return self.execute_command(generator, write_concern, session) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\pymongo\bulk.py", line 366, in execute_command _raise_bulk_write_error(full_result) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\pymongo\bulk.py", line 140, in _raise_bulk_write_error raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'admin_org_id': 1}, 'keyValue': {'admin_org_id': None}, 'errmsg': 'E11000 duplicate key error collection: ssoDB.users_user index: admin_org_id_1 dup key: { admin_org_id: null }', 'op': {'password': 'pbkdf2_sha256$216000$bbg7CWLFi44A$69XZYjuc/T1Unv0f7QXrTRTURDbPT+HhT8A2AH+WE14=', 'last_login': None, 'is_superuser': False, 'id': UUID('a9a2b67b-fb63-4b55-b889-f24676949fa6'), 'email': 'testuser@vigastudios.com', 'avatar': '', 'first_name': 'Abhijit', 'last_name': None, 'nickname': None, 'phone_number': '+919083242266', 'organization_id': None, 'admin_org_id': None, 'is_active': True, 'is_staff': False, 'created_at': datetime.datetime(2022, 8, 9, 5, 9, 37, 236707), '_id': ObjectId('62f1ec11e10c9c015b52dbd6')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': … -
UNIQUE constraint failed: Worked before now it doesn't
I was trying to create a function that programmatically adds owners to lots based on data from a csv file. It was functional before before but now it displays a UNIQUE constraint failed: valuation_lot.lot_number This is the code from which the error was raised. Please let me know if more information is needed. try: lot_new = Lot.objects.get(pk=lot["lot_number"][index]) lot_new.owner.add(owner_new) lot_new.save() except: lot_new = Lot.objects.create( lot_number=lot["lot_number"][index], lot_description= lot["lot_description"][index], lot_rate = Decimal(float(lot['lot_rate'][index])), ) lot_new.owner.add(owner_new) lot_new.save() -
Slack Login With DJango
I want to implement slack login with django and to do that i am using Django Allouth package but i am facing an error -
How to calculates face recognition distance in VGGFace
I am also interested in facial recognition. I am working on Using VGGFace for Face Recognition. I try to find 2 or 3 people who are similar to that person and what percentage of them are accurate. I'm new to dating.i am use this link https://www.codemag.com/Article/2205081/Implementing-Face-Recognition-Using-Deep-Learning-and-Support-Vector-Machines -
How to go implement custom user Token authentication in DRF?
I am trying to do user Token authentication using DRF and I have done that succesfully, but for default USER Model of django , I am want to properly configure the fields in that like I dont want username and wanna make email & password for login and wanna add more fields like first_name and last_name during signup process. I want to add one more field which will say whether this is a student or teacher or a superuser. during signup the data will get stored accordingly. -
Is there a way to pass in an Form Object in an authenticate method in django
I am trying to pass in an form object in an authenticate() method but it is saying there is no attribute for username and password. Is there a specific way I can authenticate this form or not. I have imported everything already from forms and auth.models MY VIEWS.PY def user_login(request): if request.method == 'POST': login_info = LoginForm(request.POST) user = authenticate(username = login_info.username, password=login_info.password) if user: login(request,user) return HttpResponse(reversed('index')) else: return HttpResponse("Wrong") else: login_info = LoginForm() return render(request,"login.html",{'logininfo':login_info}) MY FORMS.PY class LoginForm(forms.Form): username = forms.CharField(label = 'Your username') password = forms.CharField(label= "Don't tell any but us",widget=forms.PasswordInput()) IS there a different way user = authenticate(username = login_info.username, password=login_info.password) -
How to save two values from options in Django?
Am trying to save dropdown in django without using django forms am directly getting the form values to views. This is my view: try: courses = Course.objects.all() except ObjectDoesNotExist: courses = None form = WelcomeForm() if request.method == 'POST': form = WelcomeForm(request.POST) if form.is_valid(): _process = form.save(commit=False) _process.save() messages.success(request, 'Welcome settings has been added successfully') context = {'courses': courses} return render(request, 'welcome/add_form.html', context) And thus, using courses in my dropdown: <select class="form-select" data-search="on"name="courses" multiple> <option></option> {% for data in courses %} <option value="{{data.name}}">{{data.name}}</option> {% endfor %} </select> From the above, i can save name of the course, but i also need slug of the course to make user clickable ! HOw to save two values from the selected options ? -
Navbar get a ValueError
my nav bar: <form method = "POST">{% csrf_token %} <button class="navbar-brand", name = "next",value="next", href="/app/{{ app.id }}/start/begin">Next</a> </form> my def: def view2(request, app_id): index=0 pdict = {1:2} adict = {1: 'start'} if request.method == 'GET': app = Application.objects.get(id=app_id) ac_id = list(adict.keys())[index] p_id = pdict[anode_id] return show(request=request,app_id=app_id,p_id=p_id) else: if request.POST.get("next"): index += 1 ac_id = list(adict.keys())[index] page_id = pdict[anode_id] request.method ='GET' return show(request=request,app_id=app_id,p_id=p_id) if i press next it gives me a ValueError:didn't return an HttpResponse object. It returned None instead. How can i solve this problem? -
Django Frontend Autho key and refresh key
I would like to separate my Django frontend and backend. Literally creating 2 Django servers. What is the best way to store auth access-token and refresh-token on frontend? What is the best way to validate auth when API is called? Thanks! -
django-filter don't use rawqueryset
i have a sql, SELECT asset.id, region.id as region_id, asset.ip, asset.os_type, asset.status, asset.device_type_id FROM region_info AS region JOIN computer_info AS computer ON region.id = computer.region_id JOIN computer_cabinet_info AS cabinet ON computer.id = cabinet.computer_id JOIN asset_location_info AS location ON cabinet.id = location.cabinet_id JOIN asset_server_info AS asset ON location.asset_id = COALESCE ( asset.parent_id, asset.id ) WHERE asset.del_flag = 0 i can't use django orm, so i use raw sql. but django-filter must use queryset,because rawqueryset no .all() method. this is my viewset: from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import ListModelMixin class RegionAssetViewSet(ListModelMixin, GenericViewSet): serializer_class = AssetServerInfoSerializer filter_backends = [DjangoFilterBackend] filter_class = ServerFilter def get_queryset(self): queryset = RegionAssetListVirtual.objects.raw(region_asset_sql) return queryset Can someone help me. -
Django error NoReverseMatch on remote site but works fine locally
My Django site is working fine locally. I am pushing it to my website but one of the links is not working and I can not for the life of me see why as similar things are working fine. here is my url.py from . import views app_name = 'sitepages' urlpatterns = [ path('', views.greeting_page_def, name='greeting_page_html'), path('home/', views.home_def, name='home_html'), path('specs/', views.specs_def, name='specs_html'), path('about/', views.about_def, name='about_name'), path('faq/', views.faq_def, name='faq_name'), path('howTos/', views.howTos_def, name='howTos_name'), path('howTos/puller', views.howTosPuller_def, name='howTosPuller_name'), path('howTos/conformer', views.howTosConformer_def, name='howTosConformer_name'), path('howTos/general', views.howTosGeneral_def, name='howTosGeneral_name'), path('howTos/submitter', views.howTosSubmitter_def, name='howTosSubmitter_name'), ] and my views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required # Create your views here. def greeting_page_def(request): return render(request, 'sitepages/greeting_page_html.html') def about_def(request): return render(request, 'sitepages/about.html') def faq_def(request): return render(request, 'sitepages/faq.html') def home_def(request): return render(request, 'sitepages/home.html') def specs_def(request): return render(request, 'sitepages/specs.html') def howTos_def(request): return render(request, 'sitepages/howTos.html') def howTosPuller_def(request): return render(request, 'sitepages/howTosPuller.html') def howTosConformer_def(request): return render(request, 'sitepages/howTosConformer.html') def howTosGeneral_def(request): return render(request, 'sitepages/howTosGeneral.html') def howTosSubmitter_def(request): return render(request, 'sitepages/howTosSubmitter.html') and the html template that has the links. {% extends 'base.html' %} {% block content %} {% load static %} <a class="link-primary" href="{% url 'sitepages:howTosPuller_name' %}"} >How Tos - Puller</a> <a class="link-primary" href="{% url 'sitepages:howTosSubmitter_name' %}"} >How Tos - Submitter</a> <a class="link-primary" href="{% url 'sitepages:howTosGeneral_name' %}"} >How Tos - General</a> … -
Problem with Django and MySQL. NotSupportedError( django.db.utils.NotSupportedError: MariaDB 10.3 or later is required (found 5.5.65)
I'm using Django for a project with MySQL. I created a virtual environment and installed mysqlclient to connect to the database. But when I try to start the server I get this error. Here's is my version of MariaDB, I installed using Homebrew. And finally the version of mysqlclient in my virtual environment: -
Pymongo Not inserting full document on update_one
I have a lot of documents to update and I want to write a timestamp initially and then an update timestamp when there are duplicates. So I found this answer and am attempting it for MongoDB 6.0 https://stackoverflow.com/a/17533368/3300927 I also store in my model the variable to use when looking for duplicates as searchable If a query has no searchable then I insert it without checking and add a timestamp, then take the results and add a timestamp: data_inserted = collection.insert_many(results) for doc_id in data_inserted.inserted_ids: collection.update_many( filter={'_id': doc_id}, update={'$set': {'insert_date': now, }, }, upsert=True) No issues there: { "_id": { "$oid": "321654987654" }, "IR NUMBER": "ABC784", "Plate": " ", "Plate State": " ", "Make": "TOYOTA", "Model": "TACOMA", "Style": " ", "Color": "SIL / ", "Year": "2008", "insert_date": { "$date": { "$numberLong": "1660000808176" } } } If there is a searchable I attempt to look for it. What I get in MongoDB is only the searchable field with the timestamp: # q_statement.searchable == 'IR NUMBER' for document in results: collection.update_one( filter={q_statement.searchable: document[q_statement.searchable], }, update={'$setOnInsert': {'insert_date': now, }, '$set': {'update_date': now, }}, upsert=True) result: { "_id": { "$oid": "62f19d981aa321654987" }, "IR NUMBER": "ABC784", "insert_date": { "$date": { "$numberLong": "1660001688126" } } } … -
TypeError at /dashboard/profiles/create/ Field 'id' expected a number but got []
Hey engineers I have been trying to fetch model choices through the view so that I can render them in the template to make it easy for the users, but I swear it has given me some hard times I thought its because I had no items in the database but even when I added them the error persisted. Please give me ideas I am sure with you it will work here is my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to = '', default = path_and_rename, blank=True) provider = 'provider' requester = 'requester' user_types = [ (provider, 'provider'), (requester, 'requester'), ] user_type = models.CharField(max_length=155, choices=user_types, default=requester) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') GENDER_MALE = 'Male' GENDER_FEMALE = 'Female' OTHER = 'Other' GENDER_CHOICES = [ (GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female'), (OTHER, 'Other'), ] gender = models.CharField(max_length=15, choices=GENDER_CHOICES, blank=True) email = models.EmailField(default='none@email.com') phonenumber = models.CharField(max_length=15, default='') #blank=True, null=True birth_date = models.DateField(default='1975-12-12') residential_address = models.CharField(max_length=255, default='') village = models.CharField(max_length=255, default='') city = models.CharField(max_length=255, default='') state = models.CharField(max_length=255, default='') country = models.CharField(max_length=255, default='') education_background = models.CharField(max_length=255, default='') single = 'single' married = 'married' statuses = [ (single, 'single'), (married, 'married'), ] marrital_status = models.CharField(max_length=255, choices=statuses, default='single') USD = 'United States … -
Django Rest Framework: backend not found
I'm trying to create and authentication with github account to DRF. why i get 404 error and can't get to github authentication page? I provided the code extracts. If any information is required or you have any questions please let me know. Here's the views.py class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BooksSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] permission_classes = [IsAuthenticated] filterset_fields = ['price'] search_fields = ['name', 'author_name'] ordering_fields = ['price', 'author_name'] def auth(request): return render(request, 'oauth.html') And here's the settings.py # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'social_django', 'store', ] MIDDLEWARE = [ "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", ] ROOT_URLCONF = "books.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ['templates'], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'books_db', 'USER': 'books_user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', 'TEST': { 'NAME': 'test_finance', }, } } AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', 'django.contrib.auth.backends.ModelBackend', ) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_GITHUB_KEY = '-some github key' SOCIAL_AUTH_GITHUB_SECRET = 'git secret' My urls.py router = SimpleRouter() router.register(r'book', BookViewSet) urlpatterns = [ … -
User activity concept using django
I need to make a feature which shows if user is active or not (like on facebook). What is the best and most common way to do this? My concept looks like this: When the user logs in or refreshes the JWT token, it starts a javascript loop which sends f.e. every 3 minutes post request which sets inside User model object current date. Then if another user will enter that user's profile he will get the date from User object and check if current date minus the date from User object < 3 min - if so, it means that user is active, else user is not active. Is it a good way? Should I use websockets for it? I am using DRF and React. -
Django - User model last active column
How can I make a column in my AbstractUser Model that has the date of the last time the user logged in the app? -
form associated with the model not submitting to database
I'm newbie in the Python. I made a landing page that has a form with sending a phone number, but it does not get into the database. Form associated with the model Models.py: from django.db import models from phonenumber_field.modelfields import PhoneNumberField class CallOrder(models.Model): first_name = models.CharField(max_length=50, blank=True, verbose_name='First name') phone = PhoneNumberField(null=False, blank=False, unique=False, verbose_name='Phone') email_field = models.EmailField(blank=True, verbose_name='Email') message = models.TextField(max_length=400, blank=True, verbose_name='Comments') created_at = models.DateTimeField(auto_now=True, verbose_name='Created at') class Meta: verbose_name = 'Call order' verbose_name_plural = 'Call orders' Views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import CallOrderForm def base(request): header_menu_button = {'': 'Home', 'qui_sommes_nous': 'Qui sommes nous', 'nos_services': 'Nos services', 'avis': 'Avis', 'contacts': 'Contacts', 'faq': 'FAQ', 'partenaires': 'Partenaires'} content_body = {'qui_sommes_nous': 'qui_sommes_nous_content', 'nos_services': 'nos_services_content', 'avis': 'avis_content', 'contacts': 'contacts_content', 'faq': 'faq_content', 'partenaires': 'partenaires_content'} form = CallOrderForm() return render(request=request, template_name='repair_service/base.html', context={'title': 'Mr.Ginzby', 'header_menu_button': header_menu_button, 'content_body': content_body, 'form': form}) def call_back(request): if request.method == 'POST': form = CallOrderForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/thanks/') else: form = CallOrderForm() return render(request, 'repair_service/base.html', {'form': form}) Html: <form action="" method="post"> {% csrf_token %}<br> {{ form.as_p }} <div class="d-grid gap-2"><input type="submit" value="Submit" class="btn btn-success"></div> </form>