Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does my code have to be written in php to intefrate WordPress
Say for instance i have a web application that uses Django as a framework, is there going to be a problem when integrating WordPress? -
unable to connect django sevice with rabbitmq service using docker
I am trying to connect RabbitMQ with Django application. But when I run the command "docker-compose up" I get this error "pika.exceptions.AMQPConnectionError" can someone explain me the reason for this error and also suggest me its solution. I am sharing the code of docker-compose file and the publisher code where the main error is. docker-compose.yml version: '3.8' services: db: image: postgres:9.6-alpine restart: always environment: # - HOST:localhost - POSTGRES_DB=admin - POSTGRES_USER=postgres - POSTGRES_PASSWORD=admin123 # MYSQL_ROOT_PASSWORD: root volumes: - ./postgres-data:/var/lib/postgresql/data ports: - 5432:5432 rabbitmq: image: rabbitmq:3.8-management-alpine hostname: rabbitmq ports: - 15673:15672 environment: - RABBITMQ_DEFAULT_HOST=localhost - RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_PASS=guest backend: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/app environment: - RABBITMQ_DEFAULT_HOST=rabbitmq - RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_PASS=guest depends_on: - db - rabbitmq produce.py import pika, os, django from .models import Product # amqps://bescccok:rsjlBxeksDvwcp23H0QDJh83qttksbsF@sparrow.rmq.cloudamqp.com/bescccok connection = pika.BlockingConnection( pika.ConnectionParameters('localhost') ) channel = connection.channel() def callback(ch, method, properties, body): import json print('Received in admin') id = json.loads(body) product = Product.objects.get(id=id) product.likes = product.likes + 1 print("Product Liked!!! ") channel.basic_consume(queue='admin', on_message_callback=callback, auto_ack=True) print("Started Consuming") channel.start_consuming() channel.close() I tried to changing the hostname in docker-compose file in rabbitmq service and add the servicein pika connection function, still it didn't work. -
How to send image from django html template to view and use the openCv handdetector
I want to use a webcam in my django application and use it to play rock paper scissors with cv2 hand recognition. Basic webcam html template: <div class="container"> <div class="row"> <div class="col-md-6"> <video id="webcam" width="640" height="480" autoplay></video> </div> <div class="col-md-6"> <button id="play-button" class="btn btn-primary" onclick="play()">Play</button> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // Function to start the webcam and display the video feed function startWebcam() { navigator.mediaDevices.getUserMedia({ video: true, audio: false }) .then(function(stream) { var video = document.getElementById('webcam'); video.srcObject = stream; video.play(); }) .catch(function(err) { console.log("An error occurred: " + err); }); } // Function to capture the image from the webcam and send it to the Django view function play() { // Stop the video stream from the webcam var video = document.getElementById('webcam'); var stream = video.srcObject; var tracks = stream.getTracks(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.stop(); } // Create a canvas element to draw the image on var canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; var context = canvas.getContext('2d'); context.drawImage(video, 0, 0, canvas.width, canvas.height); // Convert the image to a data URL var imageData = canvas.toDataURL('image/jpeg'); // Send the image to the Django view using an AJAX request … -
How to direct from post to category page in Django?
I'm working on my Django blog. I have a trouble to redirect from post to category, when you open post you can click to category and when you click on category I want you to redirect you to category and show posts only from that category. This part of my html code for post_detail.html <div class="entry-meta meta-0 font-small mb-30"><a href="{{ category_detail.get_absolute_url }}"><span class="post-cat bg-success color-white">{{ post.category}}</span></a></div> <h1 class="post-title mb-30"> {{ post.post_title }} </h1> This is models.py only class category class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") category_name = models.CharField(max_length=255, verbose_name="Category name") slug = models.SlugField(max_length=200, unique=True) def get_absolute_url(self): return reverse('category_detail', args=[self.slug]) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.category_name in post_detail is defined like this (short view) class Post(models.Model): ... post_title = models.CharField(max_length=200, verbose_name="Title") category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) ... def __str__(self): return self.post_title This is views.py def category_detail(request, pk): category = get_object_or_404(Category, pk=pk) return render(request, 'category_detail.html', {'category': category}) This is urls.py from . import views from django.urls import path urlpatterns = [ path('', views.home, name='home'), path('<slug:slug>/', views.post_detail, name='post_detail'), path('<slug:slug>/', views.category_detail, name='category_detail'), ] Any idea why I'm not redirected to category_detail page? Thanks in advance! -
'WSGIRequest' object has no attribute 'request'
I am trying to use a context processor to get the last 10 messages based on the user's organization. What is weird is that I can call self in get_user, but i can't in get_last_10_messages. Any ideas why I get the WSGIRequest issue in one function and not the other? from message.models import Message from contact.models import Contact def get_last_10_messages(self): print(self.request.user.id) user = Contact.objects.get(user_id=self.request.user.id).select_related('organization') last_10_messages = Message.objects.all() return {'last_messages': last_10_messages} def get_user(self): user = Contact.objects.get(user_id=self.request.user.id).select_related('organization') return {'user': user} -
Exception Value: badly formed hexadecimal UUID string
models.py import uuid from django.db import models class Book(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title def get_absolute_url(self): # new return reverse('book_detail', args=[str(self.id)]) "-----------------------------------------------------------------------" ? I want try for better id in models but i had this erorr... who can help me? -
Django URL installation failed
[enter image description here](https://i.stenter image description hereack.imgur.com/S7Ocu.png)enter image description here I am unable to install the url package. after i did pip install url, installation failed -
Django webpage loading issue
I'm creating a project in Django, my admin section is working properly, and models are working properly but when I'm going to open the server to check the landing page, it shows like this attached below. I've created another page and made that page the main landing page but that showed me the same result. Don't know what to do now. -
Finding it difficult to construct login functionalities. Bad request
view.py class Login(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(raise_exception=True): username = serializer.data.get('username') password = serializer.data.get('password') user = authenticate(password=password, username=username) # This line above and below this comment if user is not None: login(request, user) return Response({"msg": "Login Successful"}, status=status.HTTP_200_OK) else: return Response( { "errors": { "non_field_errors": ["Email or Password is not valid"] } }, status=status.HTTP_404_NOT_FOUND ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)pe here serializer.py class LoginSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] api.js import axios from 'axios' export default axios.create({ baseURL:'http://localhost:8000/', } ) signup const onSubmit = e =>{ e.preventDefault() api .post(`user/login/`, JSON.stringify({username, password}), ) .then(({data}) =>{ console.log(data) }) If if try to login on the browser, it returns AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} How to login from reactjs to django(python) -
Don't cross time in the fishing
I'm developing a site for the sport fishing booking at a fish farm. Almost the same as when booking a hotel stay. Only instead of a room - a fishing pier. I want to write a condition for saving data in the reservation database, where the booked time will not overlap with the previously booked one. Taking into account the selected pier. For example: fisherman John has booked "Pier 1" from 6:00 to 13:00. And fisherman Alex wanted to book the same day the same "Pier 1" from 11:00 to 21:00. But the code (perhaps a validator) will not allow Alex to do this, because from 11:00 to 13:00 "Pier 1" is still the time ordered by the fisherman John. Alex can choose another time or choose another "Pier 2", "Pier 3". I hope you understand me. So, the models.py is next from django.utils.translation import gettext_lazy as _ from django.utils.timezone import now from django.contrib.auth.models import User from django.db import models from django.core.exceptions import ValidationError # blocking the reservation time that has passed def validate_past_time(value): today = now() if value < today: raise ValidationError(_(f'{value} less than the current time {today}')) # booking model class BookingPier(models.Model): pier = models.ForeignKey('Pier', on_delete=models.PROTECT, null=True) PIER_STATUS_CHOICES … -
I would like to save my crop image to my django database called model filed file, help appricated - It been 3 days still stuck in this
I have the following models.py class Imageo(models.Model): file = models.ImageField(upload_to='cropped_images') uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.pk) I would like to savemy file into my Imageo models but it is saving into my database some other folder, please look at the views.py file. def con(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = Image.open(form.cleaned_data['file']) image = image.resize((200, 200), PIL.Image.ANTIALIAS) image = image.convert('RGB') dt = image.save('resize.jpg') # i would like to save resize.jpg into my models name called file return HttpResponse('done') else: form = ImageForm() img = Imageo.objects.latest('id') return render(request, 'NEC/imgCon.html', {'form': form, 'img': img}) -
DRF: make a POST query without data
cannot manage a POST method-query to url /users/{pk}/subscribe Accesing this url should insert a record in db using Subscription model. No data is passed in body when accessing this url model.Subscription class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscriber', ) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscribing' ) a router to users router.register(r'users', CustomUserViewSet, basename='users') and the additional URL that accepts POST query in the CustomUserViewSet class CustomUserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = CreateUserSerializer @action( detail=True, methods=['post', 'delete'], permission_classes=[IsAuthenticated], ) def subscribe(self, request, *args, **kwargs): user = request.user author_pk = int(kwargs.get('pk')) author_to_subscribe = get_object_or_404(User, id=author_pk) if request.method == 'DELETE': return Response(status=status.HTTP_204_NO_CONTENT) if user.pk == author_pk: data = { "errors": "Cannot subscribe to yourself" } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) # q = Subscription.objects.filter(user=user) serializer = SubscriptionCreateSerializer(data=request.data) serializer.is_valid() serializer.save(user=user, author=author_to_subscribe) return Response( status=status.HTTP_200_OK) Method shoould return serialized data from another serializer (SubscriptionSerializer. So i have 2 serializer for subscription: for viewing and creating At this point in Postman getting error -
Django Rest Framework response give me datatype on M2M field
Working on a GET request from my django DRF backend, I receive a strange response from my m2m field. The response you see here is a response fetching from a Video model Array [ Object { "categories": Array [ "USA", ], "id": 1, "title": "first vid", }, Object { "categories": Array [ "other", ], "id": 2, "title": "second vid", ] Notice the "Object" and "Array" types in the response. Categories and Videos share a M2M relation related to the "categories" field The models: class CategoryVideos(models.Model): class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name class Videos(models.Model): category = models.ManyToManyField(CategoryVideos, null=True, blank=True) illustration = models.FileField(null=True, blank=True) video = models.FileField(null=True, blank=True) title = models.CharField(max_length=255, null=True, blank=True) The serializer: class VideoSerializer(serializers.ModelSerializer): categories = serializers.SerializerMethodField() class Meta: model = Videos fields = ["id", "title","categories"] depth=1 def get_categories(self, obj): companies = None try: companies = [obj.name for obj in obj.category.all()] except: pass return companies And the request, coming from Axios on a React Native app const fetchdata = async () => { const response = await axios.get( "https://some_ngrok_url/offerlist" ); const data = await response.data; const setnewdata = await SetData(data); }; fetchdata(); }, []); Can anyone spot the … -
How to convert django base user model date_joined to user local time
How i can convert the the date_joined field from base user model to logged in user local time? I want to get the local user time as i have tried to filter it by using time zone but no luck. -
Django - Querysets - Eficient way to get totals
I have to get totals for diferent type of concepts (Rem, NR, NROS, etc) in the queryset concepto_liq and I'm doing one filter for each type (see the code below), is there a way to make it more efficent? Thank in advance! tmp_value = concepto_liq.filter(tipo='Rem', empleado=empleado).aggregate(Sum('importe')) remuneracion = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) tmp_value = concepto_liq.filter(tipo='NR', empleado=empleado).aggregate(Sum('importe')) no_remunerativo = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) tmp_value = concepto_liq.filter(tipo='NROS', empleado=empleado).aggregate(Sum('importe')) no_remunerativo_os = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) tmp_value = concepto_liq.filter(tipo='ApJb', empleado=empleado).aggregate(Sum('importe')) aporte_jb = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) tmp_value = concepto_liq.filter(tipo='ApOS', empleado=empleado).aggregate(Sum('importe')) aporte_os = 0 if not tmp_value['importe__sum'] else int(round(tmp_value['importe__sum'], 2) * 100) -
Django biometric scanning
Is there any library that I can use to add biometric field into a django model field, so that when user plugged in biometric scanner into a computer, that django model field would allow me to scan user finger and store it into a database and even viewing it in a template. I have try using this method: I created a python file into my app and named it: biometric_field.py: Class BiometricField(models.Model): def __init__(self, *args, **kwargs): kwargs['max_length'] = 1000 super().__init__(*args, **kwargs) def db_type(self, connection): return 'binary' And add it to the model like any other field: From .biometric_field import BiometricField Class Primary(models.Model): first_name = models.CharField(max_length=20) second_name = models.CharField(max_length=20) class_of_student = models.CharField(max_length=20) year_of_graduations = Foreignkey(PrimaryAlbum, '''''''''''') finger_print_first = BiometricField() ''''''''' But using that method was completely not scalable, because, there is no way to communicate with a hardware that would allow us to scan user finger, do you have any idea or method that we can use to make that happen in django or any python libraries that is good with django? -
Django URL logical OR misunderstood
I need my django application connect two different URLs to the same view. When I use regular expression, the result is different from what I expect: from django.http import HttpResponse from django.urls import re_path def readme(request): return HttpResponse('My test', content_type='text/plain') urlpatterns = [ re_path(r'^(readme|help)$', readme), ] I should render both http://127.0.0.1:8000/readme http://127.0.0.1:8000/help to the same view. But I receive the following error when entering the URL in my browser: Exception Value: readme() takes 1 positional argument but 2 were given Exception Location: /home/ar/.local/lib/python3.8/site-packages/django/core/handlers/base.py, line 197, in _get_response 191 if response is None: 192 wrapped_callback = self.make_view_atomic(callback) 193 # If it is an asynchronous view, run it in a subthread. 194 if asyncio.iscoroutinefunction(wrapped_callback): 195 wrapped_callback = async_to_sync(wrapped_callback) 196 try: 197 response = wrapped_callback(request, *callback_args, **callback_kwargs) 198 except Exception as e: 199 response = self.process_exception_by_middleware(e, request) 200 if response is None: 201 raise 202 203 # Complain if the view returned None (a common error). -
Django. Access list index in child for loop
How can I change the accessed index of an inner for loop list based on a counter from the outer loop? In normal python I would do something like parent_list = ['One','Two','Three'] child_list = ['A','B','C'] for idx, item in enumerate(parent_list): for child_item in child_list[idx]: print(str(idx), item, child_item) I've been looking at using with and forloop.counters but I either run into the index not being accessed or index not changing. This is what I currently have. {% for item in payout_items %} {% with forloop.counter0 as outer_counter %} <h2>{{ item.market_place }} on {{ item.entry_date }}: {% for item in royalty_items.outer_counter %} <tr> <th scope="row">{{ item.id }}</th> <td>{{ item.entry_date }}</td> <td>{{ item.market_place }}</td> </tr> {% endfor %} {% endwith %} {% endfor %} If I change {% for item in royalty_items.outer_counter %} to {% for item in royalty_items.0 %} I get the first index repeated many times. I can see that outer_counter is incrementing from the output but just need royalty_items to increment the accessed index as well. -
Django - DRF ManyToMany and ForeignKey
I am building an api for entertainment management. The user can create empty project or projects with show, tour and festival. User can also create show and specify project id. A project can contain: Show 0 to * Tour 0 to * Festival 0 to * A Tour can contain: Show 0 to 1 A Festival can contain: Show 0 to * A Show, Tour and Festival necessarily part of a Project. Here are my models: class Project(models.Model): """Models for Projects""" name = models.CharField(max_length=255, unique=True) shows = models.ManyToManyField('Show', blank=True) festivals = models.ManyToManyField('Festival', blank=True) tours = models.ManyToManyField('Tour', blank=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) date_created = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Show(models.Model): """Models for Shows""" name = models.CharField(max_length=255, unique=True) start_date = models.DateTimeField(default=timezone.now, blank=True) end_date = models.DateTimeField(default=timezone.now, blank=True) tours = models.ManyToManyField('Tour', blank=True) festivals = models.ManyToManyField('Festival', blank=True) projects = models.ForeignKey(Project, on_delete=models.CASCADE, default=None) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) date_created = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Tour(models.Model): """Models for Tour.""" name = models.CharField(max_length=255, unique=True) start_date = models.DateTimeField(default=timezone.now, blank=True) end_date = models.DateTimeField(default=timezone.now, blank=True) production = models.CharField(max_length=255, blank=True) shows = models.ForeignKey(Show, on_delete=models.CASCADE, blank=True, null=True) projects = models.ForeignKey(Project, on_delete=models.CASCADE, default=None) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) date_created = models.DateTimeField(auto_now_add=True) … -
I am working with Number Plate Detection Django web based project
enter image description here Views.py Coe What will be the correct code ? -
No module named 'sklearn' while running django server
I saved a model using joblib and was trying to run server using but it shows no module as sklearn even though it is downloaded in the environment, can anyone please help? -
Cannot render model fields in forloop (Django)
I am using .values() and .annotate()to sum up 2 models fields based on matching criteria. I wrapped this in a forloop in my template to iterate. Problem: I cannot call the model fields anymore. The forloop returns the venue_id instead of the name and the usual approach to call the logo does not work anymore. (these were rendering fine before I used .values() and .annotate(). Makes me think I am missing something in the logic here. Any ideas? Models class Venue(models.Model, HitCountMixin): id = models.AutoField(primary_key=True) name = models.CharField(verbose_name="Name",max_length=100, blank=True) logo = models.URLField('Logo', null=True, blank=True) class Itemised_Loyatly_Card(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE) add_points = models.IntegerField(name = 'add_points', null = True, blank=True, default=0) use_points = models.IntegerField(name= 'use_points', null = True, blank=True, default=0) Views from django.db.models import Sum, F def user_loyalty_card(request): itemised_loyalty_cards = Itemised_Loyatly_Card.objects.filter(user=request.user.id).values('venue').annotate(add_points=Sum('add_points')).annotate(use_points=Sum('use_points')).annotate(total=F('add_points')-F('use_points')) return render(request,"main/account/user_loyalty_card.html", {'itemised_loyalty_cards':itemised_loyalty_cards}) Templates {%for itemised_loyatly_card in itemised_loyalty_cards %} <img"src="{{itemised_loyatly_card.venue.logo}}"> {{itemised_loyatly_card.venue}} {{itemised_loyatly_card.total}} {%endfor%} Renders -
Get objects where (val1, val2) both in (other_val1, other_val2, ...)
Given the models below class Language(models.Model): name = models.CharField(max_length=255, unique=True) class Profile(models.Model): languages = models.ManyToManyField(Language) class Job(models.Model): language1 = models.ForeignKey( Language, models.CASCADE, related_name='language1' ) language2 = models.ForeignKey( Language, models.CASCADE, related_name='language2' ) If a profile has n languages, usually 2 or more, I need to get the jobs matching these languages in a way that both language1 and language2 are present in the language-user table. The models above generate app_profile, app_job, app_language and app_profile_languages. Below is the query I need to convert to orm: with user_languages as (select language_id from app_profile_languages where profile_id = 6) select * from app_job where language1_id in (select * from user_languages) and language2_id in (select * from user_languages) Here's a sample input and output app_language id name 1 English 2 German 3 Russian 4 Chinese app_job id language1_id language2_id 1 1 4 2 3 2 3 2 3 app_profile_languages id profile_id language_id 1 1 2 2 1 3 3 2 2 4 2 4 If profile_id = 1 is selected, this would be the expected output id language1_id language2_id 2 3 2 3 2 3 -
How do I display all the children of a parent in Django Rest Framework?
I have this model that is a reply to a post. But replies can also have replies and it can carry on forever. If I look at a reply I would like to see all its children and other information related to that specific reply like the user profile. Here is the reply model class Reply(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) video = models.FileField( upload_to=reply_videos_directory_path, null=True, blank=True ) body = models.TextField(max_length=256, default=None) parent = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="replies" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") class Meta: verbose_name = "post reply" verbose_name_plural = "post replies" db_table = "post_reply" def __str__(self): return self.body[0:30] and here is the serializer for the reply and I can get the information I need for the parent serializer but how do I pull in any children and further related information like the user profile, if there are any children of the reply? class ReplySerializer(serializers.ModelSerializer): images = ReplyImageSerializer(many=True, read_only=True, required=False) post = serializers.SerializerMethodField() profile = serializers.SerializerMethodField() post_images = serializers.SerializerMethodField() class Meta: model = Reply fields = [ "id", "post", "post_images", "video", "images", "body", "parent", "profile", "created_at", "updated_at", ] depth = 1 def get_post(self, obj): post_obj = Post.objects.get(id=obj.post.id) post … -
No Post matches the given query. django blog
everything is ok in the model but when I try to retrieve the object the error "No Post matches the given query." is shown. I don't know what is the problem that shows this error? **Model** class Post(CoreField): .... slug = models.SlugField(max_length=250, unique_for_date='publish') tags = TaggableManager() publish = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('news:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) **url** path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), **views** def post_detail(request, year, month, day, post): single_post = get_object_or_404(Post, publish__year=year, publish__month=month, publish__day=day, slug=post ) # List of active comments for this post comments = post.comments.filter(active=True) # Form for users to comment form = CommentForm() return render(request, 'news/post_detail.html', {'post': single_post, 'comments': comments, 'form': form}) when I remove the remove the "int:year/int:month/int:day/" form url it works. but when I pass the "int:year/int:month/int:day/slug:post/" it does't work. What is the proble and where it happens????