Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Division, district, upzilla, pourosova/Union, ward, zip code implement in django
I want to implement Bangladeshi Division, district, upzilla, pourosova/Union, ward,zip code in django website..how i can implement it using django ? Can anyone help me or give me some suggestions .. -
How to update model object when testing UpdateView Django
I'm having some issues when I test an update view in my code.Here's the view: class PatientUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): permission_required = 'main.change_patient' model = Patient template_name = 'patient/edit_patient.html' form_class = PatientUpdateForm And this is the patient model: class Patient(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) middle_name = models.CharField(max_length=50, blank=True, default='') hospital_number = models.IntegerField(unique=True, default=0) age = models.IntegerField(blank=False) sex = models.CharField(max_length=6, choices=gender_choices, default='female') weight = models.CharField(max_length=10, choices=gender_choices, default='female') def __str__(self): return f' {self.hospital_number} --> {self.first_name} {self.last_name}' def get_absolute_url(self): return reverse('patient_detail', args=[str(self.id)]) Here's the form: class PatientUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PatientUpdateForm, self).__init__(*args, **kwargs) gender_choices = [ ('male', 'Male'), ('female', 'Female') ] marriage_choices = [ ('married', 'Married'), ('single', 'Single') ] self.fields['gender'] = forms.ChoiceField(choices=gender_choices) self.fields['marriage_status'] = forms.ChoiceField(choices=marriage_choices) class Meta: model = Patient fields = [ 'first_name', 'last_name', 'hospital_number', 'age', 'sex', 'weight' ] And the test case: class PatientsTest(TestCase): def setUp(self): self.superuser = get_user_model().objects.create_user( email='genuis@gmail.com', username='supergenius', password='password', is_superuser = True ) def test_patient_update_view(self): data = { 'first_name':'Joe', 'sex' :'female', } new_patient = Patient.objects.create( first_name='John', last_name = 'doe', hospital_number = 2, age=24, sex = 'male', weight='79 Kg', ) self.client.login(username=self.superuser.username, password='password') response = self.client.post(reverse('patient_edit', kwargs={'pk': new_patient.id}), data) self.assertEqual(response.status_code, 302) # should go through for superusers, response code … -
How to add a new foreign key field in model django without migration error?
I have two models A, B, they contain a lot of data(int database). Suddenly I decided to add a foreign key in model B to A. But Django can't migrate it because existing rows in table B haven't value for this FK. What should I do in such a situation? -
how to correct text orientation for scanned pdf file
I am trying to correct the orientation of the scanned pdf file to correct alignment. I have been attempting with image format using Deskew packagebelow I have uploaded image but I need to correct orientation for the pdf file but I need to update the orientation of the pdf file. Please suggest any resources or code or documentation. -
JavaScript Redirect to Django view with parameters
These lines of code produce an error, my question is, how can I pass the IDS and MESSAGES parameters to windows.location.href in Django view. $(function () { console.log("HOME"); let ids = 1; let messages = "My personal Message"; let myurl = "{% url 'message-page' ids messages %}"; //ERROR HERE: IDS and MESSAGES are variables return window.location.href = myurl }); -
Problem with handling nested dictionary on Django Rest Framework
Testing Django Rest Framework. I receive the following JSON as a result of the POST request for entry (it is important here that the keys of the dictionary, the rest are trifles): { "title": "Test title10", "description": "Test description10", "client": { "name": "Egor10", "surname": "Egor11", "phone": "1645342534532", "adress": "st. Egor9, 53453" }, "products": ["Karamel", "Shokolad", "Limon", "Banan"], "delivery_adress": "st. Egor44", "delivery_date": "2022-23-09:44:00", "delivery_code": "4562gdgll" } I have two models: from django.db import models class Client(models.Model): name = models.CharField(max_length=100, blank=True) surname = models.CharField(max_length=100, blank=True) phone = models.CharField(max_length=100, blank=True) adress = models.CharField(max_length=150, blank=True) class Order(models.Model): title = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=255, blank=True) delivery_code = models.CharField(max_length=50, blank=True) delivery_adress = models.CharField(max_length=150, blank=True) client = models.ForeignKey('Client', on_delete=models.CASCADE, null=True, related_name='orders') Next, I want to make a serializer and look towards SlugRelatedField or Nested relationships to process the nested dictionary relationship: "client": { "name": "Egor10", "surname": "Egor11", "phone": "1645342534532", "adress": "st. Egor9, 53453" } For SlugRelatedField I tried this story in the serializer: class OrderSerializer(serializers.ModelSerializer): orders = serializers.SlugRelatedField( read_only=True, slug_field='phone' ) class Meta: model = Order fields = ['title', 'description', 'delivery_code', 'delivery_adress', 'orders'] In views.py I do the standard processing: def post(self, request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() And this whole story does not work … -
ModuleNotFoundError: No module named 'api.company'
I'm doing a Django project and the only thing I've seen today is this error: File "/home/user/Work/ud_pytest_2/api/company/admin.py", line 4, in <module> from api.company.models import Company ModuleNotFoundError: No module named 'api.company' 1)I set up a virtual environment with pipenv, and it's activated and has all the packages installed. 2)I can easily import packages I installed like django, pytest 3)When I'm trying to import packages from the ACTUAL project, let's say, the class Company from the models section, VSCode doesn't give me any error and actually recognizes the file exists... 4)But when I runserver, it says the module wasn't found. I think it's some kind of path issue but I can't figure out what 5) Already selected the correct interpreter 6) Already trying the Python Path https://i.ibb.co/4KfHhRr/Project.png From the image, I'm showing my project tree. Whenever I try to import what's marked as yellow (I marked it yellow), I get that error, even though VSCode doesn't warn me and even sugest that actual import. Can't figure why the interpreter isn't recognizing the import. I think it's something related to the virtual environment and the Paths but i'm not sure Thanks in advance -
AttributeError at <URL> During Email Verification Python Django
I'm developing the backend of my React-Native application on Python Django. I'm trying to implement registration + email verification. First, the user sends their information for registration in a request. The is_active field is set to False by default. A verification_token is created for each user, stored in a separate table in the DB. The user receives an email which has a link appended with the created verification_token. The VerifyPatient class handles the email verification by checking if the token is equal to the token in the db. I receive the email just fine but get an AttributeError when I click the link, so the user doesn't get registered. My models.py file: from django.db import models from django.contrib.auth.models import User class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') verification_token = models.CharField( max_length=256, blank=True, null=True) My serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import VerificatonToken class TokenSerializer(serializers.ModelSerializer): class Meta: model = VerificatonToken fields = ('user', 'verification_token',) class PatientSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) # DOB … -
Increment Django database value every day
let's assume I've created a Django model with an integer field of count, with initial value for every record equal to 0. How do I increment this value, for every record of the db, once every day? -
Cache.get returns None when using Memcache
Would like to use Memcache to store and retrieve a list of all online users. I am using my console to test if my cache and memcache work but not getting the correct output/ So example when I run this $ python manage.py shell >>> from django.core.cache import cache >>> cache.set("foo", "bar") >>> cache.get("foo") I do not receive any output after running cache.get("foo"). I would be expecting to receive the output bar This is what I have in my settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } USER_ONLINE_TIMEOUT = 300 USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7 my middleware: import datetime from django.core.cache import cache from django.conf import settings class ActiveUserMiddleware: def process_request(self, request): current_user = request.user if request.user.is_authenticated(): now = datetime.datetime.now() cache.set('seen_%s' % (current_user.username), now, settings.USER_LASTSEEN_TIMEOUT) and models.py: from signup import settings ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... def last_seen(self): return cache.get('seen_%s' % self.user.username) def online(self): if self.last_seen(): now = datetime.datetime.now() if now > self.last_seen() + datetime.timedelta( seconds=settings.USER_ONLINE_TIMEOUT): return False else: return True else: return False -
Django - Print Dictionary of List of Lists in a Table in HTML
I have a Dictionary of List of Lists. I want to print this as a structured way preferably a table. For each hostname, i want its specified rows in the table with three columns (Address Interface State ID ) with apprpriate entries printed out. It seems a very complicated nested loop if possible. Here is the dictionary ospfdictkey being passed to the template {'hostname': [['R1-ISP'], ['R2-ISP']], 'ospfneighboraddress': [['192.168.5.2', '192.168.5.13', '192.168.5.25'], ['192.168.5.1', '192.168.5.6', '192.168.5.32']], 'ospfneighborinterface': [['ae1.0', 'ae4.0', 'ae7.0'], ['ae1.0', 'ae2.0', 'ae9.0']], 'ospfneighborstate': [['Full', 'Full', 'Full'], ['Full', 'Full', 'Full']], 'ospfneighborID': [['172.0.0.2', '172.0.0.4', '172.0.0.5'], ['172.0.0.1', '172.0.0.3', '172.0.0.6']]} HTML Code {% for ip in listip %} {% for ospfadd in ospfdictkey.ospfneighboraddress %} {% for a in ospfadd %} <tr> <td>{{ a }}</td> </tr> {% endfor %} {% endfor %} {% endfor %} Here is the end result im getting but its repeating keys data and how do i iterate over other keys to print next as table data ? -
django.security.SuspiciousOperation.response_for_exception:99- Attempted access to '/mediafiles/some' denied
The following line raw_file = fileUpload.objects.get(fileName=str(raw_file_fetch)) path_temp = fileUploadSerializer(raw_file).data["local"] The path_temp returns the error django.security.SuspiciousOperation.response_for_exception:99- Attempted access to '/mediafiles/some' denied. Any ideas how to fix this? -
Django graphene accept any mutation input
In mutation, I just need to save the event name and its payload that might differ and I do not need any validation for it. How can I say graphene that I just need to accept an object? class SendEvent(MutationMixin, relay.ClientIDMutation): class Input: event = graphene.String(required=True) payload = # any object -
Improve Django application logs to only display custom log from Logging settings
I am trying to improve the logging of my Django application to have it in a standardized way for querying it with Loki and for each log that I create, 3 log entries are recorded. For example, any request (sucess or failed) to this endpoint below will generate three log entries. views.py class ModelViewSet(models.ModelViewSet): def retrieve(self, request, *args, **kwargs): try: # do something logger.info(f"{request.path} {request.method} 200: user {request.user.id} - success!") return Response(serializer.data) except Exception as exc: logger.warning(f"{request.path} {request.method} {exc.status_code}: user {request.user.id} - {exc.detail}") return Response(exc.detail, status=exc.status_code) settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'timestamp': { 'format': '{asctime} {levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'timestamp' }, }, 'loggers': { 'django': { 'handlers': ['console', ], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } Output in console 2022-06-02 10:26:09,714 WARNING /api/v1/<path/ GET 403: user 71 - You do not have permission to perform this action. 2022-06-02 10:26:09,814 WARNING Forbidden: /api/v1/<path/ 2022-06-02 10:26:09,815 WARNING "GET /api/v1/<path/ HTTP/1.1" 403 12495 Any suggestion on how to optimize and have only one entry, preferably my custom logging entry and get rid of the other two? This will also help reduce drastically the size of the logs stored. -
React and django cache issue
I have a react and django app which is being served behind nginx. The /admin route and /api routes both point to uwsgi. However when loading these routes the react app is served unless a hard refresh of the page is peformed. It seems like react is serving all routes instead of just the index. Is there a way to exclude routes in react so it will only display if the path is "/" or is there something in nginx/django config I can change to overcome this issue. This is a snippet from my nginx conf: location / { try_files $uri $uri/ =404; } location /api/ { uwsgi_pass uwsgi; include /etc/nginx/uwsgi_params; } location /admin/ { uwsgi_pass uwsgi; include /etc/nginx/uwsgi_params; } and my django urls config: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(routers.urls)) ] Any ideas on how I could proceed would be appreciated -
Django development static 404 not found: new files only
Curious issue on Django development server. Static files which are in existing use work just fine. When I add new files (of any sort) I get 404 not found. settings.py DEBUG = True INSTALLED_APPS = [ 'django.contrib.staticfiles', ] STATIC_ROOT = os.path.join(BASE_DIR, '') STATIC_URL = '/static/' template <img src="{% static 'media/cypress.jpg' %}"/> <!-- old file works --> <img src="{% static 'media/butterfly.jpg' %}"/> <!-- new file returns 404 --> Jquery files which were in use are found, those which were sat in the same folder unused before aren't. I assume therefore it's an indexing issue of some sort. I've tried python manage.py collectstatic but no joy. Any guidance much appreciated. -
I need to redirect users to a previously typed link after authentication. (I am using Django)
In my App, being authenticated is a must to access the content. Let's say someone shared a link such as http://website.com/form/ioxPwhRtV8zeW2Lj9njZjs4065Ml6u/viewform. If not authenticated, it redirects the user to the main login page. I need to figure out how once authenticated I redirect the same user back to the previously typed link http://website.com/form/ioxPwhRtV8zeW2Lj9njZjs4065Ml6u/viewform. I am using Django version 4.4 for my app. For a reference, here is my code: def login_view(request): """ Display the login form and handle the login action. """ form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) now = datetime.datetime.now() current_time = now.strftime("%I:%M %p, %B %d") msg = f'Success - Logged in at {current_time}' messages.success(request, msg) # Look over here. It redirects not to the location typed, but the home page. I want it to redirect any authenticated user to the previously typed URL. return redirect("/") else: msg = 'Invalid credentials' messages.error(request, 'Error validating the form') else: msg = 'Error validating the form' messages.error(request, 'Error validating the form') return render(request, "accounts/login.html", {"form": form, "msg": msg}) Mates, I need help fast. -
django models hierarchy question: related attributes of a ManyToManyField
As a fresh coder, I seriously have problems to build my models relations. Please check these two cases, How can I set current_reading_pages on my Scenario2? from django.db import models # Scenario1: Users can record their reading progress of a book. class Book(models.Model): name = models.CharField(max_length=128) class User(models.Model): current_reading_book = models.ForeignKey('Book', on_delete=models.CASCADE) current_reading_page = models.IntegerField() Result1: No problems about database, but Users can records their progress of only one book. Other scenario, which I want to build: from django.db import models # Scenario2: Users can record their reading progress of multiple books. class Book(models.Model): name = models.CharField(max_length=128) class User(models.Model): current_reading_books = models.ManyToManyField('Book') # current_reading_pages = ??? I want to save all progress of current books, for example, User A is reading 3 books, book1 till page 100, book2 till page 10, book3 till page 0. -
Adding a comment through page instead of /admin - django
I am able to add comments to a page through the /admin panel and I would like to be able to do so through a buttom.. I've created an HTML page and added a some functionality for it forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('commenter_name', 'comment_body') widgets = { 'commenter_name': forms.TextInput(attrs={'class': 'form-control'}), 'comment_body': forms.Textarea(attrs={'class': 'form-control'}), } views.py @login_required(login_url='/accounts/login') def add_comment(request, slug): movie = Movie.objects.get(slug=slug) form = CommentForm() context = {'form': form} return render(request, 'add_comment.html', context) add_comment.html <form action="add_comment.html" method="post"> <textarea name="comment" id="comment" rows="10" tabindex="4" required="required"></textarea> <a href="{% url 'movies:add_comment' movie.slug %}" class="myButton">Submit</a> urls.py path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'), path('<slug:slug>/add-comment/', views.add_comment, name='add_comment'), models.py class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') banner = models.ImageField(upload_to='movies_banner', blank=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() created = models.DateTimeField(blank=True, default=timezone.now) slug = models.SlugField(blank=True, null=True) class Comment(models.Model): movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE) commenter_name = models.ForeignKey(User, default=None, on_delete=models.CASCADE) comment_body = models.TextField() date_added = models.DateTimeField(auto_now=True) def __str__(self): return '%s - %s' % (self.movie.title, self.commenter_name) I've confirmed the URL works and the html webpage add_comment is shown.. my goal is to allow the user to comment - … -
Ngrok "HTTP Error 404". The requested resource is not found
Error picture I've tried to execute my django-app with "ngrok". Added url to "ALLOWED_HOSTS" and other variables which need that. I did 'py manage.py runserver' and 'ngrok http 80' together => no result. -
Django model inheritance with proxy classes
I've got proxy classes which have been created mainly to implement custom filtering, but there are some other fairly small custom methods as well, and they will be expanded to provide other custom logic as well. So say I have models: class Videos(models.Model): title = models.CharField(max_length=200) publisher = models.Charfield(max_length=100) release_date = models.DateField() class Superheroes(Videos): objects = SuperheroesManager() class Meta: proxy = True class Recent(Videos): objects = RecentManager() class Meta: proxy = True and model managers: class SuperheroesManager(): def get_queryset(self): return super().get_queryset().filter(publisher__in=['Marvel','DC']) class RecentManager(): def get_queryset(self): return super().get_queryset().filter(release_date__gte='2020-01-01') On the front end a user may pick a category which corresponds to one of the proxy classes. What would be the best way to maintain a mapping between the category which is passed to the view and the associated proxy class? Currently I have an implicit dependency whereby the category name supplied by the front end must be the same as the proxy class name, allowing for a standard interface in the view: def index(request, report_picked) category = getattr(sys.modules[__name__], report_picked) videos = category.objects.all() I'd like to move away from this implicit dependency, but not sure what the best way would be. I wouldn't want to maintain a dictionary and can't use a … -
How to get Id from CreateView in django
Hello all I need some help getting the id from an object in django I have a createView where I want to send an notification for the user when a new object is created, and I need the object Id... def form_valid(self, form): # setting fields that are not open to user form.instance.created_by = self.request.user form.instance.status = 'open' messages.success(self.request, 'Ticket Created Successfully!') Notification.objects.create( created_by=self.request.user, created_for=form.instance.responsible, title=f"New ticket from {self.request.user.first_name} {self.request.user.last_name} =====> {form.instance.id}", message=f"Hello",) return super().form_valid(form) The problem is that {form.instance.id} is always none. Anyone can help me with that? Thanks in advance -
Why do my javascript integration in a django template does not work?
I am really new to django and i am trying to build a small page where a chart with chart.js is shown. I want to load the javascript file static. I created a basic html-file called data_table.html and added a folder static where three files are in: data_table.js, styles.css and a picture bild.jpg. The html file is: {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static 'styles.css' %}" type="text/css"> <script type="text/javascript" src="{% static 'data_table.js' %}"></script> <title>Data viewer</title> </head> <body> <canvas id="myChart" width="200" height="200"></canvas> <script> </script> <p class="text">Picture:</p> <br> <img class="img" src="{% static 'bild.jpg' %}" alt="My image"> </body> </html> The css file and the picture are loaded. The picture is displayed and with the css file i can resize the picture. So that works i guess? The javascripts file looks as follows: const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for d in data%}'{{d.label}}',{%endfor%}], datasets: [{ label: '# of Votes', data: [{% for d in data%}{{d.data}},{%endfor%}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, … -
Django export model to csv for ManyToManyField
Have a few tables for which I successfully built export to CSV, based on the Models. However, for one where I count the 'likes' for the news (posts) I'm getting nowhere. Here is my model: class News(models.Model): news_title = models.CharField(max_length=300) news_text = models.TextField(max_length=2000) news_author = models.CharField(max_length=150) news_date = models.DateField(default=now) likes = models.ManyToManyField(User, related_name='user_like', blank=True) @property def total_likes(self): return self.likes.count() Problem is, that I can print out to CSV all items from the model, but if I print "likes" I get duplicated (or more) rows in CSV. The reason is, that if News is liked by 3 users, I get 3x rows on CSV for each User and under "Like Count" column I get their IDs. What I would like to get instead is: 1x row per News with a total of likes for each news. and view.py @login_required def export_news(request): newss = News.objects.all() response = HttpResponse(content_type='txt/csv') writer = csv.writer(response) writer.writerow(["ID","Title","Author","Date","Text","Likes Count"]) for news in newss.values_list('id','news_title','news_author','news_date','news_text','likes'): writer.writerow(news) response['Content-Disposition'] = 'attachment; filename="News_list.csv"' return response Appreciate any help. Thx -
How to get current value from django table
I am only getting the last value from my django table after clicking the delete button. html file - <body> <div class="for-body"> <!-- test table --> <form method="POST" action=""> {% csrf_token %} <input id="label" name="engname" value="{{ eng_name }}">{{ eng_name }}</input> <button name="update" class="add-button" type="submit"><b>Update</b></button> <button name="add" class="add-button1" type="submit"><b>Add Existing User</b></button> <tbody class="for-tbody1"> <tr class="for-tr1"> <td class="for-td1"> <dh-components-grid-body-render class="for-dhcomp"> <div class="for-div1"> <table class="for-table1" id="pgnum"> <thead class="for-thead1"> <tr class="for-tr2"> <td class="for-td2"><div class="dh-grid-headers-cell-default">User</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Email</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Role</div></td> <td class="for-td2"><div class="dh-grid-headers-cell-default">Remove</div></td> </tr> </thead> <tbody class="for-tbody2"> <tr class="for-tr3"> {% for i in user_list %} <td class="for-td3"><div class="cell-default-style">{{i.first_name}} {{i.last_name}}</div></td> <td class="for-td3"><div class="cell-default-style"><input type="hidden" value="{{ i.email }}" name="email">{{i.email}}</input></div></td> {% if i.is_superuser == True %} <td class="for-td3"><div class="cell-default-style">Super User</div></td> {% elif i.is_staff == True %} <td class="for-td3"><div class="cell-default-style">Admin</div></td> {% else %} <td class="for-td3"><div class="cell-default-style">Practitioner</div></td> {% endif %} <td class="for-td3"><div class="cell-default-style"><button class="btn" name="delete" type="submit"><img src="/static/assets/images/trash1.png" style="width: 18px;" alt="Delete"></button></div></td> </tr> {% endfor %} </tbody> </table> </div> </dh-components-grid-body-render> </td> </tr> </tbody> </form> </div> </body> views.py - def engagement_admin_edit(request, id): staff = request.user.is_staff a = User.is_authenticated if staff == True: eng_list = Grp.objects.all() eng = Grp.objects.get(id = id) eng_name = eng.gname eng_name = str(eng_name) eng_id = eng.id cursor = connection.cursor() cursor.execute('''SELECT * FROM main_enguser WHERE eid=%s''',[eng_id]) row = cursor.fetchall() users …