Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to perform query in Django
I need to filter the a particular user's bar in whcih reservations were made. I am a beginner in Django and have tried some methods which unfortunately didn't work. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) class Bar(models.Model): user_id = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class Tables(models.Model): table_no = models.CharField(max_length=14, unique=False) bar = models.ForeignKey(to=Bar, on_delete=models.CASCADE) def __str__(self): return self.table_no class Reservation(models.Model): first_name = models.CharField(max_length=200) table = models.ForeignKey(Tables, on_delete=models.CASCADE) def __str__(self): return self.first_name Note: I wan to filter the reservations made in a particular user's bar -
TemplateSyntaxError at 'bootstrap4' is not a registered tag library. Must be one of: bootstrap is installed and in INSTALED_APPS
I am trying to use bootstrap_datepicker_plus and to do that I need bootstrap4. I have installed it. when I run pipenv run pip freeze, I see: django-bootstrap==0.2.4 django-bootstrap-datepicker-plus==3.0.5 django-bootstrap4==2.3.1 django-compressor==2.4 django-jquery==3.1.0 and I have in settings.py: INSTALLED_APPS = [ "bootstrap4", "bootstrap_datepicker_plus", But I still see TemplateSyntaxError at /myapp/ 'bootstrap4' is not a registered tag library. Must be one of: when I include {% load bootstrap4 %} in my template. Does anyone have an idea of why the tag is not registered? I have restarted the server. -
Django Model Form is_valid returning False always
I am new to django, my is_valid() doesn't seem to work here, my code: forms.py: class ImageForm(ModelForm): class Meta: model = Image exclude = ['album'] models.py class Image(models.Model): image = models.ImageField(upload_to=save_path) default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) def __str__(self): return self.image views.py if request.method == 'POST': form = ImageForm(request.POST) if form.is_valid(): print('form.is_valid working') return render(request, "auctions/index.html") -
Checking for duplicate email address causing Bad Request error
I have a form for creating new users and I've added clean_email function for checking if the email address already exists like this: class NewUserForm(ModelForm): class Meta: model = Student fields = __all__ def clean_email(self): email = self.cleaned_data.get('email') try: match = User.objects.get(email = email) except User.DoesNotExist: return email raise forms.ValidationError('User with this email address already exists.') Unfortunately, after I try to test this by attempting to register a user with an email address that already exists I get the This page isn't working error in my browser. I'm not sure why this is happening, can anyone help? -
Retrieve instance DRF
I am trying to retrieve an instance that does not exist. Whenever I send GET by postman it returns "detail": "Not found." And whenever an instance does not exist I want it to be created, but can't set up proper condition. What should I type instead of None, or how can I improve this code to work in a proper way. def retrieve(self, request, *args, **kwargs): instance = self.get_object() if instance == None: instance = Cart.objects.create(owner=self.request.user) serializer = self.get_serializer(instance) return Response(serializer.data) -
How to filter a type of user in Django
I am working a particular web application. I have made use of the Django Abstract user has my application has different types of user. I have the admin user as well as the bar owner. I need to be able to return the number of bar owners in the application but don't know how to go about it. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_landlord = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) Note: I need to be able to return the number of is_landlord -
Django rest framework - set default serializer for a class
In my code, I have a few models with multiple custom properties: @dataclass class Value: amount: float currency: str class MyModel(models.Model): ... @property def v1(self) -> Value: ... @property def v2(self) -> Value: ... @property def v3(self) -> Value: ... An I have the following serializer: class MyModelBaseSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = [..., "v1", "v2", "v3"] When serializing any MyModel instance, a TypeError raises: TypeError: Object of type Value is not JSON serializable. I know this can be solved by explicitly adding v1, v2, v3 as fields inside MyModelBaseSerializer, but I don't want to do that: I have many models with Value properties. I want the default DRF serializer to know how to serialize Value instances. I tried overriding to_representation, but that didn't seem to work. I want something similar to overriding the JSONEncoder.default(o) method, but I don't see how to tell DRF which encoder to use. -
When want to acces forms: ModelForm has no model class specified
I have a mistake but I don't understand the reason. I everytime use this method. But now not working. I try old way its working but then lot of code working. How I can pass this error? Why I have these error? Can you tell me about this? error typye: ModelForm has no model class specified. Models.py; from django.db import models from django.db.models.base import Model # Create your models here. class Personel(models.Model): KullaniciAdi=models.CharField( max_length=8, verbose_name="Kullanıcı Adı", null=False, blank=False, unique=True, error_messages={ "unique":"Böyle Bir Kullanıcı Mevcut.", "null":"Kullanıcı Adı Boş Bırakılmaz", "blank":"Kullanıcı Adı Boş Bırakılmaz", "max_lenght":"Kullanıcı Adı 8 Karekteri Geçmemeli" } ) Parola=models.CharField( max_length=18, verbose_name="Parola", null=False, blank=False, error_messages={ "max_lenght" : "Parolanız Çok Uzun", "null":"Parola Boş Bırakılmaz", "blank":"Parola Boş Bırakılmaz" } ) IsimSoyisim= models.CharField( max_length=30, verbose_name="İsim Soyisim", null=False, blank=False, error_messages={ "null":"İsim Boş Bırakılmaz", "blank":"İsim Boş Bırakılmaz", "max_lenght":"Girilen İsim Çok Uzun" } ) Email = models.EmailField( max_length=50, null=True, verbose_name="E-Mail", blank=True, unique=True, error_messages={ "max_lenght":"Mail Adresi Çok Uzun", "unique" : "E-Posta Adresi Kayıtlı" } ) Telefon = models.EmailField( max_length=11, verbose_name="Telefon", null=True, blank=True, unique=True, error_messages={ "max_length" : "Numara Çok Uzun", "unique":"Numara Kayıtlı" } ) MagazaID=models.ForeignKey( "auth.User", on_delete=models.CASCADE, verbose_name="Firma Adı" ) MagazaYoneticisi=models.BooleanField( verbose_name="Mağaza Yöneticisi", null=True ) TeknikServis=models.BooleanField( verbose_name="Teknik Servis", null=True ) HesapOlusturmaTarihi=models.DateTimeField( auto_now_add=True, verbose_name="Oluşturulma Tarihi" ) HesapGuncellenmeTarihi=models.DateTimeField( auto_now_add=True, verbose_name="Güncellenme … -
How to create a seperate file for Sitemap?
I am trying to craete sitemaop in my website, but I craeted seperate sitemap for eact App, Please let me know how I can merge all sitemap urls in a single sitemap.xml file... Here is my urls.py file... from django.contrib.sitemaps.views import sitemap sitemapblog = { 'blog': BlogSitemap, } sitemapproject = { 'project':ProjectListSitemap } sitemaplocation = { 'location':LocationListSitemap } sitemaplocality = { 'locality':LocalityListSitemap } urlpatterns = [ path('sitemap/sitemapblog.xml', sitemap, {'sitemaps': sitemapblog}), path('sitemap/sitemapproject.xml', sitemap, {'sitemaps': sitemapproject}), path('sitemap/sitemaplocation.xml', sitemap, {'sitemaps': sitemaplocation}), path('sitemap/sitemaplocality.xml', sitemap, {'sitemaps': sitemaplocality}), ] and here is my sitemap.py file... class BlogSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Blog.objects.all() def lastmod(self, obj): return obj.updated_at def location(self, item): return reverse('page:blogsingle', args=[item.slug]) class LocationListSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Location.objects.all() def lastmod(self, obj): return obj.updated_at def location(self, item): return reverse('page:locationproject', args=[item.slug]) class LocalityListSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Locality.objects.all() def lastmod(self, obj): return obj.updated_at def location(self, item): return reverse('page:localityproject', args=[item.slug]) class ProjectListSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Project.objects.all() def lastmod(self, obj): return obj.updated_at def location(self, item): return reverse('page:projectview', args=[item.slug]) Now my current website url is this 127.0.0.1:8000/sitemap/sitemapblog.xml, and same url for other sitemap, but I want these all … -
How to see data in json form from a 3rd party website after inserting data in a html form using django framework?
Suppose , owner will give you a 3rd party website link. you're given a task where you'll create a simple html form and submit your personal info. Then fetch data and see it in json form using python django rest framework. No need to create model for your project since you're using 3rd party's database. Need views.py ,serializers.py,urls.py file. Suppose given url link: https://jobs.xyz.com/api/v1/recruiting-entities/ here's my html code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags--> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Colorlib Templates"> <meta name="author" content="Colorlib"> <meta name="keywords" content="Colorlib Templates"> <!-- Title Page--> <title>Job Application Form</title> <!-- Icons font CSS--> <link href="{% static 'vendor/mdi-font/css/material-design-iconic-font.min.css' %}" rel="stylesheet" media="all"> <link href="{% static 'vendor/font-awesome-4.7/css/font-awesome.min.css' %}" rel="stylesheet" media="all"> <!-- Font special for pages--> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet"> <!-- Vendor CSS--> <link href="{% static 'vendor/select2/select2.min.css' %}" rel="stylesheet" media="all"> <link href="{% static 'vendor/datepicker/daterangepicker.css' %}" rel="stylesheet" media="all"> <!-- Main CSS--> <link href="{% static 'css/main.css' %}" rel="stylesheet" media="all"> </head> <body> <div class="page-wrapper bg-gra-03 p-t-45 p-b-50"> <div class="wrapper wrapper--w790"> <div class="card card-5"> <div class="card-heading"> <h2 class="title">Job Application Form</h2> </div> <div class="card-body"> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="name">Name</div> <div class="value"> <div class="input-group"> <input class="input--style-5" type="text" name="name" value="{{ name }}" … -
Cke editor youtube embend
I am currently working on a blog and I'm using CKE editor to create articles. I've also downloaded external plugins like codesnipped or youtube. However, I'm experiencing some troubles with the last one, because it doesn't appear in the toolbar as you can see in this image: Here's the code for the CKE EDITOR: CKEDITOR_CONFIGS = { 'default': {'toolbar': 'Custom', 'toolbar_Custom': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'youtube','Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ['CodeSnippet',] , ], 'extraPlugins': ','.join(['codesnippet','youtube']), } } And the models.py in case you need it: lass Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = RichTextUploadingField() author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) -
Development of Django project, code exception, automatically locate the exception to the code segment after the project is overloaded
Question: This is the case, I use VsCode to develop Django projects, I haven't finished writing a piece of code, but due to my operating habits, I will often ctrl + s, or the automatic save function provided by Vscode will save my code. At this time, the running Django project will be automatically reloaded, and because my code is not finished, reloading Django will definitely throw an exception, and Vscode will automatically locate the page where I wrote the code at this time. Where is the code segment where the exception occurs. Originally, I was happily writing code, and suddenly the page jumped to another location, which was terrible and greatly affected my development. I just switched from pycharm to vscode. This problem has affected me for several days. If it can’t be solved, I can’t use vscode to develop happily. I hope that vscode will not help me locate in my editing interface, it is enough to throw an exception in the terminal below. Friends who know the solution, please feel free to enlighten me~~~ Thank you My troubleshooting process: I tried my best to find the various settings of vscode, but I couldn't find the corresponding configuration … -
fake.date_between return always the same date in a loop
I try to implement an algo to create Django objects with random date over the last 2 years I use Faker and it work when I use it in a python shell: each time I call fake.date_between(start_date='today', end_date='+2y') it retunr a new datetime object but I want to do the same in django data migration but don't nderstand why it always return the same value for order in range(0,total_orders + 1): Orders.objects.create( table = random.sample(tables,k=1)[0], customers = random.randrange(1,6), split_bill = random.randrange(1,3), delivered = True, paid = True, created_at = fake.date_between(start_date='today', end_date='+2y') ) save 2020-12-16 17:57:04.203858+01 in postgresql database -
Problem with save method overriding attribute value
I have a model called 'Trip' with a Foreign Key to 'Destination'. The Destination model specifies a maximum number of passengers in it's 'max_passengers' attribute. Trip class Trip(models.Model): destination = models.ForeignKey( Destination, null=True, blank=False, on_delete=models.SET_NULL, related_name="trips", ) date = models.DateTimeField() seats_available = models.IntegerField( null=False, blank=False, editable=False ) trip_ref = models.CharField( max_length=32, null=True, editable=True, blank=True ) Destination class Destination(Product): max_passengers = models.IntegerField(null=True, blank=True) duration = models.CharField(max_length=20, blank=True) addons = models.ManyToManyField(AddOn) min_medical_threshold = models.IntegerField( default=0, null=False, blank=False ) def __str__(self): return self.name Back in the Trip model, I am overriding the model save method, so that when a trip object is created, the 'seats_available' for that instance is set to the 'max_passengers' of the related destination: def save(self, *args, **kwargs): if not self.trip_ref: date = (self.date).strftime("%m%d-%y") self.trip_ref = self.destination.pk + "-" + date if not self.seats_available: self.seats_available = self.destination.max_passengers super().save(*args, **kwargs) I have additional models for Bookings and Passengers. When a booking is created, a post_save signal is sent, calling the model method on my Trips model, def update_seats_avaialable(): def update_seats_available(self): reservations = ( self.bookings.aggregate(num_passengers=Count("passengers")) ["num_passengers"] ) self.seats_available = self.destination.max_passengers - reservations self.save() <---- PROBLEM THe problem is when all seats are finally taken ie. the passenger count = max_passengers and seats … -
Django queryset Product table and Product images table
I am developing an ecommerce website with Django. I had Product and Product_images models as below: class Product(models.Model): tags = models.ManyToManyField(Tag, related_name='products') same_product = models.ManyToManyField('self', related_name='same_products', blank=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='product_categories') who_like = models.ManyToManyField(User, related_name='liked_products', blank=True) title = models.CharField('Title', max_length=100, db_index=True) slug = models.SlugField('Slug', max_length=110, unique = True) sku = models.CharField('SKU', max_length=50, db_index=True) description = models.TextField('Description', null=True, blank=True) sale_count = models.IntegerField('Sale Count', default=0) is_new = models.BooleanField('is_new', default=True) is_featured = models.BooleanField('is_featured', default=False) is_discount = models.BooleanField('is_discount', default=False) price = models.DecimalField('Price', max_digits=7, decimal_places=2) discount_value = models.IntegerField('Discount Value', null=True, blank=True) def __str__(self): return self.title class Product_images(models.Model): # product-un butun sekilleri burda saxlanacaq # is_main true olan esas shekildi # is_second_main olan shekil coxlu product sehifesinde hover edende gelen sekildi # relations product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') # informations image = models.ImageField('Image', upload_to='media/product_images') is_main = models.BooleanField('Main Image', default=False) is_second_main = models.BooleanField('Second Main Image', default=False) # moderations status = models.BooleanField('Status', default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'image' verbose_name = 'Image' verbose_name_plural = 'Images' ordering = ('created_at',) def __str__(self): return f'{self.image}' In my Product_images I store several images for one Product, in Product_images model I wrote boolean fields with names is_main and is_second_main. In my template I want to get these … -
Getting 'undefined' when accessing existing field in django admin change_form.html from custom js
I am trying to learn how to work with custom js in django admin pages. admin.py: class TestAdmin(nested_admin.nested.NestedModelAdmin, tabbed_admin.TabbedModelAdmin): class Media: js = ("admin/js/vendor/jquery/jquery.js", "admin/js/jquery.init.js", "js/testChangeForm.js") tab_overview = ( (None, { 'fields': ('name', 'domain', 'visible') }), QuestionAdminInline ) tabs = [ ('Test content', tab_overview), ] testChangeForm.js: window.addEventListener("load", function () { if (!$) { $ = django.jQuery; } console.log($("#domain").val()) }); change_form.html from django admin contains select/option element with name="domain", but when I try to access it, it gives me undifined. I tried various suggested things, but I still can't get it to work. -
Django Models How To Upload Multiple Files For One Field
I'm looking to upload multiple images from my front-end form (VueJS) to my 'photos' field. However, even with my foreign key, I can only link one image at a time. (I tried ArrayField too, but didn't work) I know with Django forms.Form there's a widget option for 'attr multiple = True', but I can't seem to find a solution for models. class Photos(models.Model): photos = models.ImageField(upload_to='uploads/', null=True, default="") class Actors(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default="") Writing_Samples = models.FileField(upload_to='uploads/', null=True, default="no samples") photos = ForeignKey( Photos, on_delete=models.CASCADE, default="", null=True) gallery = ArrayField( models.CharField(max_length=100), blank=True, default="") Thanks for your time! -
How to login in Django Rest Auth using username or email
In my django project, I am using django rest auth for api authentication. The default is to use username and password for login. I can also use email and password. But I want my user to have the option of either using email or username and password for login authentication; which I believe is more user friendly. How do I do this in django rest auth? -
django.db.utils.OperationalError no such table
Good evening, I am wondering what may the cause of a 'no such table' error in django. I have three databases defined in settings: a 'default' sqlite3 one and two postgresql ones. Out of my models defined in models.py, only one is specifically routed to 'default'. The other models have no routing settings set since they are meant to exist in all postgresql databases, just with different data. I write Model.objects.using(DBname) everywhere to make the DB access explicit. Migrations to all three of my databases were initially successful and, based on DB Browser and phAdmin, they all have the correct fields and data. In the 'context' variable sent to each rendered template, I send only the queryset after Model.objects.using(DBname), but within the template Django cannot see the tables. What could be the reason for django not being able to see them? What I think may be happening is that because the 'table not found' relates to a ForeignKey field of one of my models (a through table), Django is attempting to look for that model in the 'default' database instead of the database chosen during .using(). Does anyone possibly have any experience with anything like this? -
How make fucntional for create form?
I need to create functional to create forms: Create name of form (Generator) Create steps of form Create fields for steps Then I need to use this forms on this site. How can i do this? from django.db import models from enum import Enum class Generator(models.Model): name = models.CharField(max_length=255, verbose_name='Название') cost = models.DecimalField(max_digits=7, decimal_places=2, null=True) class Step(models.Model): generator = models.ForeignKey(Generator, on_delete=models.CASCADE, related_name='steps', verbose_name='Генератор') name = models.CharField(max_length=255, verbose_name='Название') class FieldChoices(Enum): text = 'text' email = 'email' tel = 'tel' url = 'url' password = 'password' number = 'number' search = 'search' date = 'date' time = 'time' range = 'range' radio = 'radio' checkbox = 'checkbox' color = 'color' file = 'file' hidden = 'hidden' class Field(models.Model): step = models.ForeignKey(Step, on_delete=models.CASCADE, related_name='fields', verbose_name='Шаг') name = models.CharField(max_length=255, verbose_name='Название') type = models.CharField(max_length=255, choices=((choice.name, choice.value) for choice in FieldChoices)) -
a raw query set is not retrieving data from the backend
views.py imports.html Here it gives an error I checked it part by part - its not retrieving the data to c_id and t_id from the database. Please suggest me solution to this Thank you. -
Errno 13 Permission denied, when trying to save an image
I have hosted my python + django project on pythonanywhere.com and I have encountered a problem, when I want to save an item with an image. All other fields of item are saving, but the image isnt. Here's the whole error: PermissionError at /admin/core/bike/add/ [Errno 13] Permission denied: '/home/omega/resizedComm/media_root/bikes/xx.png' My settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') What can be causing this error? -
Django Rest Framework AttributeError: Got AttributeError when attempting to get a value for field
I have been trying to add attributes to the UserProfile by creating a OneToOneField to User and adding different fields. Now I run this and call the api with the body below. The api is able to successfully get parsed. A user gets created in the user table and user profile table with the correct attributes. However, Django returns an error AttributeError: Got AttributeError when attempting to get a value for field first_name on serializer UserProfileSerializer. This makes sense since the model does not have these attributes, but what is the correct way to pass the json in the same manner and create the user in the User Table and UserProfile Table? { "first_name": "Jay", "last_name" : "Patel", "email": "tes1t@email.com", "password": "password", "tier": "Gold", "bkms_id": "12234" } model.py # Create your models here. class UserProfile(models.Model): MedalType: List[Tuple[str, str]] = [('Bronze', 'Bronze'), ('Silver', 'Silver'), ('Gold', 'Gold')] bkms_id = models.PositiveIntegerField() tier = models.CharField(choices=MedalType, max_length=100) user = models.OneToOneField(to=User, on_delete=models.CASCADE) def __str__(self): return self.user.username serializer.py from typing import Dict from django.contrib.auth.models import User from rest_framework import serializers from authentication.models import UserProfile class UserProfileSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=65, min_length=8, write_only=True, required=True, style={'input_type': 'password'}) email = serializers.EmailField(max_length=255, min_length=4, required=True) first_name = serializers.CharField(max_length=255, min_length=2, required=True) last_name = serializers.CharField(max_length=255, … -
How to Solve price error in Django when I am displaying Data in my template?
I am trying to convert price in Lac and crore in India currency, suppose value is store in minprice' in this format (10000000), then it will display on my homepage in this format (1 cr), but I am getting this error ('>=' not supported between instances of 'NoneType' and 'int' `) in my website whenever I open any project. This issue with some projects. Please let me know how I can Solve this issue. I am stuck in this from last 5 Hours. Here is my models.py file... class Project(models.Model): name=models.CharField(null=True, max_length=114, help_text=f"Type: string, Values: Enter Project Name.") slug=models.SlugField(null=True, unique=True, max_length=114, help_text=f"Type: string, Values: Enter Project Slug.") here is my related model name, project has OneToOne relation with details... class Detail(models.Model): project = models.OneToOneField(Project, related_name='project_details', on_delete=models.CASCADE) minprice = models.IntegerField(null=True, blank=True, verbose_name="Minimum Price", help_text=f"Type: Int, Values: Enter Minimum Price") maxprice = models.IntegerField(null=True, blank=True, verbose_name='Maximum Price', help_text=f"Type: Int, Values: Enter Maximum Price") @property def min_price_tag(self): if self.minprice >=1000 and self.minprice <=99999: self.minprice=self.minprice//1000 return f"{self.minprice} K" elif self.minprice>=100000 and self.minprice<=9999999: self.minprice=self.minprice//100000 return f"{self.minprice} Lac" else: self.minprice=self.minprice/10000000 return f'{self.minprice} Cr' return str(self.minprice) if self.minprice is not None else "" @property def max_price_tag(self): if self.maxprice >=1000 and self.maxprice <=99999: self.maxprice=self.maxprice//1000 return f"{self.maxprice} K" elif self.maxprice>=100000 … -
Issue with Django recognizing URL passed parameter
I am learning Django and am having an issue with some simple testing and passing URL parameters. Here is my urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('custnames', views.custnames, name='custnames'), path('custdetail/<int:cust_id>/', views.cust_detail, name='cust_detail'), ] And here is my views.py def cust_detail(request, cust_id): return HttpResponse('<p>Cust Detail View with cust_id {cust_id}</p>') When I put this for my URL in my browser: http://localhost:8000/custdetail/1/ My output is: Cust Detail View with cust_id {cust_id} The "home" and "custnames" sections seem to work fine. Any ideas on what I'm doing wrong here? ~Ed