Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I can set frontend of html to Django CMS login page that can redirect to login page of Django CMS?
I want to redirect my user from my html frontend and there after they must see dajngo CMS login page. Please anyone tell how to do? My html code contains admin panel How to do? -
Issue in starting Django server
I followed the instructions given on Django docs and did the following: django-admin startproject mysite cd mysite python3 manage.py runserver I get the following error : File "/home/dox/.local/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' My Django version is 3.0.4 -
my template is broken and cannot get static files
my template didn't work and can't get static files but I did everything. my static folder is in the Base directory but when I'm trying to reach static files, for example, CSS or js I'm getting file not found error and template is broken. my file Tree for project this is an image of my folder and project tree Settings for Static and media. STATIC_URL = '/temfiles/' MEDIA_URL = '/mediafiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads/') X_FRAME_OPTIONS = 'SAMEORIGIN' my project URL file urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('froala_editor/', include('froala_editor.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my app URL file urlpatterns = [ path('', views.index, name = 'index'), path('<slug:slug>/', views.post_detail, name='Post Detail') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my Views File def index(request): Post_list = BlogPost.objects.all() template_name = 'front/index.html' return render(request, template_name,{"Post_list":Post_list}) def post_detail(request): return render(request, 'front/post_detail.html') my base template CSS example {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'front/css/style.css' %}"> -
ModuleNotFoundError: No module named 'posts.urls'
I'm starting with Django by seeing a tutorial, when I start editing urls.py, I start giving these errors: Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\salva\appdata\local\programs\python\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\salva\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "c:\users\salva\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, … -
Update form creates new object in Django
I have a Trip model and created a form so it updates existing trips. models.py: class Trip(models.Model): trip_id = models.CharField(max_length=20, verbose_name="Ref. Viagem") destination = models.CharField(max_length=200, null=True, verbose_name='Destino') client = models.ForeignKey(Clients, null=True, on_delete=models.CASCADE, verbose_name="Cliente") out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida") hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel") in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso") forms.py: class UpdateTrip(ModelForm): def __init__(self, *args, **kwargs): super(UpdateTrip, self).__init__(*args, **kwargs) self.fields['trip_id'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['destination'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['client'].queryset = Clients.objects.all() class Meta: model = Trip fields = ('trip_id', 'destination', 'client', 'out_flight', 'hotel', 'in_flight') And this is the views.py for it: def trip_upd(request, trip_id): if request.method == 'POST': form = UpdateTrip(request.POST) if form.is_valid(): form.save() return redirect('trips') else: form = UpdateTrip() return render(request, 'backend/trip_update.html', {'form': form}) I am using a barebones form while testing: <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> Now, this doesn't update the objects but creates a new one. -
Django application using matlab.engine in python script failing when deploying on aws using elastic beanstalk
I am deploying my django application on aws using elastic beanstalk. I have setup virtual python environment and its using matlab.engine inside python script. Its running perfectly on my ec2 but when I use eb deploy coomand it shows below error. I have put error logs below. [2020-03-07T18:51:26.604Z] INFO [10873] - [Application update app-200307_185106@172/AppDeployStage0/AppDeployPreHook/03deploy.py] : Starting activity... [2020-03-07T18:51:27.509Z] INFO [10873] - [Application update app-200307_185106@172/AppDeployStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Requirement already satisfied: certifi==2019.11.28 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Requirement already satisfied: chardet==3.0.4 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Requirement already satisfied: defusedxml==0.6.0 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Requirement already satisfied: Django==2.1.1 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Requirement already satisfied: django-paypal==1.0.0 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Requirement already satisfied: idna==2.8 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Collecting matlabengineforpython===R2018b (from -r /opt/python/ondeck/app/requirements.txt (line 7)) Could not find a version that satisfies the requirement matlabengineforpython===R2018b (from -r /opt/python/ondeck/app/requirements.txt (line 7)) (from versions: ) No matching distribution found for matlabengineforpython===R2018b (from -r /opt/python/ondeck/app/requirements.txt (line 7)) You are using pip version 9.0.1, however version 20.0.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2020-03-07 18:51:27,502 ERROR Error installing dependencies: Command … -
DRF ModelViewSet queryset return results that their date is greater than or equal to today
I am using Django Rest Framework. In the queryset I'm trying to filter my objects based on IF their Date is greater than or equal to today. Like so: class DateViewSet(viewsets.ModelViewSet): """ API Endpoint to retrieve all dates after today. """ serializer_class = DateSerializer today = datetime.date.today() queryset = EventDate.objects.filter(end_date__gte=today) But this ends up showing the past dates as well. my serializer: class DateSerializer(serializers.ModelSerializer): class Meta: model = EventDate fields = ('start_date', 'end_date') And then I pass it on to the Event Serializer: class EventSerializer(serializers.HyperlinkedModelSerializer): id = serializers.StringRelatedField() dates = DateSerializer(many=True, read_only=True) class Meta: model = Event fields = '__all__' extra_kwargs = { 'url': {'lookup_field': 'slug'}, } My goal is when my API returns all events it should not return all dates that have been in the past. What am I doing wrong? -
31/5000 connecting django with postgresql
how to connect postgres to the django project? when trying to connect I get the error "django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2" When installing psycopg2 you get the error "Command" python setup.py egg_info "failed with error code 1 in / tmp / pip-install-xntnhxcd / psycopg2 /" Error: You need to install postgresql-server-dev-NN for building a server-side extension or libpq-dev for building a client-side applicati when installing "sudo apt install libpg-dev" Reading package lists ... Done Building a dependency tree Reading status information ... Ready E: The libpg-dev package could not be found -
python django only the first statement statement can be accessed
i can acccess only the first statement in my name app javascript: <script type="text/javascript"> function searched(){ {% for names in name %} nameSearched = document.getElementById('name').value; document.getElementById('dis').innerHTML = nameSearched; if (nameSearched == "{{ names.First }}" ){ document.getElementById('dis').innerHTML = "{{ names.Last }}"; } else { document.getElementById('dis').innerHTML = "none"; } {% endfor %} } </script> -
hashtag signal is not working properly in the update view
I have successfully take the @username hashtagging part in the new post form whenever i update that with another content of @username its not giving the user any signals. And i'm using django-notifications to notify the user. i'm using django claassbased update view. my models.py: class post(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) video = models.FileField(upload_to='post_videos', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = postManager() def __str__(self): return self.title class Meta: ordering = ['-date_posted', 'title'] def get_absolute_url(self): return reverse ('blog-home') def total_likes(self): return self.likes.count() def post_save_receiver(sender, instance, created, *args,**kwargs): if created and not instance.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, instance.content) if m: try: recipient = User.objects.get(username=m.group('username')) except (User.DoesNotExist, User.MultipleObjectsReturned): pass else: notify.send(instance.author, recipient=recipient, actor=instance.author, verb='mention you in a post', target=instance, nf_type='tagged_by_one_user') post_save.connect(post_save_receiver, sender=post) and my updateview in views.py: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = post fields = ['content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def update_save_receiver(sender, post, created, *args,**kwargs): if created and not post.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, post.content) if m: try: recipient … -
Session variable set before request is not accessible in Django view during tests
I need to store a kind of state between HTTP requests. Because I don't use the JS frontend, I decided to use session variables stored in cookies. My session settings look like below: SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_COOKIE_HTTPONLY = False I need a function to easily manipulate one session variable. Because this functionality is quite simple, I decided to exceptionally use function-based view: def set_category_filter(request, pk): if pk == 0: if 'filter_category_id' in request.session: # this is False during unit testing, but it's ok in a normal app run del request.session['filter_category_id'] else: get_object_or_404(Category, pk=pk, user=request.user) request.session['filter_category_id'] = pk return redirect('index') The problem is I cannot test case when I want to unset this session variable. Suppose the session variable filter_category_id is set and I want to reset it. When I do this in my browser, everything works okay. When I try to do this via Django TestCase, it fails, because this session variable is not passed to request! class SetCategoryFilterTest(TestCase): def setUp(self) -> None: super().setUp() self.fake = Faker() self.user = User.objects.create_user(username="testuser", password="12345") self.client.force_login(self.user) def tearDown(self): self.client.logout() # ... def test_unset_successfully(self): """Werify unsetting "filter_category_id" session field. Expected: Delete "filter_category_id" when url called with parameter 0 """ # GIVEN session = self.client.session session['filter_category_id'] … -
How import everything from designated module without get error of flake8
I want to split my settings.py in django project so I do: # within __init__py from .app import * try: from .app.local_settings import * except ImportError: pass But I get this error from flake8: 'from .app import *' used; unable to detect undefined namesflake8(F403) '.app.*' imported but unusedflake8(F401) How can I solve it? When I used of importlib.import_module I got The SECRET_KEY setting must not be empty error because the 'SECRET_KEY` inserted into the object that returned from importlib.import_module. -
Django form not submitting on post
I have django form that is not submitting upon clicking Submit. I try to click on the button to submit the information nothing happens. No errors or messages of any kind show up in terminal or in developer in Chrome. There is no JS on this page just straight html: I used the same approach on the a different project but for this it doesn't work. What could be the issue with my code. models.py class Department(models.Model): depart_code = models.CharField(max_length=20,unique=True) depart_name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.depart_name views.py class DepartmentAddView(CreateView): model = Department form_class = DeptAddForm template_name = 'hrms/department_form.html' def form_valid(self, form): form.save() return redirect('/') forms.py class DeptAddForm(forms.ModelForm): depart_name = forms.CharField( max_length=100, widget=forms.TextInput( attrs={ 'class': 'span8', } ), label = "*Department Name", ) departt_code = forms.CharField( max_length=100, widget=forms.TextInput( attrs={ 'class': 'span8', } ), label = "*Department Code", ) class Meta: model = Department fields = ['depart_code', 'depart_name'] hrms/department_form.html <form class="form-horizontal row-fluid" method="POST">{% csrf_token %} <div class="control-group"> <label class="control-label" for="basicinput">Department Code</label> <div class="controls"> {{ form.depart_code }} </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Department Name</label> <div class="controls"> {{ form.depart_name }} </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn-success">Submit Form</button> </div> </div> </form> -
How to get Django models data in python script variables?
I want to get the data stored in django models dynamically into my python script. But so far I have not found any solution. I'm new to django so would appreciate the help. -
Make a ForiegnKey to an unknown model in django
I'll illustrate by example I have class Stone(models.Model): # name, color, whatever class Member(models.Model): # whatever class Image(models.Model): stone = models.ForiegnKey(Stone, on_delete=...) # this should have the model that needs images image = models.ImageField() I'm using a foriegnKey to the Image model to make multiple images, But This forces me to create an Image model for each Model, In my example, Stone can has multiple images right? I want Member and all my models that need images to use the same class, I want to make only one images table. I've been searching for a while but I don't think I know what should be the search text, I read about ContentType but I don't think I understand what it does and I don't even know if it's the what I'm asking for. -
How to implement multi-tenancy with custom user model?
I'm trying to create a multi-tenant application where authentication happens through the django default user model. I've used my own custom user model. I want to use same database with multiple schemas. User Model class UsersManager(BaseUserManager): def create_user(self, username, password=None, **kwargs): if not username: raise ValueError('Users must have a valid username.') if not kwargs.get('email'): raise ValueError('Users must have a valid email.') if not kwargs.get('contact_number'): raise ValueError('Users must have a valid contact number.') account = self.model( username=username, email = kwargs.get('email'), contact_number=kwargs.get('contact_number'),first_name=kwargs.get('first_name'),last_name=kwargs.get('last_name') ) account.set_password(password) account.save() return account def create_staffuser(self, username, password, **kwargs): account = self.create_user(username, password, **kwargs) account.is_admin = False account.is_superuser = False account.is_staff = True account.is_agent = False account.save() return account def create_superuser(self, username, password, **kwargs): account = self.create_user(username, password, **kwargs) account.is_admin = True account.is_staff = True account.is_superuser = True account.is_agent = False account.save() return account def create tenant_user(self, username, password, **kwargs): """Custom command to create a tenant user""" ... ????????????????????? class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50, default=None, null=True) middle_name = models.CharField(max_length=50, default=None, null=True) last_name = models.CharField(max_length=50, default = None, null=True) username = models.CharField(unique=True, max_length=50) email = models.EmailField(unique=True) street_address = models.CharField(max_length=150) city = models.CharField(max_length=50) contact_number = models.CharField(max_length=40) alternative_contact_number = models.CharField(max_length=40,default=None, null=True) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) objects = UsersManager() USERNAME_FIELD … -
Modeling a 2D Table in PostgreSQL (Django)
So I'd like to model a 2D table in PostgreSQL, and by 2D I mean I'd like to add/update/delete both rows and columns. Before I really get into the details I wanted to convey that I did look into dynamic Django models such that I could extends models and add columns during runtime but to be honest it does seem like kind of a hack job, and none of those packages have good docs or is maintained as of now for the latest version of Django and Python. NoSQL is kinda a stretch to switch too this late in the game and eliminates many of the useful features of Django such as the ORM and model integration with DRF. For example in this table, I have some required fields such as firmware name to which I might add publish date or build number or something of the sort. But I also have column headers which may be added or removed as new software versions are released, for example 4.0.1. Is there such a way of modeling this to optimally create a CRUD API that avoids unnecessary redundancy? As of now, I basically have the following models, but of course storing … -
How to get current page number of pdf document which is rendered using <embed> tag in html?
I am rendering a simple html template in my Django project and I want to dynamically know which page the user is reading currently. Is there any way to get that information, and then use it at the backend. -
How to keep getting http data in flutter?
I am currently creating a location tracking application. It contains a backend where lat and long is stored. So how can my flutter application keep getting the data from the server in certain intervals using http in flutter? -
Nontype error while iterating json in djagon template
I need to iterate json in my django template. I receive nontype error while attempting to do this. the JSON object must be str, bytes or bytearray, not NoneType context["reserved"] = json.dumps(reserved, sort_keys=True) return render(request, 'users_templates/reservations.html', context) {% for date,time in reserved.items|loadjson %} <tr> <td>{{forloop.counter}}</td> <td>{{date}}</td> <td>Pitt</td> <td>35</td> <td>test</td> </tr> {% endfor %} -
How do I create comment which is automatically is related to model
I need to set comment which is automatically related to the Article model when created article list article comment article list comment model -
Django: can't retrieve variable from my view after AJAX call
After an AJAX Post request, I'm trying to retrieve from my view some list values contained in a variable. The idea is to use these values to populate a dropdown. But my variable seems empty. I thought that it was because I initially used a 'return render()', but even with a 'return HttpResponse()' it doesn't work. This is my views.py: def MyView3(request): if request.method == 'POST' and request.is_ajax: myVariable = ["1", "2", "3", "4", "5"] print(myVariable) return HttpResponse(myVariable) else: return render(request,'home3.html') This is my html code: <form class="wrapper" action="" method="post"> {% csrf_token %} <select name="myVal" class="toChange"> <option val="1">1</option> <option val="2">2</option> </select> <select id="dep" name="dep"> {% for item in myVariable %} <option val="{{ item }}"> {{ item }} </option> {% endfor %} </select> <script type="text/javascript"> function dropdownChange () { var selectedValue = $(".toChange option:selected").val(); $.ajax({ type: 'POST', data: {'myVal': selectedValue}, }); var mylist = '{{myVariable}}'; alert(mylist); } $(".toChange").change(dropdownChange); </script> </form> The idea here is to triger the AJAX call when I select a new value in my 'myVal' dropdown. The call works since the view is correctly activated, as 'print(myVariable)' shows the expected result in the console. Moreover, my alert pop-up is displayed. Yet, it is empty. I would need it … -
I am developing a quiz app and trying to recuperate different responses of one question with django
i am developping a quiz app and trying to recuperate deffirent responses of one question with python-django; but it is not working need some help plz this is my views.py, when I try to add different responses of a question; the only one that is inserted is the last one def add_question_form_submission(request): print("hello form is submitted.") Commentaire= request.POST["Commentaire"] questions = request.POST["question"] matiere= request.POST["matiere"] dif = request.POST["dif"] reponses= request.POST["reponse"] comment = request.POST["comment"] flag = request.POST["flag"] ques=question(questionA=questions,explication=Commentaire, difficulte=dif,id_matiere=matiere) ques.save() rep =reponse(response=reponses,commentaire=comment,estVrai=flag,id_question=ques.id_question) rep.save() return render(request,"myblog/questionnaire.html") and this is my template with javascript, i used javascript to add more fields in order to add more responses of a question {% extends "myblog/base.html" %} {% block content %} <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper = $(".input_fields_wrap"); //Fields wrapper var add_button = $(".add_field_button"); //Add button ID var x = 1; //initlal text box count $(add_button).click(function(e){ //on add input button click e.preventDefault(); if(x < max_fields){ //max input box allowed x++; //text box increment $(wrapper).append('<div><input placeholder="reponse" type="text" name="reponse"/> <input placeholder="Comment" align="center" type="text" name="comment"><select name="flag"> <option value=True>Vrai</option><option value=False>Faux</option></select> <a href="#" class="remove_field">Remove</a></div>'); //add input box } }); $(wrapper).on("click",".remove_field", function(e){ //user click on remove text e.preventDefault(); $(this).parent('div').remove(); x--; }) }); … -
how to send the selected value to django?
I trying to implement a search button using ajax and django where I send the selected value the server, but I can't get the selected value from the select HTML tag , the variable value is always empty ({"obj":""}) ?? HTML : div class="col-2"> <label style="color : white;">Title</label> <select name="da" id="da" class="form-control da"> <option selected></option> {% for obj in ds %} <option value="{{obj}}">{{obj}}</option> {%endfor%} </select> <button type="submit" class="btn btn-warning btn-lg search">ajax</button> </div> ajax : var value = $('#da').val(); console.log(value) $(document).ready(function() { $('.search').click(function(){ var csrftoken = $('[name="csrfmiddlewaretoken"]').val(); $.ajax({ type: "GET", url: '/search/ajax/', data: JSON.stringify({'obj' : value}), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, success: function(response) { do somthing ...... }, error: function(rs, e) { alert(rs.responseText); } }); }) }); view.py def filter_ajax(request): if request.method == 'GET': value = request.GET.get('obj') print(value) -
get_object_or_404 not working properly in django
when I attempt to get an object with specific slug it gave me 404 page error, however I've hard coded the slug name and that worked and I've printed the slug field separately and it was the one that I've already tested before. this the view part: def show_category(request, hierarchy=None): category_slug = hierarchy.split('/') category_queryset = list(Category.objects.all()) all_slugs = [x.slug for x in category_queryset] print(all_slugs) print(get_object_or_404(Product, title='benz')) parent = None for slug in category_slug: if slug in all_slugs: parent = get_object_or_404(Category, slug=slug, parent=parent) else: # these 3 lines bellow: print(slug) print(get_object_or_404(Product, slug='benz')) instance = get_object_or_404(Product, slug=slug) breadcrumbs_link = instance.get_cat_list() breadcrumbs_name = instance.get_cat_names() category_name = [' '.join(i.split('/')[-1].split('-')) for i in breadcrumbs_name] breadcrumbs = zip(breadcrumbs_link, category_name) return render(request, "products/product_detail.html", {'instance': instance, 'breadcrumbs': breadcrumbs}) return render(request, "products/products_list.html", {'product_set': parent.product_set.all(), 'sub_categories': parent.children.all()}) and these are Product and Category models: class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(allow_unicode=True) parent = models.ForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" @property def get_products(self): return Product.objects.filter(category__name=self.name) class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField(verbose_name='desription') slug = models.SlugField() image = models.ImageField(upload_to='product_pics', default='default.jpg') category = models.ForeignKey( 'Category', null=True, blank=True, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('product-detail', kwargs={'slug': self.slug}) def get_cat_list(self): k = self.category breadcrumb = ["dummy"] …