Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why isn't Django passing ImageField data via ListView to a template?
This is my first programming project, and first question on StackOverflow - so please be gentle! I've been good and checked all the relevant existing questions and answers - apologies in advance if I've missed it. I have a model that contains images: models.py class Image(models.Model): image = models.ImageField(upload_to='portfolio-images/', blank=False, null=False) uploaded_by = get_user_model() uploaded = models.DateTimeField(auto_now_add=True, editable=False) alt_text = models.CharField(verbose_name='Alternate text', max_length=200, blank=True, null=True) def __str__(self): return self.alt_text def get_absolute_url(self): return reverse('image_detail', args=[str(self.alt_text)]) Which is handled by these views: views.py class ImageDetailView(DetailView): model = Image context_object_name = 'image' template_name = 'image_detail.html' class ImageListView(ListView): model = Image context_object_name = 'images' template_name = 'image_list.html' Now when these are passed to their relevant templates, the DetailView works as it should - passes the url to the template using this code, and the image renders in the browser. image_detail.html ... <img src="{{ image.image.url }}" alt="{{ image.alt_text }}"> ... But the ListView does not pass the url or alt-text into the template. Here's the code I use to call it in the template: image_list.html {% for image in images %} <img src="{{ images.image.url }}" alt="{{ images.alt_text }}"> {% endfor %} Weirdly, it is getting a response from the database, as the loop creates 5 … -
My table is becoming very wide because of a table row item is a long url
I am working with Django and Bootstrap to create this table. {% extends "jsonparser/base.html" %} {% block content %} {% if data %} <h1>{{ data }}</h1> {% else %} <table class="table table-hover"> <thead> <tr> <th scope="col">Property</th> <th scope="col">Actual Value</th> </tr> </thead> <tbody> <tr> {% for list in adobe %} <tr> {% for i in list %} <td>{{i}}</td> {% endfor %} </tr> {% endfor %} </tr> </tbody> </table> {% endif %} {% endblock content %} Right now when I view the output, the table is very long horizontally because of one of the properties I am printing is a very long URL. -
Django : Find 'difference' between two models
Say I have two models as follows - class DID_Definition_Model(models.Model): # DID to Region-Carrier Mapping did_number= models.CharField(max_length=32, validators=[alphanumeric], primary_key=True) class DID_Number_Assignment_Model(models.Model): #DID Number Assignment did_selector = models.ForeignKey(DID_Definition_Model, on_delete=models.CASCADE, primary_key=True, unique=True) I want to report on the 'difference' in entries, (possibly via difference method) which may be available in DID_Definition_Model did_number field but not in DID_Number_Assignment_Model did_selector field. In my failing attempt my thought process was to create a query which will contain all entries of did_number. Then repeat the same procedure to get all entries of did_selector. Finally compare the two queries using difference method. But I kind of got stuck at the first stage - getattr(DID_Definition_Model, did_number) Traceback (most recent call last): File "", line 1, in NameError: name 'did_number' is not defined * But the above is simply not possible as did_number is a valid field of DID_Definition_Model Any guidance will be helpful as I have been through multiple message boards and could not seem to find any way out. -
How to print extracted dictionary values in input fields of html (placeholder)
I am quite new to django and struggling to do something very simple.I am working on django based pdf data extraction project.in this project i am taking invoice pdf from user and then extracting fields like issuer, invoice_number, date, amount, currency, other.and then save those data into database.everything works fine but the only thing is i want to print extracted data in html forms input fields.guys could you please help me this is the flow input invoice.pdf --> extract button --> print values in inputs fields of html form --> submit after pdf extraction i got this dictionary {'issuer': 'Freefiber', 'amount': 29.99, 'date': '02/07/2015', 'invoice_number': '562044387', 'currency': 'EUR', 'other': {'amount_untaxed': 24.99, 'date_due': '02/08/2015', 'vat': 'FR60421938861', 'line_number': 'FO10479674', 'client_id': '10577874', 'desc': 'Invoice from Free'}} expected output here is my code views.py from django.shortcuts import render, redirect, HttpResponse from .models import InvoiceList import os from .forms import browse from .models import handle_uploaded_file from invoice2data import extract_data # Create your views here. def index(request): invoices = InvoiceList.objects.all() context = { 'invoices': invoices, } return (render(request, 'index.html', context)) def create(request): print(request.POST) issuer = request.GET['issuer'] invoice_number = request.GET['invoice_number'] date = request.GET['date'] amount = request.GET['amount'] currency = request.GET['currency'] other = request.GET['other'] invoice_details = InvoiceList(issuer=issuer, invoice_number=invoice_number, date=date,amount=amount,currency=currency,other=other) … -
Django login redirects to login page
During development I was able to login and logout just fine. However in production I am experiencing some headaches. When I login the page just reloads. I have it set to redirect to the home page upon login and all I have needed before was this: urls.py urlpatterns = [ path("", include('main.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), # For /accounts/login page ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) templates/registration/login.html {% extends "base.html" %} {% block content %} <div class="container"> <div class="card"> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success"><i class="fas fa-sign-in-alt"></i> Login</button> <input type="hidden" name="next" value="{{ next }}" /> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> </div> </div> {% endblock content %} -
Django Static Refer To Wrong URL
I am using Django (v. 3.0.5). I am trying to load the image from database (from FileField) When I use <p>{{ post.profile_image.url }}</p> in HTML it returns me a good path (static/user_profile/user_1_default_profile_image.png) but when I put this into the img tag <img src="{{ post.profile_image.url }}" alt="image"> I have an 404 error GET /profile/static/user_profile/user_1_default_profile_image.png HTTP/1.1 404 2598" Template URL: profile/ Of course I used {% load static %} tag above the <img src="{{ post.profile_image.url }}" alt="image"> tag and I also configured the static files STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] PS Sorry for my broken English -
Migration error on github actions with Django
I’m having trouble getting github actions to work with a django app. When I try to run migrations it fails, though if I install it as a new app on my computer the migrations run fine. I’m brand new to github actions so I don’t really know what I’m doing, but I’ve been struggling with this for a bit today and figured I’d ask. Here is my actions file: https://gist.github.com/pjhoberman/8333df201176bfc00e506ed7d8b4977a#file-django-yml-L52 - it’s failing at the highlighted line 52. And the error is cumbersome and in full here: https://gist.github.com/pjhoberman/8a8ebd9838a9901e1c9929c219549f50 But is basically this: psycopg2.errors.UndefinedTable: relation "listings_category" does not exist ...ory"."slug", "listings_category"."parent_id" FROM "listings_... -
Django I18n - issues with translating in Python code
I decided to add an English translation to my Russian language website. I decided to start with translating strings in my Python code. This is how I tried to do it: (project name)/settings.py: MIDDLEWARE = [ # ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', # ... ] # ... LANGUAGE_CODE = 'en' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = [ ('en', 'English'), ('ru', 'Русский'), ] (app name)/views.py: from django.contrib import messages from django.utils.translation import gettext as _ # ... # in a function based view messages.success(request, _("Тема изменена успешно!")) Then, I run: python3 manage.py makemessages --ignore="venv" --ignore="collectedstatic" -l en This creates file in conf/locale/en/LC_MESSAGES called django.po. When I open it, it contains this: # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2020-04-24 21:08+0300\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: front/views.py:29 msgid "Тема изменена успешно!" msgstr "" I change the last msgstr … -
Serving media files in Chunks
I have huge video files (size: 200mb average) stored in my media folder. I fetch those files using os.listdir and then store them in dictionary, with respect to storing filename, date (fetch from file) and time (fetched from file) against each file in the dir '../media/videos/'. Refer to code below: file_names = [os.path.join('../media/videos/',fn) for fn in os.listdir(path) if fn.startswith(example_20_Apr_20)] file_names_final=[] for item in file_names: tmp=item.split("-") file_names_final.append({'file_name':item,'date':"-".join(tmp[-6:-3]),'time':"-".join(tmp[-3:-1])}) print(file_names_final) #for debugging Then i place those files in the template. Refer to code section below: {% for i in files %} <div class="col"> <div class="alert-card clickable-feed-wrapper"> <div class="old-feeds-video-wrapper"> <video class="video-container" preload="auto"> <source src="{{ i.file_name }}#t=0.5" type="video/mp4"> </video> </div> <div class="alert-details"> <span class="h">Location : <span class="d feed-location-info">{{location}}</span></span><br/> <span class="h"><span class="d feed-pilot-info"></span></span> <span class="h">Date : <span class="d feed-time-info">{{i.date}}</span></span><br/> <span class="h">Time (24h): <span class="d feed-time-info">{{i.time}}</span></span> </div> </div> </div> {% endfor %} FYI, im passing file_names_final in context as files The problem that I'm running into is, when I try to stream the files from external network, I just can't load the huge files that may size around 200mb, however i'm able to stream the files that are roughly within the 10mb to 50mb ballpark. This may primarily be due to the internet connectivity, and it is … -
How to upload files in Django without using form
Trying to upload a file without using forms.py, I tried with these codes but it only saves the location into the corresponding model, file is not saved in the media folder and can't able to open it in admin. upload_file.html <form id="" method="post" action="#"> {% csrf_token %} <div class="formin"> <input type="text" name="desc" id="desc" placeholder="Description" /><br> <input type="file" id="myFile" name="filename"> <input type="submit" value="Upload" /> </div> </form> models.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.description views.py def form_upload_view(request): if request.method == "POST": descrip = request.POST.get("desc") file = request.POST['filename'].data print(file) obj = Document(description=descrip, document=file) obj.save() return HttpResponse("<h1>Success</h1>") else: return render(request, "upload/upload_file.html", {}) In the document FileField after the submission of the form the location of file http://127.0.0.1:8000/media/index.jpeg is stored. But this file in local machine is not reflected in media folder. -
Running an external python script when a user does something on a django website
I want to build some sort of django app that can react to a change in an SQL database and handle all activate some external python scripts. I, being a django noob, have no idea to do this but I have few ideas and am looking for some help. My first idea is to have a script simply react to a change in an SQL database. I would just have a script running and check if the size of the database changes. If it does, then it will read the latest entry and do something with that data. My second idea is to simply activate a python script when someone clicks a certain button on the website. I also have no idea how to execute this plan. If any of these ideas are dumb, or there is a better way to do things, please let me know. If these ideas are viable, then please let me know what I can research to make these happen. I have been searching and searching and have been able to either find nothing or not understand what I have found Thanks! -
MySQL query not visualizing on Django HTML page
I'm currently trying to take specific queries of databases and display them on an HTML page. I'm working on the Django framework with mySQL as the DB. I've run the queries successfully in mySQL and the server isn't giving me any errors so I'm lost as where to go next. My views.py file where I have the queries from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from student.models import StudentDetails, CourseDetails from django.db import connection from django.core.paginator import Paginator def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] # Create your views here. @login_required def home(request): cursor = connection.cursor() cursor.execute("SELECT COUNT(*) 'totalstudents' FROM student_studentdetails") cursor.execute("SELECT COUNT(*) 'totalseniors' FROM student_studentdetails WHERE year='Senior' ") cursor.execute("SELECT COUNT(*) 'totaljuniors' FROM student_studentdetails WHERE year='Junior' ") cursor.execute("SELECT COUNT(*) 'totalfreshman' FROM student_studentdetails WHERE year='Freshman' ") cursor.execute("SELECT COUNT(*) 'coursecount' FROM student_coursedetails") cursor.execute("SELECT AVG(GPA) 'averagegpa' FROM student_studentdetails") homedata = dictfetchall(cursor) return render(request, 'student/home.html', {'data' : homedata}) My home.html where they should be loading. The aesthetics of how they are displayed is secondary right now, I'm still trying to figure out how to pull the data without having … -
Django different 'exact Item lookups' multiple times optimizations
I have an table with the attributes (id, email, score, date_added, state, fk, etc.) which is stored into a MySql database. Currently the data will be ingested in an additive manner where the same entry (new id) can be added, but with a more recent date and changed state (to maintain history). I use a single Django endpoint that will accept a single entry to ingest. This endpoint first checks if it is a new email, or already existed by querying model.objects.filter(email__iexact=email).first(). This query is used so that the remaining row data fk, etc. can be copied without reprocessing. Is there a way to optimize and increase the speed of this process/lookup (possibly with Django caching or simple adjustments)? If it's not possible, what are the biggest design limitations that would need to be changed to allow for database query improvements/optimizations. Notes: The table likely to become too large to store as a python dict, I have currently tried wrapping the single entry call with a batch_ingest method that uses an atomic transaction and the entire batch to reduce the write at each call; This seems to help reduce disk usage while processing, but doesn't reduce the lookup time per … -
python django object matching query: i am getting different object id in featured page and not getting the same object in index on click
Template Featured: <div class="container"> <div class="row"> <div class="col-lg-6 mb-5 animate"> <a href="{{ product_object1.image.url }}" class="image-popup"><img src="{{ product_object1.image.url }}" class="img-fluid" alt="Template"></a> </div> <div class="col-lg-6 product-details pl-md-5 animate"> <h3>{{ product_object1.name }}</h3> <div class="rating d-flex"> <p class="text-left mr-4"> <a href="#" class="mr-2">5.0</a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> </p> <p class="text-left mr-4"> <a href="#" class="mr-2" style="color: #000;">100 <span style="color: #bbb;">Rating</span></a> </p> <p class="text-left"> <a href="#" class="mr-2" style="color: #000;">500 <span style="color: #bbb;">Sold</span></a> </p> </div> <span class="status">{{ product_object1.discounted_price }}%</span> <div class="overlay"></div> <p class="price">Price<span class="mr-2 price-dc">(${{ product_object1.price }}/Lb)</span><span class="price-sale">${{ product_object1.afterdiscount }}</span></p> <p>A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Text should turn around and return to its own, safe country. But nothing the copy said could convince her and so it didn’t take long until. </p> <div class="row mt-4"> <div class="col-md-6"> <div class="form-group d-flex"> <div class="select-wrap"> <div class="icon"><span class="ion-ios-arrow-down"></span></div> <select name="" id="" class="form-control"> <option value="">Small</option> <option value="">Medium</option> <option value="">Large</option> <option value="">Extra Large</option> </select> </div> </div> </div> <div class="w-100"></div> <div class="input-group col-md-6 d-flex mb-3"> <span class="input-group-btn mr-2"> <button type="button" class="quantity-left-minus btn" data-type="minus" data-field=""> <i class="ion-ios-remove"></i> </button> … -
Multiple images in a single detailed view
I'm working with a store website in Django, and I'd like to have a product-detail view to show (obviously) the product card with all of its images. The problem is that detail views only focus on one model, and here's what I have: class Bag(models.Model): title = models.CharField(max_length=30) description = models.TextField() previous_price = models.FloatField(null=True, blank=True) actual_price = models.FloatField() slug = models.SlugField() main_image = models.ImageField(upload_to='product_image', blank=True) def get_absolute_url(self): return reverse( 'product_page', kwargs={ 'slug' : self.slug } ) def __str__(self): return self.title class MoreImage(models.Model): Bag = models.ForeignKey(Bag, related_name='image', on_delete=models.CASCADE) image = models.ImageField(upload_to='product_image', blank=True) Any idea on how I can accomplish this? Thanks in advance! -
How to count the number of objects in a given foreign key in django inside the html template?
I have 3 models which are. class Category(models.Model): name = models.CharField(max_length=100) class Subcategory(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Item(models.Model): name = models.CharField(max_length=100) subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE) In my Html template I want to access the number of items in each given category. I have tried using the _set method but it doesn't work on category.subcategory_set.course_set.count. How can I access the number of courses under each given category. I didn't include category as a foreign key in my Items models as it can lead to assignment of wrong category-subcategory pair for an item. -
Aggregation in Django viewset - Django Rest Framework:
I have a table with the following attribute- created_at = TimestampField(auto_now_add=True,auto_now_update=False, editable=False) updated_at = TimestampField(null=True,auto_now_update=True, editable=False) And one service is running there, first comes into the system and we capture created_at timestamp. And after some time on service completion, the script updates the table attributes and we capture updated_at timestamp. So now I want to find the AVERAGE of the service deployment time i.e. addition of (updated_at-created_at) divide by total services or we can say total rows in the table. So that query needs to be implemented in Django ORM and have to serialize to the endpoint. So that data can be fetched in frontend. Could you guys help me out here that would be highly appreciable? Thanks in advance! -
How to get IMSI number via link to my django webapp?
I have a web application accessible via a mobile browser. I need to detect a mobile device IMSI whenever a user clicks on the link in my app page accessible via web browser. The question is how to get unique device id/sim id via web browser for a specific mobile device. Focus of most of the ideas is, what is the kind of access a browser has over the phone and How can control it using python? Via webpage scripts we can store some data locally at client machine and retrieve it later. Is there a way to get a hook to webap app from the webpage and get the id details via scripts in my page? **Let me know if there is any other option without asking user to installing a local app or browser plugin on the device?**olm -
django forms and models by muxamedovr
I have such a situation I have 3 models Profil, Stimul_slov, Otvet, the participant must go to his login and password to the main part of the site there he must answer some questions questions are stored on the model Stimul_slov answers must be saved to the model Otvet I am new to my knowledge solve this problem please tell me how to solve this issue how can I make a form for this task for earlier thanks and forgive me if my level is English models.py from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=100, blank=True) age = models.DateField(blank=True) specialite = models.CharField(max_length=100,blank=True) language = models.CharField(max_length=100,blank=True) def __str__(self): return self.fullname class Stimul_slov(models.Model): stimulus = models.CharField(max_length=200, blank=True) def __str__(self): return "%s" % ( self.stimulus) class Otvet(models.Model): answer = models.CharField(max_length=200, blank=True) user = models.ForeignKey(Profil, on_delete=models.CASCADE) stimul = models.ForeignKey(Stimul_slov, on_delete=models.CASCADE) def __str__(self): return "%s: %s ----> %s" % (self.user ,self.stimul, self.answer) form.py from django import forms from .models import Profil, Otvet from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class ExtendedUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super().save(commit==False) user.email = self.cleaned_data['email'] if commit: user.save() return … -
Geoalchemy2 get mvt tiles from postgis database
I am trying to fetch MVT/geojson vector tiles directly from POSTGIS server using SQLAlchemy ORM but i am unable to find any examples. All the examples shown do not use ORM but instead use raw queries -
Django How to switch between Development, Stageing and Production Environment
I am new to Django. I used python manage.py runserver to run the server and I got: * Serving Flask app "application" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off The server is running production environment with DEBUG OFF. I want to run it in development environment with DEBUG ON. How can I change the running environment? My config file: class Config(object): DEBUG = True TESTING = False CSRF_ENABLED = True SECRET_KEY = 'this-really-needs-to-be-changed' SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True I am wondering how can I switch between defferent environment. -
Obtain the date from datepicker and send it to my backend - Django
I'm using the datepicker from jquery-ui and I need to pass the date to my python backend (I'm working with Django). Obtain the date in my JS it's not a problem, user_date = $("#datepicker").datepicker('getDate'); Then I have a function that pass this result using ajax to my python backend. function getUserDate(user_date){ var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ url: '/../../../getUserData/', type: 'POST', headers:{"X-CSRFToken": csrftoken}, data: { 'Date':user_date }, dataType: "json", cache: true, success: function(response) { var data = response.Data; } }); } But now, when I want to work with it in my python function, I don't know how to do it. I'm doing the following, try1 = request.POST['Date'] print('>>>>>>>>>>>> TRY1 >>>', type(try1)) But this is a string. My question is, how can I receive it as a dictionary, json, timestamp or something similar? That it's more manageable. Thank you very much! -
How to create a file using Celery/Django
I’ve set up a Django project with Celery and Redis(Broker, Backend). I need to bind file generation to the view, the task is marked as successful but file is not created. What am I doing wrong? from celery import shared_task @shared_task def create_task(task_type): f = open("example_file.txt", "a") f.write("Now the file has more content!") f.close() return True -
Django Rest Framework get params inside has_permission
I'm filtering real estates queryset dependent on user status and district (last one with GET param). In views.py I have this: class RealEstateView(APIView): serializer_class = RealEstateSerializer permission_classes = [RealEstatePermission] def get(self, request): district = self.request.query_params.get('pk') if district: serializer = RealEstateSerializer(RealEstate.objects.filter(owner_id=district), many=True) else: serializer = RealEstateSerializer(RealEstate.objects.all(), many=True) return Response(serializer.data) If user is superuser, he have access to all information. If user in not superuser, he can get access only to real estates from district which he is responsible. If user is responsible to district with id=1, but sends a get param with id=2, I need to raise an exception. But the problem is I don't know how to get access to get parameter in has_permission function. Doing this inside views get function seems not good idea. I already tried request.resolver_match.kwargs.get('id') and view.kwargs.get('id'), both of them are empty. in permissions.py: class RealEstatePermission(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: if request.user.is_staff: return True ## HERE I need something like request.user.district.id == kwargs('id') if request.user.role == 'district_municipality': return True Thank you for your help. -
How to join 2 attributes to create a name in Django model instance?
I have a model: class Subject(models.Model): level = models.CharField(choices=LEVEL_CHOICES, max_length=2) subject_name = models.CharField(max_length=50) teacher_name = models.ForeignKey(Teacher, on_delete=models.CASCADE) total_seats = models.IntegerField() subject_details = models.CharField(max_length=100) subject_img = models.ImageField() I want to display each instance as level and then subject name. For example, if the instance has a level 'Advanced' and subject_name as 'Physics', I want the instance to be displayed as 'Advanced Physics'. I have tried using str method but it shows subject_name is not defined: def __str__(self): return self.level+ ''+ subject_name