Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass multiple value from select element and pass to django views and print it in cmd
so i have a select element which i can append it depends on the user , i need to retrieve the multiple value(if the user need pick more than 1 options) and i need to pass it to django views after the user click submits #script to append box <script> function appendBox() { $('#test').append('<select class ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;margin-top:5px"></select>') } </script> #script to check wheter the multiple value that user choose is right <script> function passingval() { var inputs = $(".columnselect"); for(var i = 0;i<inputs.length;i++){ alert($(inputs[i]).val()); } } </script> #some snippet in my select element <div class="form-group"> <button class="btn btn-theme" onclick="appendBox()">Add</button> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4" id ="test"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> </div> #button <button class="btn btn-theme" onclick="passingval()" href="{% url 'polls:printvalue' %}">submit</button> #html in new page to make the option appear(because i use ajax) <option> -------------------- </option> {% for data in obj %} <option value="{{data}}">{{data}}</option> {% endfor %} urls.py urlpatterns = [ path('', views.login_view, name='login'), path('home/', views.index_view, name='indexing'), path('profile/', views.profile_view, name='profile'), path('chatroom/', views.chatroom, name='chat_room'), path('lockscreen/', views.lockscreen, name='lock_screen'), path('newsegment/', views.createsegment, name='newsegment'), path('definesegment/', views.list_all_table, name='definesegment'), path('manageuser/', views.manageuser, name='manageuser'), path('approvallist/', views.approvallist, name='approvallist'), path('approvalhistory/', views.approvalhistory, name='approvalhistory'), path('load-data/',views.list_all_tabledependent, name = 'load-data'), path('load-column/',views.list_all_column,name='load-column'), path('logout/',views.logout,name='logout'), path('definesegment/',views.printallvalue, name ='printvalue'), # … -
API state design pattern in python
as I understood, Is the following code sufficient for the attached question? please need your help to clarify the missing points or parts, should I add some exceptions catching, should edit_title & edit_description be only in the New class() or abstract in the TaskAPI class() and override it inside child classes , should i use the Django rest framework API, below the in-progress state is written 'link two tasks you should be able to call both of them using any id' what does that mean. # States of a Task class TaskAPI(object): """ Abstract base class of state of a task """ name = "state" allowed = [] def switch(self, state): """ Switch to new state """ if state.name in self.allowed: print('Current:', self, ' => switched to new state', state.name) self.__class__ = state # print( self.__class__) else: print('Current:', self, ' => switching to', state.name, 'not possible.') def __str__(self): return self.name class New(TaskAPI): """ New State being in progress """ name = "New" allowed = ['InProgress'] def edit_title(self,new_title): self.title = new_title def edit_description(self,new_description): self.new_description = new_description class InProgress(TaskAPI): """ State of being in progress after New state and need to switched to be done """ name = "InProgress" allowed = ['Done'] … -
Django: NullBooleanField value False not restored properly from MySQL Database
When I save a False value in a models.NullBooleanField in my database it is correctly stored as 0 in the DB. When reading it Django assigns None. Here is a small code snippet to reproduce: model.py: class Test(models.Model): foo = models.NullBooleanField() def __str__(self): return f'{self.foo}' test.py: from data.models import Test import subprocess def run(): print("created in Django:") for val in [None, True, False]: t = Test(foo=val) t.save() print(t) print("\nSQL from Database:") cmdResult = subprocess.getoutput("mysql -N -u user -ppass, -e 'select foo from data_test;' mydb") print(cmdResult) print("\nDjango read from Database:") for test in Test.objects.all(): print(test) and this is the result: created in Django: None True False SQL from Database: NULL 1 0 Django read from Database: None True None I would expect the last value to be False. I have also tried with a BooleanField with null=True. Since it is stated in the docs that this may be deprecated in future. Nevertheless the same error occurs. I also now how to workaround this problem using another field type. But I would like to understand where my mistake is. As this should be running as expected, shouldn't it? Thanks a lot for your time and hints. -
Is it possible to use my existing HTML/CSS/JS with a move to Django?
I'm working on a full stack web application for a class, and originally was going to use AWS S3 for hosting, Dynamo as a database, Lambda for passing data to and from Dynamo, and Gateway API to connect the front and back end, but have had nothing but issues with AWS. As this is just a class project, nothing needs to be remotely hosted, and a classmate suggested Django to allow us to completely ditch AWS. After looking through a lot of the introductory stuff for Django, it looks like it could be the magic bullet we need. However, we already have dozens of hours sunk into our frontend HTML/CSS/Javascript, as well as some Bootstrap. My only reservation about making a complete dive for Django for handling our database and enabling us to run everything off localhost is that it seems to do EVERYTHING in Python, and I don't immediately see any way to integrate our existing frontend. Our frontend JS is intended to receive data from the database and do rudimentary calculations with it before providing it to the HTML page, and I'm also not sure how this would integrate with Django and SQLite. -
How can I add custom fields when creating a sign up form using Django form?
I am very much a beginner to Django and just Python overall, but I am trying to create a relatively simple web app and I seem to be running into some obstacles. I would like to add custom fields to my Django UserCreationForm like first name, last name, email and ID number? Should I create a separate Profile model and if so how should I do that, or is there some other way to achieve this? Like I said, I am a beginner so I would appreciate as much detail as possible! -
Trying to update model data with ajax from DetailView?
I would like to do: I am trying to create a form input on a detail view that will update a particular data column ('status') of the detailed model instance. Here is a picture of what I have in mind: The selector would display the current status and the user could change it and update from the detail view without having to access the UpdateView. my idea here would be to have this happen: 1. On submit, get the new user entered value. 2. get the model instance of the currently detailed class 3. assign the model instance attribute as the user entered value 4. save the model instance I've tried: I don't know if this is the best way to do this but i've been trying to create an AJAX call, mostly by looking for examples online. Results: Terminal shows Post on submit: "[19/Nov/2019 17:50:33] "POST /task/edit/4 HTTP/1.1" 200 41256". However, the data is not saved to the db. On refresh, the selector returns to previously saved status. The console shows: "script is connected", and "Update Status" with no errors. On submit, the alert displays success message: "127.0.0.1:8000 says status updated". Task_detail.html <div class="deliv-box edit"> <form id="status-update-form" method='POST' action='{% … -
Why is a CSS file not changing the colors of HTML tags on Django project?
I've been working on adding css styles to my django web project, but I noticed something odd I can't understand. My page is succesfully adding or removing a gif when I add it or remove it in my css file, but the color of my labels, for instance, doesn't change. This is my simple css file that works this way: li a { color: green; } body { background: white url("images/background.gif") no-repeat; } When in my browser, I can see if I delete the second statement, the gif no longer appears, but whether I delete or not the first one, all text is still black. I also tried this: h1 a, h2 a { color: #C25100; } But it works the same, it doesn't change any text, and the document has many different tags, and none is affected. I include the css in my html file like this: <link rel="stylesheet" type="text/css" href="{% static 'app_name/style.css' %}"> When I first figured it out, I had bootstrap linked too, but I removed it and it changed nothing. -
How to update a single field from modal form in Django?
I have a form that keeps track of when people enter/leave different areas. Whenever there is a discrepancy, for example, someone forgets to "leave" an area before entering a new one, the user is prompted an "estimate" of the time they believe they left the previous area at(edited_timestamp). The only two required fields on the main form are the employee number and the work area, as these are used to verify/keep track of data. When I try to reproduce the situation that would make the modal show up, it works, but when I attempt to submit it, I get these messages: and these are the errors that are being returned. Now, while I don't understand why the "Enter valid date/time" error is showing, I'm guessing the other two errors are due to the main form requiring the employee_number and the work_area and probably for this request, even though it is updating by the ID, it still wants the other two fields. I guess my question is, how could I modify this so that these two fields are not required for the modal? models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, … -
atomic requests in django form
I'm trying to implement atomic requests in CreateView, so I can check how many times users entered given code, so if they satisfy the condition they will be redirected to success page if not redirect to try again page, currently doing something like this: class IpadCodeView(CreateView): model = IpadCode form_class = IpadCodeForm template_name = 'giveaway/index.html' @transaction.atomic def form_valid(self, form): if form.is_valid(): instance = form.save(commit=False) if instance == COUNT_GAP: instance.save() return HttpResponseRedirect('success') else: return HttpResponseRedirect('you-lose') First time doing this, so does it make sense to use atomic transactions in form like this? -
deleting a user django rest framework knox
users are able to create an account and login. How would users be able to delete their own account? thought I would be able to do it with a delete request with the token. would i need to make another viewset for deleteAccount so users can remove their account by using the token? Currently use knox token authentication serializer from rest_framework import serializers from django.contrib.auth import authenticate from django.contrib.auth import get_user_model User = get_user_model() # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( validated_data['username'], validated_data['email'], validated_data['password']) return user # Login Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") viewset from rest_framework import generics, permissions, viewsets from rest_framework.response import Response from knox.models import AuthToken from users.models import User from .serializers import UserSerializer, RegisterSerializer, LoginSerializer # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Login … -
django postgresql CASE types interval and integer cannot be matched
In Django I'm creating a queryset query with annotation. This is part of it: days_calc = Case( When(Q(received_date__isnull=True), then=ExpressionWrapper(timezone.now().date() - F('due_date'), output_field=DurationField())), ) The query that it creates looks like this (the relevant part)- WHEN "item"."received_date" IS NULL THEN ('2019-11-19' - "item"."due_date") And I get this error: ERROR: CASE types interval and integer cannot be matched LINE 51: ...item"."received_date" IS NULL THEN ('2019-11-1... ^ What am I doing wrong? They are both dates (item.due_date is of type models.DateField). I noticed that if I'm using timezone.now() instead of timezone.now().date() it works, but then I get the value not in the required format. -
Django Database Structure for Time Series Data?
I am developing an app that allows users to choose an ocean buoy and then explore its historical time series data via interactive plotly plots. My end goal is that the user can input a location, which then loads a buoy's data, and the user can then choose filters for which data they'd like to have plotted (so basically a dashboard). For example, maybe they'd like to view only swells that were larger than 1 ft and occurred in the month of August. I know how to do this using pandas and plotly, but I'm struggling with how to transfer this to a django database framework. The code currently creates a buoy object that has a data attribute. This data attribute is a dictionary that is structured as follows: {'stdmet':{'meta':{dictionary of metadata}, 'data':[pandas dataframe of time series data]}} I have the data in a pandas dataframe as it allows me to easily manipulate and create plotly interactive plots. My question is how should I save this to a django model? I think I should have a buoy class which has fields for the meta data (e.g., buoy ID, lat/lon, etc.) and then I'd like to have a final field for … -
strange error with serializer and the json response
I have a profile model that I serialize and set fields using "all". The problem is that when I run it, I get the error that: AttributeError at /api/accounts/profile/ 'User' object has no attribute 'following' I tried setting the fields manually and get the same error, but when I remove following from the field it runs properly and I get the normal JSON response, but all the fields show null instead of the data I set in the admin panel. { "pk": 2, "date_of_birth": null, "bio": null, "profile_photo": null, "sex": null, "type_of_body": null, "feet": null, "inches": null, "lives_in": null } below is the code to the rest of the app models.py class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True) date_of_birth = models.DateField(blank=True, null=True, verbose_name="DOB") bio = models.TextField(max_length=500, null=True, blank=True) profile_photo = models.CharField(blank=True, null=True, max_length=300) sex = models.CharField(max_length=1, choices=SEX, blank=True, null=True) type_of_body = models.CharField(max_length=8, choices=BODYTYPE, blank=True, null=True) feet = models.PositiveIntegerField(blank=True, null=True) inches = models.PositiveIntegerField(blank=True, null=True) lives_in = models.CharField(max_length=50, blank=True, null=True) updated_on = models.DateTimeField(auto_now_add=True) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' read_only_fields = ('pk', 'user', 'following', 'height') views.py class CurrentUserProfileAPIView(APIView): permission_classes = [IsAuthenticated] def get(self, request): serializer = ProfileSerializer(request.user) return Response(serializer.data) urls.py urlpatterns = [ … -
I want add two annotation for two foreign keys using Django. How do I do this?
# models.py from django.db import models class Elephant(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) families = models.ForeignKey(Families, on_delete=models.CASCADE) def add_families_and_locations_counts(elephants): return elephants.annotate( families_number=Count('families'), location_number=Count('location') ) # Run output = add_families_and_locations_counts(elephants) In the above, the counts are incorrect. How do I get the correct counts? -
Is there an REST API where i can send a POST and make a comment in a TripAdvisor Profile?
I'm developing a personal project where I must publish a comment in a Tripadvisor profile. According to the TripAdvisor's Rest API, there is no endpoint for me to make a POST. Is there a generic API REST that allows this functionality? Or has anyone in this community been able to solve this? I'm developing my project in Django Thanks! -
How to Query search model with key words Django? (Current dropdown)
I have multiple models in Django that hold hundreds of different fields. One of which describes a uniform class Uniform(models.Model): category = models.CharField(max_length = 50) description = models.CharField(max_length = 50) price = models.FloatField(max_length = 6) size = models.CharField(max_length = 10) def __str__(self): return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price) And a transaction model which inherits from the uniform class Transaction(models.Model): employee_id = models.ForeignKey(Employee, on_delete = models.PROTECT) uniform = models.ForeignKey(Uniform, on_delete = models.CASCADE) date = models.DateTimeField(default=timezone.now) def __str__(self): return '{}: {} - {}'.format(self.employee_id, self.uniform, str(self.date)) There are hundreds of different uniforms I have loaded into the SQLite Db that connects to a form class TransactionForm(forms.ModelForm): class Meta(): model = Transaction fields = '__all__' Right now the current query is a HUGE dropdown and the user must scroll through the uniform options to record the right uniform as a transaction How can I query the uniform as a search on the user side, rather than it being a dropdown? I have seen queries done within the app, and qutocomplete-light package, but the package isn't readable as a module, and even installed on my machine. I have gone through different query sets, but trouble implementing the form as a search, … -
Django LDAP3 security with TLS: am I secure?
I'm concerned the login with LDAP in my Django app is not secure. After trying several methods, I was able to get a working custom backend using ldap3. I was advised by other programmers (unfortunately non-Django programmers) in my organization to use TLS, but when I make a connection with ldap3, it looks like it's not using TLS. I'm new to LDAP and security, but I've tried to do as much reading as possible, so hopefully I'm not missing something obvious. Based on the ldap3 documentation, and trial-and-error, it seems that the connection has to be bound (conn.bind()) before TLS can be started (conn.start_tls()). Is this true? If the connection is bound without TLS, is this exposing a vulnerability? If so, what's the point of start TLS after the connection? Am I using ldap3 and TLS correctly? Is this login method insecure, exposing passwords? #backends.py import ldap3 import ssl class LDAPBackend(ModelBackend): def authenticate(self, request, username=None, password=None): server = ldap3.Server('ldap://<url>', use_ssl=True) conn = ldap3.Connection(server, user=request.POST.get('username'), password=request.POST.get('password')) try: conn.bind() conn.start_tls() search_filter = '(&(objectClass=user)(userPrincipalName='+request.POST.get('username')+'))' conn.search(search_base='<search terms>', search_filter=search_filter, search_scope='SUBTREE', attributes='*') attrs = conn.response[0]['attributes'] username = attrs['userPrincipalName'] except: return None If I switch the conn.bind() and conn.start_tls() order (so TLS starts first), the login fails … -
Getting the same output in Gunicorn as runserver
I'd like to use gunicorn in dev just to have as close to production an environment as possible. I really like the output though of runserver: I'm launching gunicorn with: gunicorn -b :5000 --log-level debug config.wsgi:application Which has a mess of information, but not what runserver includes. Is there a setting in either gunicorn or django I should be looking at to get it to have similar output as runserver? -
Django: logging messages from raised exceptions in REST API
I'm using Django REST Framework for a simple API. I have the following custom exception that subclasses DRF's APIException: class BadRequest(APIException): status_code = 400 default_detail = 'Invalid request' default_code = 'bad_request' The project uses the following logging setup: LOGGING = { 'handlers': { 'log_to_file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', } }, 'loggers': { # "catch all" logger '': { 'handlers': ['log_to_file'], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['log_to_file'], 'propagate': False, 'level': 'INFO', }, } Now if I test the exception handling with this view: @api_view(['GET']) def hello_world(request): raise BadRequest('test') I correctly get a 400 response with a {'detail': 'test'} JSON, but the log file contains only: 2019-11-19 [django.request] ERROR: Internal Server Error: /api/hello [in log.py:228] How can I get it to display the actual exception message (test) in the log file? Note that this is the behavior I get when DEBUG = False. -
Python django 'QueryDict' object has no attribute 'subject'
Hola que tal escribo aquí porque no se como solucionar mi problema, resulta que estoy creando un portal de pruebas en linea y necesito saber que estoy fallando, explico el contexto al momento de crear una pregunta se debe indicar un indice de evaluación, y este tiene un filtro que va de acuerdo la asignatura y curso de la prueba en cuestión. Bueno el filtro funciona me muestra los indicadores que son de un curso y asignatura en especifico, pero solo cuando le ingreso un id manual en cambio cuando le paso las variables del quiz este me tira el error: 'QueryDict' object has no attribute 'subject'dejo el codigo del form y la vista para que me puedan decir en que estoy fallando porfavor. forms.py class QuestionForm(forms.ModelForm): class Meta: model = Question context_object_name = 'questions' fields = ('number','planificacion','text','description', 'puntaje' ,'image','document' ) label = 'Pregunta' def __init__(self ,quiz ,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['planificacion'].queryset = PlanificacionIndicador.objects.filter(planificacion__asignatura__id=quiz.subject.id, planificacion__curso__id=1) Como se logra apreciar en el filter que hice el planificacion__curso__id=1 tiene una id puesta de manera manual y la otra tiene como quiero, debo decir que el filtro funciona lo que falla es que al momento de querer guardar me tira el error. view.py … -
Sending a Base64 to Backend using Ajax ---- Django receiving just part of the data sent by ajax
I made a simple Konva Js app that draws on a image, and i intend to send the image in base64 to the backend were i will decode it and store it, but i have a problem the backend is only receiving part of the data Can you guys help me out, Thanks in Advance !!! The Base64 is working on the Javascript side Javascirpt and Ajax document.getElementById('save').addEventListener( 'click', function () { var imagesrc = stage.toDataURL(); console.log(imagesrc) $.ajax({ url: '', data: { 'imagesrc': imagesrc }, type: 'POST' }).done(function (response) { console.log(response); }); } Django View @csrf_exempt def project_chapter_drawing_view(request, id, pk, name): project = get_object_or_404(Project, id=id) chapter_project = get_object_or_404(Chapter_Project, pk=pk) chapter = get_object_or_404(Chapter, name=name) try: chapter_menu = Chapter_Project.objects.filter(project__id=id).order_by('chapter__theme__name') except Chapter_Project.DoesNotExist: chapter_menu = None if request.method == 'POST': form = Plant_Drawn_Form(request.POST, request.FILES, instance=chapter_project) if request.is_ajax(): image = request.POST.get('imagesrc') print(image) image_data = base64.b64decode(image + "===") image_drawn = ContentFile(image_data, 'stage.jpg') chapter_project_plant = form.save(commit=False) chapter_project_plant.plant_image_drawn = image_drawn chapter_project_plant.save() else: form = Plant_Drawn_Form() return render(request, 'project-chapter-drawing.html', {'project': project, 'chapter_project': chapter_project, 'chapter_menu': chapter_menu, 'form': form, 'chapter': chapter}) ) -
Django REST with SPA - what structure
Django REST with SPA "within" or completely stand alone? I'm diving into a new project where I'll try to build a SaaS web application and I've set on using Django Rest (with Postgres to utilize schemas) and React/Vue on the frontend. What I'm unsure and what I can't seem to get an answer to is the way people structure these frameworks. E.g, on https://www.valentinog.com/blog/drf/ the author writes: /// I see the following patterns (which are common to almost every web framework): React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium) Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication) Mix and match: mini React apps inside Django templates (difficulty: simple) And here are my advices. If you’re just starting out with Django REST and React avoid the option 2. Go for option number 1 (React in its own “frontend” Django app) if: you’re building an app-like website the interface has lot of user interactions/AJAX you’re fine with Session based authentication there are no SEO concerns you’re fine with React Router /// Why is this beneficial, and is it actually … -
Why threads stopped in heroku?
I have been uploaded my project in heroku, and my script create 4 threads, each thread perform specific task, but sometimes log file tells me that some threads stopped like this, (Thread 13)! How can I solve it? this is the code! segmentationProcess = SegmentationProcess() dataList = request.body.decode("utf-8").split(',') data = segmentationProcess.preProcess(dataList) lock = multiprocessing.Lock() thread1 = ThreadWithLogAndControls(target=segmentationProcess.searchWorkExperience, args=(data, "W", manager.result, lock)) thread2 = ThreadWithLogAndControls(target=segmentationProcess.searchEducation, args=(data, "E", manager.result, lock)) thread3 = ThreadWithLogAndControls(target=segmentationProcess.serchSkills, args=(data, "S", manager.result, lock)) thread4 = ThreadWithLogAndControls(target=segmentationProcess.searchOthers, args=(data, "O", manager.result, lock)) thread1.start() thread2.start() thread3.start() thread4.start() thread1.join() thread2.join() thread3.join() thread4.join() Am using nbmultitask library for creating threads, it's like multiprocessing. https://github.com/micahscopes/nbmultitask -
How to override values on submission to update a field from a modal in Django?
I have a form that keeps track of when people enter/leave different areas. Whenever there is a discrepancy, for example, someone forgets to "leave" an area before entering a new one, the user is prompted an "estimate" of the time they believe they left the previous area at(edited_timestamp). The only two required fields on the main form are the employee number and the work area, as these are used to verify/keep track of data. When I try to reproduce the situation that would make the modal show up, it works, but when I attempt to submit it, I get these messages: and these are the errors that are being returned. Now, while I don't understand why the "Enter valid date/time" error is showing, I'm guessing the other two errors are due to the main form requiring the employee_number and the work_area and probably for this request, even though it is updating by the ID, it still wants the other two fields. I guess my question is, how could I modify this so that these two fields are not required for the modal? models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, … -
Django view works for only one url ,despite the appropriate queryset being generated in the view
I am trying to access a lesson belonging to a course in my application. When I use the url http://127.0.0.1:8000/courses/1/lessons/1/" the appropriate results get returned. However when I try anyother url such as "http://127.0.0.1:8000/courses/1/lessons/2/" I get an error instead Result for http://127.0.0.1:8000/courses/1/lessons/1/ { "id": 1, "title": "course 1 lessson 1", "owner": 1, "course": 1 } Expected Result for http://127.0.0.1:8000/courses/1/lessons/2/ { "id": 1, "title": "course 1 lessson 2", "owner": 1, "course": 1 } actual result { "detail": "Not found." } URL path('courses/<int:pk>/lessons/<int:lpk>/', LessonDetail.as_view()), Serializer class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ['id','title','owner','course'] view class LessonDetail(generics.RetrieveUpdateDestroyAPIView): # queryset = Lesson.objects.all() serializer_class = LessonSerializer def get_queryset(self): # GET PK FROM URL USING KWARGS course_pk = self.kwargs['pk'] lesson_pk = self.kwargs['lpk'] qs = Lesson.objects.filter(course_id=course_pk,id=lesson_pk) print(qs) return qs model class Lesson(models.Model): title = models.CharField(max_length=150, help_text='Enter course title') video = models.CharField(max_length=150, help_text='Enter course title', null=True) thumbnail = models.CharField(max_length=150, help_text='Enter course title', null=True) pub_date = models.DateField(null=True, blank=True) course = models.ForeignKey('Course', on_delete=models.CASCADE,related_name='lessons') description = models.TextField(max_length=1000, help_text='Enter a brief description of the course') owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) The view returns the object <QuerySet [<Lesson: course 1 lessson 1>]> for http://127.0.0.1:8000/courses/1/lessons/1/ and <QuerySet [<Lesson: course 1 lessson 2>]> for http://127.0.0.1:8000/courses/1/lessons/2/. To my inexperienced eye, it looks as …