Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can not migrate model after create function for rename file
I create rename function for rename file in model with this code. def path_and_rename(path): def path_and_rename_func(instance, filename): upload_to = path ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(upload_to, filename) return path_and_rename_func I use the function like this. image=models.ImageField(upload_to=path_and_rename("test_image")) video=models.FileField(upload_to=path_and_rename("test_file"),blank=True, null=True) when I use command for migration python manage.py makemigrations It show error like this. ValueError: Could not find function path_and_rename_func in Test.models. How to fix it? -
Django RF, error validating objects owner (error: Field 'id' expected a number but got .AnonymousUser )
I have a object created by a user, When other users try to access the object, it should not allow it. After logging out, when anonymous user try to access the object Django throw error as mentioned below. ERROR TypeError at /PoUserTracking/ Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x0445F160>. VIEWS.PY class PoUserTracking(generics.ListAPIView): serializer_class = NewPoSerializer permission_classes = [IsAuthor] def get_queryset(self): user = self.request.user return Po.objects.filter(user=user) PERMISSIONS.PY class IsAuthor(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.author == request.user -
Django-taggit: validate what a user inputs
django-taggit==1.2.0 Django==3.0.8 class TagMixin(models.Model): tags = TaggableManager(verbose_name="Tags") # django-taggit class Meta: abstract = True class Post(TagMixin, models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name="Category") def is_featured(self): return SPECIAL_TAGS.FEATURED.value in self.tags.names() def is_news(self): return self.category.slug == SPECIAL_CATEGORIES.NEWS.value def _validate_featured(self): if not self.is_news() and self.is_featured(): raise ValidationError("Featured can be in News only.") Problem In the admin site there is Tags field visible. But really it is not a field. It is a manager. Therefore my validator doesn't work properly: it doesn't validate tags the field in the admin site. What is_featured() does is extracting tag names from the database. Could you help me validate what tags are input by a user. -
Django ModelSelect2MultipleWidget for ManyToMany field
I have defined in my model a service which uses one or more articles. Therefore, i use a manytomany relationship. This is my model.py class Artikel(models.Model): id = models.AutoField(unique=True, primary_key=True) artikel_typ = models.IntegerField(unique=False, default=0) bezeichnung = models.TextField(max_length=50) menge = models.FloatField(blank=True, null=True) preis = models.FloatField(blank=True, null=True) einheit = models.TextField(blank=True, null=True) def __str__(self): return self.bezeichnung class Leistung(models.Model): id = models.TextField(unique=True,primary_key=True) bezeichnung = models.TextField() dauer = models.FloatField(blank=True, null=True) # This field type is a guess. preis = models.FloatField() # This field type is a guess. artikel = models.ManyToManyField(Artikel,null=True, unique=False) def __str__(self): return self.bezeichnung class Meta: db_table = 'leistung' I defined the form where i add a new service as follows: class AddNewServiceForm(forms.ModelForm): class Meta: artikel_dd = Artikel.objects.all() model = Leistung fields = '__all__' widgets = {'id':forms.TextInput(attrs={'id': 'id', 'name': 'id', 'type': 'text', 'class': 'form-control', 'data-val-required': 'Bitte tragen Sie eine 4MyHealth ID ein!', 'aria-required': 'true', 'aria-invalid': 'false', }), 'bezeichnung': forms.TextInput( attrs={'id': 'bezeichnung', 'name': 'bezeichnung', 'type': 'text', 'class': 'form-control', 'data-val-required': 'Bitte tragen Sie eine Bezeichnung ein!', 'aria-required': 'true', 'aria-invalid': 'false', }), 'dauer': forms.TextInput( attrs={'id': 'dauer', 'name': 'dauer', 'type': 'number', 'step': '0.01', 'class': 'form-control', 'data-val-required': 'Bitte tragen Sie die Dauer ein!', 'aria-required': 'true', 'aria-invalid': 'false', }), 'preis': forms.TextInput( attrs={'id': 'preis', 'name': 'preis', 'type': 'number', 'step': '0.01', 'class': … -
django-pytest is not using configs mentioned in pytest.ini
I am using pytest-django for the unit test cases for my django app. I have created pytest.ini in the root directory (same level as manage.py) with the following configs: [pytest] DJANGO_SETTINGS_MDOULE = mysite.settings python_files = tests.py test_*.py *_tests.py addopts = --reuse-db Whenever I run command pytest in my root directory, it is giving me the following error: ImportError while loading conftest '/Users/aakash/Desktop/experiments/repos/organonconnect/conftest.py'. conftest.py:4: in <module> from django.contrib.auth.models import User, Group ../venv/lib/python3.7/site-packages/django/contrib/auth/models.py:2: in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager ../venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py:47: in <module> class AbstractBaseUser(models.Model): ../venv/lib/python3.7/site-packages/django/db/models/base.py:103: in __new__ app_config = apps.get_containing_app_config(module) ../venv/lib/python3.7/site-packages/django/apps/registry.py:252: in get_containing_app_config self.check_apps_ready() ../venv/lib/python3.7/site-packages/django/apps/registry.py:134: in check_apps_ready settings.INSTALLED_APPS ../venv/lib/python3.7/site-packages/django/conf/__init__.py:79: in __getattr__ self._setup(name) ../venv/lib/python3.7/site-packages/django/conf/__init__.py:64: in _setup % (desc, ENVIRONMENT_VARIABLE)) E django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. However whenever I run pytest --ds=myproject.settings, it works fine but without the configs mentioned in pytest.ini. I have created a conftest.py at the same level as pytest.ini and I am using Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 What am I doing wrong? Any help would be appreciated. Thanks in advance! -
How to run a function with arguments from python shell in Django
I am facing with the problem of running my function containing arguments from the python shell environment in a Django project. Here is the function i am trying to run from shell: def email_process(request,email): print("Inside email process function \n") #1st step find the email of logged in user which is the receiver to_email = [email] #1st step define the email of the sender from_email=settings.EMAIL_HOST_USER #3rd step define the subject of the email subject="Test Subject" #4th step define the message of the email message="Sign up procedure" #4th step define the paragraph of the email paragraph="The sign up procedure completed" #5th call the function to send the email message = create_mail_message(message,paragraph) send_mail(subject,message,from_email,to_email,fail_silently=True,html_message=message) Here, there are the steps I am following to run the function: Enter to the shell environment python manage.py shell My function resides in the users/views.py file so i type: from users.views import email_process To run the function i type email_process() but fairly enough the shell complains about missing arguments TypeError: email_process() missing 2 required positional arguments: 'request' and 'email' How can i add these arguments from shell? -
Linking my Python QR code scanner with Django?
I built my python QR code with opencv, numpy and pyzbar libraries. I don't know how to make it work on Django. -
Can Django admin show the image after the model name?
I have a problem. Can I add image after the Model name in the django admin? The postion I want to add the picture. I want to see the books image when I login admin page I have no idea about it maybe I can use verbose_name with inject html tag? Can django do it? Or I should use others way to do it? -
Throw [Errno 13] when docker-compose build
docker-compose.yml: version: '3' services: web: build: . command: ./manage.py runserver container_name: report_service volumes: - .:/report_service ports: - "8000:8000" Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /report_service WORKDIR /report_service ADD . /report_service/ RUN pip install -r requirements.txt --user Why throw this error? When i local build on Mac OS it's okey but if on production (ubuntu) error. root@services:~/services/generation_report# docker-compose build ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/root/.local/lib/python3.6/site-packages/__pycache__/appdirs.cpython-36.pyc.139931671694792' Check the permissions. ERROR: Service 'web' failed to build: The command '/bin/sh -c pip3 install -r requirements.txt --user' returned a non-zero code: 1 -
what is diffrent between WSGIRequest and django HttpRequest?
in django view ,I check the type of request : it shows <class 'django.core.handlers.wsgi.WSGIRequest'> def simpleview(request): print(type(request)) output: <class 'django.core.handlers.wsgi.WSGIRequest'> but in django documenttion but django has documented HttpRequest what is the diffrent beetween these two ? -
Django - Items not showing up in Products page
I'm trying to create a basic e-commerce site in Django. I have created a products page and when I open the page, my products are not showing up. I'm new to Django and have no idea what to do. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('products', views.products) ] views.py from django.shortcuts import render from products.models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def products(request): return render(request, 'products.html') index.html file in templates folder <!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"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>{% block title %}{% endblock title %}PyShop</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="/">PyShop</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="/products">Products</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a … -
Add additional data when django form is saved
I am looking for some help in my first django app and I am new to programming. I have the below scenario: Models: class save_table(models.Model): name=models.CharField(max_length=100) UniqueuserID = models.CharField(max_length=7) UserLocation = models.CharField(max_length=100) UserLead = models.CharField(max_length=50) def __str__(Self): return self.UniqueuserID class data_table(models.Model): UniqueuserID = models.CharField(max_length=7) name=models.CharField(max_length=100) UserLocation = models.CharField(max_length=100) UserLead = models.CharField(max_length=50) Form: class save_table_form(forms.ModelForm): class Meta: model = save_table fields = ('UniqueuserID') def __init__(self,*args,**kwargs): super(save_table_form,self).__init__(*args,**kwargs) Every user ID that the user will add to the form will have a respective data entry int he second model and I want to save that additional data along with the form. However I did not use a foreign key because I do not want the saved model data in the save_table to change based on the changes in the data_table. Can I add the additional data to the form before saving the form. if form.is_valid(): form.save() Please help.. -
Substring in search with Django
How I can do a search for substring for a filename using Django views.py def search(request): entries = util.list_entries() find_entries = list() search_box = request.POST.get("q").capitalize() if search_box in entries: return HttpResponseRedirect(f"wiki/{search_box}") for entry in entries: if search_box in entry: find_entries.append(entry) return render(request, "encyclopedia/search.html", { "search_result": find_entries, "search": search_box }) else: print(f'{find_entries}') else: return render(request, "encyclopedia/search.html", {"no_result": f"No results for {search_box}"}) search.html: {% extends "encyclopedia/layout.html" %} {% block title %} search results {% endblock %} {% block body %} {% for result in search_result %} <li><a href=wiki/{{ result }}>{{ result }}</a></li> {% endfor %} <h1>{{ no_result }}</h1> {% endblock %} i tried it but only return a result for example if I search for 'd' it only return django and then stop the for loop without return another values like node for example -
Is it possible to create a .msi installer for dockerized angular plus django web application?
I have a web application (angular+django) running locally in Docker. Is it possible to create an executable version of the application for windows i.e distributable Docker image that could be installed in windows? I do not want the end-user to install docker and run the docker commands, it should be like normal software installation. How should I proceed in this case, if not, any alternative solution possible? Thanks in advance! -
How to use the redirect_field_name in Django's auhviews?
I am creating a django project involving multiple types of users. For that, I have not created new User classes, rather I have just extended the model using a OneToOne relation (like we do while creating a profile model). One of the models is like this: class Dev(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) BaseSkills = models.ManyToManyField(ProjectBaseSkills, help_text='Adding Base skills help us to identify the best projects for you', blank=True) PhoneNumber = models.BigIntegerField( help_text="Don't add the country code (the user base is restricted to India for now)") def __str__(self): return f'{self.user.first_name} {self.user.last_name}' Now since there are multiple user types, I need to redirect the different users to different urls after login, so I can't just rely on the LOGIN_REDIRECT_URL settings. Also I don't want to define a login view myself, so I am using the default LoginView from django auth. Here is the urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='dev_user/login.html'), name='dev-login'), path('register/', views.Register, name='dev-register') ] + static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT) In the documentation (https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.views.LoginView) it is said that we can override the redirect url by using the redirect_field_name in GET … -
Django authentication process, how to render the template of email?
I'm setting the authentication process in my django project. In my password_reset_email.html I have set the following code: Someone requested a password reset for the account associated with the email {{email}}. If you haven't changed any passwords, I will ignore this email. Follow the link in case you proceed: {{protocol}}://{{domain}}{% url 'password_reset_confirm' uidb64=uid token=token %} But when I send the e-mail the hyperlink not works. Appear only the text. How could get it? -
Passing aws credentials as windows ENV variables to dockerfile
I have a django project that i am trying to deploy in aws, i am using the parameter store to store my secret keys, so i need to pass the aws credentials and the region otherwise i am getting an error each time i want to create the docker image that the aws credentials are missing, i have tried to pass those credentials as windows env variables using the setx variable value i am able to get the correct value when i run echo %variable% on the cmd, i have added this to the docker file ENV AWS_ACCESS_KEY_ID ${AWS_ACCESS_KEY_ID} ENV AWS_SECRET_ACCESS_KEY ${AWS_SECRET_ACCESS_KEY} ENV AWS_DEFAULT_REGION ${AWS_DEFAULT_REGION} i was getting always the same error so i have added this cmd to print the variables that i have in the container when creating the image Run printenv i have got the logic output is that the three variables are empty so i assume that the docker file is not accessing those variables, i don't know if it is a permission problem or if some one got the same error as mine, I have also passed those values to the docker-compose file environment: - AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} - AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} - AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION} But the dockerfile is not … -
Blog post cards |safe whitout styling?
On my blog post cards I have truncated text of the post previewed. I create the posts with with ckeditor so my problem is when I create a post if I have |safe used on the cards it renders with large text or any styling. Is there any way I can just have plain text while using safe to not show tags? -
Djang - Apache wsgi fails ModuleNotFoundError
My apache / wsgi config is correct (it runs py3.8 and executes the script). The problem is that I can't import either the settings file or my app. My wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'timemanagement.settings') application = get_wsgi_application() Installed apps (in settings.py): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mod_wsgi.server', 'timemanagementtool', ] Error: ModuleNotFoundError: No module named 'timemanagement' If i specify in wsgi.py that: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') It fails with: ModuleNotFoundError: No module named 'timemanagement_tool' Folder struture: Root: test/ apps: test/timemanagement, test/timemanagement_tool wsgi.py: test/timemanagement/wsgi.py settings.py: test/timemanagement/settings.py -
Django form Wizard: Create "Add Another Record" button on same form
I am using django form wizard with 9 steps. My problem is that i need to populate a listview with with multiple records using same form(on step5). In short on step5 i want my form to have "Add another record" button. When i click this button staying on the same page i populate the table below, usage of this button will be optional. Then i proceed to next steps and complete my process. my get_form currently looks like this: def get_form(self, step=None, data=None, files=None): # determine the step if not given if step is None: step = self.steps.current return form what should be my approach? -
Upload input data and input file using ajax in django
Using ajax to pass input data to views function editJob but I also want to upload a file using ajax. I am using jQuery("#myform").serialize() for passing data but I suppose this will not help me in uploading images. What will be the ajax code for uploading image. <script> jQuery(".submit").on('click',function (e) { e.preventDefault(); jQuery.ajax({ type:'POST', url:'{% url 'editJobDesc' %}', dataType:'json', enctype: 'multipart/form-data', data: jQuery("#myform").serialize(), success: function (data) { if(data['success']){ $(".alert-success").css("display", "block"); } else{ $(".alert-success").css("display", "none"); } } }); }); </script> <form id="myform"> <input type="file" class="myfile" name="myfile" accept=".jpg, .png, .jpeg"> </form> -
Form Failing Validation - Multi File Upload
I am following a tutorial to add multi-file upload using AJAX but am really stuck. I later intend on loading in a inlineformset_factory of the users uploaded_files as the user will have manyunits and they will be able to upload many uploaded_files to each unit. I'm first trying to get a very basic implementation working. In my view if form.is_valid(): fails and I'm not sure why. view.py ajax class UserUploadView(View): def get(self, request): files_list = UserUploadedFile.objects.all() return render(self.request, 'users/modules.html', {'user_files': files_list}) def post(self, request): form = UserUploadedFileForm(self.request.POST, self.request.FILES) if form.is_valid(): uploaded_file = form.save() data = {'is_valid': True, 'name': uploaded_file.file.name, 'url': uploaded_file.file.url} else: data = {'is_valid': False} return JsonResponse(data) normal view def modules(request): [...] return render(request, 'users/modules.html', {"user":User.objects.get(username=username)}) javascript.js $(function () { $(".js-upload-photos").click(function () { $("#fileupload").click(); }); $("#fileupload").fileupload({ dataType: 'json', done: function (e, data) { if (data.result.is_valid) { $("#gallery tbody").prepend( "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>" ) } } }); }); template.html <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% url 'user-file-upload' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> models.py class UserUploadedFile(models.Model): unit = models.ForeignKey(UnitData, related_name='user_uploaded_file', on_delete=models.CASCADE) user_file = models.FileField(upload_to='user_files/', default=None) forms.py class UserUploadedFileForm(forms.ModelForm): class Meta: model = UserUploadedFile fields = ('user_file', ) Thank you. -
How to add styling to ManytoMany field in forms(Django)
I am trying to add styling in my Django forms. I know how to add styling in single input fields but in manytomany fields, it display kind of weird which I don't like. I have tried to add classes in widgets attributes but it does not work. This is my code. #model.py class Professor(models.Model): professor_id = models.AutoField(primary_key=True) professor_name = models.CharField(max_length=200, null=True) professor_course = models.ManyToManyField(Course) working_hours = models.IntegerField(null=True) def __str__(self): return self.professor_name [#form.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = \['course_id', 'course_name', 'course_type', 'per_week_classes'\] course_name = forms.TextInput(attrs={'id': 'course_name', 'class': 'form-control'}) course_type = forms.TextInput(attrs={'id': 'course_type', 'class': 'form-control'}) per_week_classes = forms.NumberInput(attrs={'id': 'per_week_classes', 'class': 'form-control'}) class ProfessorForm(forms.ModelForm): class Meta: model = Professor fields = \['professor_name', 'professor_course', 'working_hours'\]][1] This is how it looks now. I want to add search facility and styling to it. -
django Item cant be removed from cart
class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path,null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) class OrderItem(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) item_cart = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return f"{self.item.title}" class Cart(models.Model): user = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE) products = models.ManyToManyField(OrderItem, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) """ new_or_get function returns cardid if exists or create new session of the cart and returns cardid """ def new_or_get(self,request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) print("qs",qs) if qs.count() == 1: cart_obj = qs.first() new_obj = False if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() print("user is there") else: cart_obj = Cart.objects.new(user=request.user) new_obj=True request.session['cart_id'] = cart_obj.id return cart_obj ,new_obj """ in this cart_update fumction i can add a item to the cart but i cant remove it ? i cant understand y """ def cart_update(request): print(request.POST) product_id = request.POST.get('product_id') product = Product.objects.get(id=product_id) print("id", product) quantity = 1 product_obj = Product.objects.get(id=product_id) print("product_obj",product_obj) if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("shoe message product is gone") return redirect("cart:home") … -
ValueError at /category/sugar/ Field 'id' expected a number but got 'sugar'
I'm trying to make category for eCommerce urlpatterns = [ path('category/<cats>/', views.categoryView , name = 'category') ] views.py: def categoryView(request, cats): products_category = Product.objects.filter(category=cats) return render(request, 'store/categories.html', {'cats': cats.title(), 'products_category': products_category}) models.py class Category(models.Model): name = models.CharField(max_length=100) image = models.FileField(null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') @property def imageURL(self): try: url = self.image.url except: url = '' return url class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=40, unique=True) price = models.FloatField() discount = models.FloatField(blank=True, null=True) digital = models.BooleanField(default=False, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') featured = models.BooleanField(default=False, null=True, blank=True) new = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url html {% for product in products_category %} <div class="col-lg-3 col-md-6"> <div class="product-item mb-30"> <a href="#" class="product-img"> <img src="{{ product.imageURL}}" alt=""> <div class="product-absolute-options"> <span class="offer-badge-1">6% off</span> <span class="like-icon" title="wishlist"></span> </div> </a> </div> </div> {% endfor %} when i try to get category name to my URL got this error, and if i write the category id in URL like this >> http://127.0.0.1:8000/category/3/ I got the correct page, If i clicked on category get this message ValueError at /category/sugar/ Field 'id' expected a …