Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker: Cannot COPY from parent directory while building the image
I am trying to use docker-compose up -d for deploying my django application. The problem is that my Dockerfile and docker-compose.yml are in one directory, but need access to a requirements.txt from the parent directory. Minimal Example: Filestructure: requirements.txt (file) docker (directory) docker/Dockerfile (file) docker/docker-compose.yml (file) Dockerfile: FROM python:3.10-slim COPY ./../requirements.txt /requirements.txt docker-compose.yml: version: '3' services: django: container_name: django_123 build: context: ./.. dockerfile: ./docker/Dockerfile expose: - "8000" The setup works on Docker Desktop 4 on Windows 10, but not on Ubuntu 22. I get the error: Step 1/2 : COPY ./../requirements.txt /requirements.txt COPY failed: forbidden path outside the build context: ../requirements.txt () ERROR: Service 'django' failed to build : Build failed I already read that I should build the image from the parent directory, but I get the same error message. What could be the problem? And why does it work on Windows and not on Ubuntu? -
How to use install django_debug_toolbar
I am trying to run django_debug_toolbar I followed the instructions at: https://django-debug-toolbar.readthedocs.io/en/latest/installation.html I also saw several YouTube videos, this should be working. Here's the code ` import debug_toolbar from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('__debug__/', include(debug_toolbar.urls)), ]` I tried to install django_debug_toolbar, but it gives a 404 -
Django Python Link Dropdown Element to Database
I am working on creating a web application that will generate a report for visiting different office locations. I have implemented the choices option in a model and placed all the different offices within the choices. One of the things we have to do is take inventory of the equipment in the office ex. computers in use, computers not in user, monitors in use, monitors not in use, etc. I am wanting to make it so that essentially each inventory report is linked to the correct location based on what the user has selected so that these reports can be called later. I currently do not have a ton of code as I decided to focus on the inventory portion first. But is it even possible to link whatever the user selects as the location as the way to call previous reports? Also, would I need to create a model for each location they would be the same as the below model? Below is what I have like a said not much from django.db import models OFFICE_CHOICES = ( ('Akron, OH', 'AKRON'), ('Atlanta, GA', 'ATLANTA'), ('Austin, TX', 'AUSTIN'), ('Birmingham, AL', 'BIRGMINGHAM'), ('Boston, MA', 'BOSTON'), ('Charleston, SC', 'CHARLESTON_SC'), ('Charleston, WV', 'CHARLESTON_WV'), … -
Trying to Display Pandas DataFrame in Django HTML Output
I am currently trying to display a dataframe in HTML output with Django. Currently I have designed a view that takes in a couple csv files, runs some functions on them and then outputs a results dataframe. I am now trying to get this results dataframe to be on my html output. views.py: results_html = results.to_html(index=False) return render(request, 'home.html', {'results_html': results_html}) home.html: <html> <body> <table>{{results_html|safe}}</table> </body> </html> My home.html is in the templates folder within my overall app folder. I am trying to get this table to be displayed after clicking a button and also allow the ability to add design to the table to make it more visually appealing. I have been researching on this site and other and tried their solutions and the table still doesn't output. -
How to deal 'WSGIRequest' object has no attribute 'Get'
I am a django beginner even programming beginner this issue I have found one day still can not work out views.py from django.shortcuts import render, redirect from django.template import loader from .models import Topic from django.contrib.auth.models import User from .forms import TopicForm # Create your views here. def home(request): q = request.Get.get('q') topics = Topic.objects.filter(name__icontains=q) context = {'topics':topics} template = loader.get_template('home.html') return render(request, 'home.html', context) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): name = models.CharField(max_length=200) description = models.TextField() home.html <body> {% include 'navbar.html' %} <div> <div> <h3>Topic</h3> {% for topic in topics %} <a href="{% url 'home' %}?q={{topic.name}}">{{topic.name}}</a> {% endfor %} </div> </div> </body> I tried if statment still not work -
WebSocket connection to 'ws://localhost:8000/ws/' failed: in djangorest
(index):77 WebSocket connection to 'ws://localhost:8000/ws/' failed: (anonymous) @ (index):77 2127.0.0.1/:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received i want to make websoket in my app and i always get this errror i installed djangorestchannel and redis-channel and still erorr found image of errorhere -
Python Django views.py filter button doesn't work
My models.py: class Recipe(models.Model): recipe_title = models.CharField("Назва Рецепту", max_length=50) recipe_text = models.TextField("Текст Рецепту") recipe_image = models.ImageField(default="", null=True, blank=True, upload_to="recipeImages/") isHot = models.BooleanField(default=False) isVegan = models.BooleanField(default=False) author_name = models.CharField("Імʼя автора", max_length=100) pub_date = models.DateTimeField("Дата публікації") def __str__(self): return self.recipe_title def isHOT(self): if self.isHot == True: return self.recipe_title My views.py: def index(request): latest_recipes = Recipe.objects.order_by('-pub_date')[:5] search_query = request.GET.get('search', '') if 'ishot' in request.POST: recipes = Recipe.objects.filter(isHot=True).all() else: recipes = Recipe.objects.all() if search_query: recipes = Recipe.objects.filter(recipe_title__icontains=search_query) else: recipes = Recipe.objects.all() return render(request, 'recipes/list.html', {'latest_recipes': latest_recipes, 'recipes': recipes}) 'search_query' function works, 'ishot' function itself works as well, but filter 'recipes = Recipe.objects.filter(isHot=True).all()' doesn't -
ModuleNotFoundError: No module named 'requests.adapters' when using pyfcm
I'm trying to use pyfcm library in my django project , by adding it to requiements.txt but I noticed that it is getting an error that mainly comes because of trying to import from requests library .. here is the error : rolla_django | from pyfcm import FCMNotification rolla_django | File "/usr/local/lib/python3.10/dist-packages/pyfcm/__init__.py", line 14, in <module> rolla_django | from .fcm import FCMNotification rolla_django | File "/usr/local/lib/python3.10/dist-packages/pyfcm/fcm.py", line 1, in <module> rolla_django | from .baseapi import BaseAPI rolla_django | File "/usr/local/lib/python3.10/dist-packages/pyfcm/baseapi.py", line 6, in <module> rolla_django | from requests.adapters import HTTPAdapter rolla_django | ModuleNotFoundError: No module named 'requests.adapters' and here is my requirements.txt Django~=4.1.1 djangorestframework~=3.13.1 django-extensions pymysql~=1.0.2 requests tzdata psycopg2-binary django-crontab pyfcm -
Foreign key in django signals
i need use node in created method signals, but raise this error my signals : @receiver(post_save, sender=AUTH_USER_MODEL) def create_user_progress(sender, instance, created, **kwargs): specialties = instance.specialties section = SectionSpecialties.objects.filter(specialties=specialties) section_slice = section.values_list('section_id', flat=True) node = Nodes.objects.filter(sections__in=section_slice) if created: Progress.objects.create(user=instance, node=node) my error : Cannot assign "<QuerySet [<Nodes: dsdsd - cccc>, <Nodes: chizi nemiyare - cccc>]>": "Progress.node" must be a "Nodes" instance. -
Read the time and run a function
I have a Django app which collects start time and date from the user and store in the sqlite. I want to read the date & time from database and run a function only during that time. Could anyone suggest a best way to do this? I tried with scheduler and no luck -
Django queryset related field lookup with filtering the last object
I am building a Price comparing django app, i came across this scenario where i need to filter the Last price for each seller in a related field lookup. Seller model : class Seller(models.Model): name = models.CharField(max_length=250, null=True) Part model : class Part(models.Model): name = models.CharField(null=True, blank=True, max_length=250, unique=True) Seller model : class Price(models.Model): seller = models.ForeignKey(Seller, on_delete=models.CASCADE, null=True, blank=True, related_name='sellerprice') part = models.ForeignKey(Part, on_delete=models.CASCADE, null=True, blank=True, related_name='partprice') price = models.FloatField(null=True, blank=True) added = models.DateTimeField(auto_now_add=True, null=True, blank=True) Each item for sale has 4 price history ordered by "added" and each price has the seller name next to it. views Queryset : parts = Part.objects.all() Template : {% for part in parts %} {% for y in part.partprice.all %} <a href="{{y.part.amazonURL}}"><p>${{y.price}} {{y.seller}}</p></a> ... ... ... {% endfor %} {% endfor %} price table : Problem is: I am trying to query : LAST PRICE per PRODUCT for each SELLER ordered by newest ADDED date so far i tried : >>> for part in parts: ... for price in part.partprice.all().order_by('price')[:4]: ... print(price) result : (NGK 3951) $4.0 Amazon @2023-01-09 20:36:37.083544+00:00 (NGK 3951) $5.0 Amazon @2023-01-09 20:26:12.961078+00:00 (NGK 3951) $5.5 Rockauto @2023-01-09 20:26:31.890411+00:00 (NGK 3951) $7.0 Ebay @2023-01-09 20:26:20.358864+00:00 (Bosch Automotive 9603) $1.0 … -
Defining different apps in a one page template-Django
I'm trying to deploy a website and I need to use different apps. The website is one page that elements change and you can see different pages. But the problem is that because I'm using different apps the Django needs url to call the views.py function and I don't want separated urls for each app. I want to have an template that receives all the views.py variables from different apps and show them. The models are already registered. Directory: models.py: class AboutpageText(models.Model): aboutText = models.TextField() class Icons(models.Model): iconName = models.CharField(max_length=255) def __str__(self): return self.iconName class ServiceItems(models.Model): serviceIcon = models.CharField(max_length=255) serviceName = models.CharField(max_length=255) serviceText = models.TextField() def __str__(self): return self.serviceName views.py: def aboutpage(request): aboutpageText = AboutpageText.objects.all() icons = Icons.objects.all() serviceItems = ServiceItems.objects.all() return render(request, "index.html", context={"aboutpageTexts": aboutpageText, "serviceItems": serviceItems, "icons": icons}) aboutpage_app/urls.py: urlpatterns = [ path('', views.aboutpage) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) index.html(template): {% for aboutpageText in aboutpageTexts %} <strong>{{ aboutpageText.aboutText }}</strong> {% endfor %} The values are not passed to the index.html I tried to have a views file called mainView.py in the main directory(where manage.py is) and pass all values from apps views file to this file then send the variables to template, But the didn't work too. -
Problem with gunicorn and nginx while deploying django project to digitalocean
I am trying to host a django project using digitalocean on a domain. While the project is visible in the ip address, it does not work with the domain. These are the exact steps I tried. Can you please help sort this issue. Thank you. sudo apt update sudo apt install python3-pip python3-dev nginx sudo pip3 install virtualenv mkdir ~/projectdir and cd~/projectdir source env/bin/activate pip install django gunicorn django-admin startproject test_project ~/projectdir ~/projectdir/manage.py makemigrations ~/projectdir/manage.py migrate sudo ufw allow 8000 sudo fuser -k 8000/tcp gunicorn -w 2 -b 0.0.0.0:8000 --chdir /home/MY_USER_NAME/projectdir/test_project test_project.wsgi deactivate sudo vim /etc/systemcd/system/gunicorn.socket Pasted the following content by using vim: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target sudo vim /etc/systemd/system/gunicorn.service Pasted the following content through vim: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=MY_USER_NAME Group=www-data WorkingDirectory=/home/MY_USER_NAME/projectdir ExecStart=/home/MY_USER_NAME/projectdir/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ test_project.wsgi:application [Install] WantedBy=multi-user.target sudo systemctl start gunicorn.socket sudo systemctl enable gunicorn.socket sudo vim /etc/nginx/sites-available/test_project/ Pasted the following content using vim: server { listen 80; server_name IP_ADDRESS www.MY_DOMAIN MY_DOMAIN; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/MY_USER_NAME/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } sudo ln -s /etc/nginx/sites-available/test_project /etc/nginx/sites-enabled/ sudo systemctl restart nginx … -
remove Django "channels" package INFO logs
I recently started using the channels package in Django (versions: channels==3.0.4 and channels-redis==3.3.1) The application is sending massive amount of unwanted logs for each request i make to Django: {"time": "2023-01-11 16:12:09 UTC", "msg": "HTTP %(method)s %(path)s %(status)s [%(time_taken).2f, %(client)s]", "logger": "edison", "level": "INFO", "log_trace": "/Volumes/dev/venv3.8/lib/python3.8/site-packages/channels/management/commands/runserver.py"} the log seems exactly the same no matter what request i send. I tried to set the channels logging level to ERROR using logging.getLogger('channels').setLevel(logging.ERROR) just like i do with other packages but it doesn't help any ideas what I need to do to remove those logs? -
Cannot run migration from Django on Docker to MariaDB installed on host
I created a Django project running on Docker, and I successfully connected from the container to the host MariaDB server as an URL host.docker.internal:3306 with the command sudo docker run -p 8000:8000 --add-host=host.docker.internal:host-gateway -d kms1212/jsis:latest. But due to several problems(I can't remember why I did it), I removed the original database, created a new database, and modified settings.py. Then I ran the modified Docker image that is built from Dockerfile: FROM ubuntu:22.04 ENV PYTHONUNBUFFERED 1 RUN apt-get -y update RUN apt-get -y install build-essential python-is-python3 pip mysql-client libmysqlclient-dev RUN mkdir /usr/local/workdir WORKDIR /usr/local/workdir COPY requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY jsis . EXPOSE 8000 CMD ["bash", "-c", "python manage.py makemigrations && python manage.py showmigrations && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker jsis.asgi:application"] I dropped and recreated the database and checked that no old constraints and tables were left, but despite my effort, I got some error messages from the container log like this eventually: No changes detected admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ … -
What is the best way to raise an exception in case of BadHeaderError in django unit testing?
Tests fail with an error response meaning that it is likely to be allowing email with wrong data and yet it should throw an HttpResponse as expected, I have tried to figure it out why my test is failing and returning 200 http status code but not as expected = 400. Test to raise an exception def test_exception_raised(self): # register the new user response = self.client.post(reverse('register'), self.user, format='text/html') # expected response self.assertEqual(response.status_code, status.HTTP_302_FOUND) # verify the email with wrong data data = {"uid": "wrong-uid", "token": "wrong-token"} response = self.client.post(reverse('resetpassword'), data, format='text/html') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) Error File "../tests/test_passwordreset.py", line 55, in test_exception_raised self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) AssertionError: 200 != 400 Failing code -
Django: 0001_initial.py is not on current status after complementing models.py
I am new to Django/ python and I am facing a problem with my models.py I added some attributes, saved it -> py manage.py makemigrations -> py manage.py migrate but the current attributes are not shown in the 0001_initial.py and also when I am opening the database in my DB Browser for SQLite I still get the old status. Can anyone of you help me out with this? Thanks in advance, Laura Here's my code: models.py ` from django.db import models # from django.contrib.auth.models import User # Create your models here. category_choice = ( ('Allgemein', 'Allgemein'), ('Erkältung', 'Erkältung'), ('Salben & Verbände', 'Salben & Verbände'), ) class medicament(models.Model): PZN = models.CharField(max_length=5, primary_key=True) # Maxlaenge auf 5 aendern name = models.CharField('Medikament Name', max_length=100) description = models.CharField('Medikament Beschreibung', max_length=500) category = models.CharField(max_length=100, blank=True, null=True, choices=category_choice) instructionsForUse = models.CharField('Medikament Einnehmhinweise', max_length=400) productimage = models.ImageField(null=True, blank=True, upload_to="images/") stock = models.PositiveIntegerField(default='0') reorder_level = models.IntegerField(default='0', blank=True, null=True) price= models.DecimalField(default='0.0', max_digits=10, decimal_places=2) sold_amount = models.IntegerField(default='0', blank=True, null=True) sales_volume = models.DecimalField(default='0.0', max_digits=10, decimal_places=2) def __str__(self): return self.name And the 0001_initial.py `# Generated by Django 3.2.16 on 2023-01-05 14:33 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='medicament', fields=[ ('PZN', … -
how to use static in django project
Is this not the correct way of making use of Django's static directories in code? The folder is static/assets/css/style.css settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) urls.py from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) base.html {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static 'assets/css/style.css' %}"> </head> <body> <a href="">Go somewhere</a> </body> </html> style.css a{ text-decoration: none; } -
How can I save the data from my Django crispy form
This is how my form looks like: When I press submit and go to the page where the post should be rendered, then I cannot see the post I just have created. This is the page where I have my form: 'anzeige_new.html' {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Inserat erstellen</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} This is where it should be rendered: "angebote.html" {% block content %} {% for post in posts %} <p>Inside for loop</p> <a class="mr-2" href="#">{{ Post.objects.all }}</a> <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} forms.py class PostForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) # If you pass FormHelper constructor a form instance # It builds a default layout with all its fields self.helper = FormHelper(self) # You can dynamically adjust your layout self.helper.layout.append(Submit('save', 'save')) class Meta: model = Post fields = ('title', 'category', 'weekday') models.py class … -
Run Celery tasks on Railway
I deployed a Django project in Railway, and it uses Celery and Redis to perform an scheduled task. The project is successfully online, but the Celery tasks are not performed. If I execute the Celery worker from my computer's terminal using the Railway CLI, the tasks are performed as expected, and the results are saved in the Railway's PostgreSQL, and thus those results are displayed in the on-line site. Also, the redis server used is also the one from Railway. However, Celery is operating in 'local'. This is the log on my local terminal showing the Celery is running local, and the Redis server is the one up in Railway: -------------- celery@MacBook-Pro-de-Corey.local v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- macOS-13.1-arm64-arm-64bit 2023-01-11 23:08:34 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: suii:0x1027e86a0 - ** ---------- .> transport: redis://default:**@containers-us-west-28.railway.app:7078// - ** ---------- .> results: - *** --- * --- .> concurrency: 10 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . kansoku.tasks.suii_kakunin I included this line of code in the Procfile regarding to the worker (as I … -
Comparação de tabelas em python
Olá, gostaria de saber como que eu comparo duas tabelas em python e crio uma nova apenas com as linhas que são diferentes entre elas. Eu pensei na função merge() mas não sei como remover as linhas diferentes. -
vscode testing with pytest for dockerized Django project
i want to debug my tests in vscode for my Django project witch is set up in a docker container but the problem is it always says pytest discovery error, sometimes it seems to not be able to import modules(for example models) inside the test file and after some configuration it seems to not find the test file itself. all the folders of my project have an init.py file so everything is treated as a package, by the way there is no problem importing modules in my Django project. the odd thing is when I run pytest inside of my docker container it works fine but I want to debug the tests. i am fairly new to this so any help would be welcomeenter image description here I enabled pytest in the .vscode/settings.jsonenter image description here file as some other settings I tried also creating a .env file with PYTHONPATH in it to my root folder cause every tutorial I found work with a virtual environment and not a docker container -
Errors in importing a react library created using rollup
I am writing a React/Next app. I have created a react accordion-component external to the app. I am using rollup to create a package and importing that package into my app. When I run the app I get the error ./node_modules/@zeilsell-user1/accordion-component/dist/esm/index.js Module parse failed: Unexpected token (1:4) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders use clientfunction getDefaultExportFromCjs (x) { | return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; | } I do not understand why I am seeing this error. The component is ESM so why the CSJ function? Nexrjs uses webpack, but that should handle csj, I can't find anything about loaders anyway. I am assuming that the issue is on the component side, so I have included the rollup, tsconfig and package files below. Really appreciate any help that the community can offer me as I have been stuck on this problem for ages. my rollup.config.mjs import {nodeResolve} from '@rollup/plugin-node-resolve'; import commonjs from "@rollup/plugin-commonjs"; import typescript from "rollup-plugin-typescript2"; import banner2 from "rollup-plugin-banner2"; import dts from "rollup-plugin-dts"; import packageJson from "./package.json" assert { type: "json" }; export default [ { input: … -
makemigrations ModuleNotFoundError: No module named Insta
I had to re-do my project, and I copied the code from my files [names and directories are virtually the same] When I try to make migrations, this error pops out. I have insta in my settings.py at installed apps. File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'insta'I'm not sure if it will help, but here's my file structure I'm not really sure what to do, could someone help? -
The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead
I'm not sure what is coursing the problem.... The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead. views.py from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages def Insertrecord(request): if request.method == 'POST': if request.POST.get('empname') and request.POST.get('email') and request.POST.get('country'): saverecord = EmpInsert() saverecord.empname = request.POST.get('empname') saverecord.email = request.POST.get('email') saverecord.country = request.POST.get('country') saverecord.save() messages.success(request, 'Record saved successfully...!') return render(request, 'Index.html') else: return render(request, 'Index.html'), I have change the code.... from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages def Insertrecord(request): if request.method == 'POST': if request.POST.get('empname') and request.POST.get('email') and request.POST.get('country'): saverecord = EmpInsert() saverecord.empname = request.POST.get('empname') saverecord.email = request.POST.get('email') saverecord.country = request.POST.get('country') saverecord.save() messages.success(request, 'Record saved successfully...!') return render(request, 'templates/Index.html', {}) else: return render(request, 'templates/Index.html', {}) but still it doesn't display what it should... Index.html <!DOCTYPE html> <html lang="en"> <head> <title>Insert new Record</title> </head> <body> <h1>Create or New record Insert into MySQL(PhpMyAdmin)</h1> <h2>Python Django web Programming</h2> <hr> <form method="POST"> {% cdrf_token %} Employee Name : <input type="text" placeholder="Enter Name" name="empname" required> Email : <input type="text" placeholder="Enter Email" name="email" required> country : <input type="text" placeholder="Enter Country" name="country" required> <input type="submit" value="Insert record"> {% if messages %} {% for message in messages %} <h2 …