Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Didn't see any time difference in django async and sync view?
I'm new to django and async programming. So just for testing. I tried this code in django but I didn't see any any time difference. Sample code def sync_view(request): print('Called Sync View') start_time = time.time() context = dict() time.sleep(5) print('First time sleep') time.sleep(5) print('Second time sleep') print('Time Consumed', time.time()-start_time) return render(request, 'sync.html', context) async def async_view(request): print('Called Async View') start_time = time.time() context = dict() await asyncio.sleep(5) print('First time sleep') await asyncio.sleep(5) print('Second time sleep') print('Time Consumed', time.time()-start_time) return render(request, 'async.html', context) and here is console output. To setup async environment I followed this tutorials https://testdriven.io/blog/django-async-views/ Do i really need to use uvicorn in local environment? Here I'm using uvicorn in my local environment,so i used this command to start the server (env)$ uvicorn hello_async.asgi:application --reload and My last question. After releasing django3 do i really need django channels for chat application and django celery for running task in the background. -
Capture Image through Camera in the Website and Store the Path of Image in PGAdmin using Django
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>Capture Image From Camera</title> <meta name='viewport' content='width=device-width, initial-scale=1'> </head> <body> <video id="video" width="100" height="100" autoplay></video> <button id="snap">Snap Photo</button> <canvas id="canvas" width="100" height="100"></canvas> </body> <script> // Grab elements, create settings, etc. var video = document.getElementById('video'); // Get access to the camera! if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { //video.src = window.URL.createObjectURL(stream); video.srcObject = stream; video.play(); }); } // Elements for taking the snapshot var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var video = document.getElementById('video'); // Trigger photo take document.getElementById("snap").addEventListener("click", function() { context.drawImage(video, 0, 0, 100, 100); }); </script> </html> '''I have used this code to add a button which will open camera to take a snap.I have to store the path of the image in Pg-admin using Django.I am not able to do this.Please Help Me...''' -
Django OneToMany api
I am new in Django and Django-Rest-framework. I am following one Youtube Tutorial. He used static Django Template but I want to use React as my frontend. So I have create multiple api endpoints. In this particular Youtube episode I am stuck to display what kind of products specific customer bought. Short summary of my project is: I have four models: order, customer, product and tags(Product and tags have many to many relationships). In the order model I have two foreign key one is product and another one is customer. This is my order models [Looks like]. I don't know how to query and display what kind of products specific customer(by using id) bought. This is my models from __future__ import unicode_literals from django.db import models class Tag(models.Model): name= models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY=( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor'), ) name= models.CharField(max_length=200, null=True) price= models.FloatField(null=True) category=models.CharField(max_length=200,null=True, choices=CATEGORY) description= models.CharField(max_length=200,null=True, blank= True) date_created=models.DateTimeField(auto_now_add=True, null=True) tags= models.ManyToManyField(Tag) def __str__(self): return self.name class Customer(models.Model): name = models.CharField(max_length=200, null= True) email = models.CharField(max_length=20, null=True) phone = models.CharField(max_length=20, null=True) date_created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS =( ('Pending', 'Pending'), ('Out of delivery', 'Out of delivery'), ('Delivered', 'Delivered'), ) status= models.CharField(max_length=200, … -
How to add ChoceField to Django forms for regustration user
I am making a registration form for 3 types of users. When a user enters email and password he/she must select one of the roles. First I used BooleanFields and it works, but more than one checkbox can be selected. I need that user can select only one role. I have tried ChoiceField, which I could display on the template but it does not POST any data to db. forms.py class RegisterForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) parent = forms.BooleanField(label="I am a Parent") school = forms.BooleanField(label="I am a School Admin") vendor = forms.BooleanField(label="I am a Vendor") role_select=forms.ChoiceField( widget=forms.RadioSelect, label="Select your role.", choices=(('is_parent','parent '),('is_school','school'),('is_vendor','vendor')), ) if not parent and not school and not vendor: raise forms.ValidationError("Users must have a role") class Meta: model = User fields = ['role_select', 'parent', 'school', 'vendor', 'email'] #'full_name',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.role_select( self.cleaned_data['role_select']) # … -
Django redirect_url with parameter
I have a simple UpdateView which updates instances of my Profile model. class ProfileUpdateView(UpdateView): model = Profile fields = ['first_name', 'last_name'] It's working fine both GET and POST, but since the GET uses an url parameter, I want also the redirect_url to redirect to the updated profile. My current urls.py: from profiles.views import ProfileUpdateView urlpatterns = [ path('self/<slug:slug>', ProfileUpdateView.as_view(success_url='/'), name='self_profile') ] It is currently redirecting to the main url, but I don't figure out how to make the redirect_url parameter redirect to the profile modified on the handled POST. Let's say I do http://localhost:8000/profiles/self/demo, (GET), then I modify my first_name and submit the request. I want the redirection to go to /profiles/self/demo again. I know I could override def post() on the view and achieve it, but since I only want to deal with the redirection I wanted to know if exists any other elegant solution. EDIT: Additional info: the slug url parameter will always be request.user in this case (since I use other view (a DetailView) to see other users' profiles). Thanks!! -
ckeditor dosn't save files and dosn't appear in django admin panel
I'm trying to use Ckeditor and Django and follow django-ckeditor, but there are two problems here; when I import images(or other files) in CKEditor, it doesn't save anymore. in the Django admin panel, there is no editor space for edit content. setting.py INSTALLED_APPS = [ 'myapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader' ] ROOT_URLCONF = 'thisproject.urls' TEMPLATE_DIR= os.path.join(BASE_DIR,'media/template/') STATIC_ROOT = os.path.join(BASE_DIR,'statcifiles') CKEDITOR_BASEPATH = "/my_static/ckeditor/ckeditor/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'uploads/' urls.py from django.contrib import admin from django.urls import path,include from . import views from django.conf.urls import url, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/',include('myapp.urls')), path('',views.login,name='login'), url(r'^ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) models.py from django.db import models import datetime from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField class PrescriptionSheet(models.Model): Text=RichTextUploadingField() Date=models.CharField(max_length=20) here is my Django admin panel that CKEditor not appears: -
Customising the fields of drop-downs in Django w.r.t to conditions
I have a scenario where I have 2 drop-downs and the values of second drop-downs are based on the first drop-downs values. For example :- According to my implementation write now it appears to be 2 separate drop-downs drop-down1_value 1 drop-down1_value 2 drop-down1_value 3 drop-down2_value 1 drop-down2_value 2 drop-down2_value 3 drop-down2_value 4 What I want is the value should appear as drop-down1_value 1 drop-down2_value 1 drop-down2_value 2 drop-down1_value 2 drop-down2_value 3 drop-down2_value 4 so, basically the values of drop down 2 are dependent on the values of drop down 1. Internally the tables are connected but I am not able to display it as required. It has to be done something with Django forms as per my research but I am not able to do it. Any help will be really very helpful. -
How do I change a value in django on option click in HTML using Ajax-JavaScript?
I am trying to implement a function using Ajax-JavaScript in which when I click on Activate Option, the value in my Django database for this field changes to 'Active' and is displayed on the HTML page as active with Activate Message. If De-Activate is clicked, the text changes to De-Active along with it's value in the django database and show De-Activated message HTML page: <div class="col-sm-5"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Job activation status</h3> </div> <div class="panel-body"> <td> Campus Name </td> <td> hod_name </td> <td> <select name="status" class="form-control"> <option value="1">Active</option> <option value="2">Disabled</option> </select> </td> </div> </div> </div> Model: class Campus(models.Model): STATUS = ( ('Active', 'Active'), ('Disabled', 'Disabled'), ) campus_name = models.CharField(blank=True, max_length=30) hod_name = models.CharField(blank=True, max_length=25) status = models.CharField(max_length=10, choices=STATUS, default='Disabled', blank=True) def str(self): return self.campus_name -
Range slider to change function argument inn Django
I want to make a slider range that changes the value of an argument of a function I have a slider like this: <div class="slidecontainer"> <input type="range" min="0.5" max="2.5" value="1.2" step="0.1" class="slider" id="limit"> </div> It supposed to change the value "1.2" argument: def summarize (sentences, sentences_value, limit): ... summary = summarize(sentences, sentences_value, 1.2 * average_score) What can I do? Do i have to place the function in a views? Thank you -
'QuerySet' object has no attribute 'completed'
In my quiz app, every user can have multiple attempts. My model setup is as follows: class Quiz(models.Model): title = models.CharField(max_length=15) slug = models.SlugField(blank=True) questions_count = models.IntegerField(default=0) class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) label = models.CharField(max_length=1000) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=100) is_correct = models.BooleanField('Correct answer', default=False) class QuizTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) correct_answers = models.IntegerField(default=0) completed = models.BooleanField(default=False) attempt_number = models.PositiveIntegerField(default=0) I get the error in my serializer when I try to determine if a given quiz has been completed: class MyQuizListSerializer(serializers.ModelSerializer): questions_count = serializers.SerializerMethodField() completed = serializers.SerializerMethodField() progress = serializers.SerializerMethodField() score = serializers.SerializerMethodField() class Meta: model = Quiz fields = ['id', 'title', 'type_of_content', 'song', 'slug', 'questions_count', 'completed', 'score', 'progress'] read_only_fields = ['questions_count', 'completed', 'progress'] def get_completed(self, obj): try: quiztaker = QuizTaker.objects.filter(user=self.context['request'].user, quiz=obj) for attempt in quiztaker: return quiztaker.completed #the error comes from this line except QuizTaker.DoesNotExist: return None Can anybody tell me why I am getting this error? I am filtering because the user can have multiple attempts, therefore I get a queryset, and therefore I must loop through it. The QuizTaker model does have a completed field, so what is the issue? Here is the full traceback: Traceback (most recent … -
Adding multiple groups with django channels and websocket
I try to development a notificaiton system. I would like the system administrator to be able to send notifications to different groups. For this, I create only one websocket connection, and when socket is connected(during login) I want to add the user to the groups it belongs to. I wrote the code as below but I'm not sure it's correct. I am already getting this error: "AttributeError: 'WebSocketProtocol' object has no attribute 'handshake_deferred'" class MyConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: await self.close() else: groups = await sync_to_async(list)(self.scope["user"].channel_groups.all()) for group in groups: await self.channel_layer.group_add(group.name,self.channel_name) await self.accept() print("###CONNECTED") Can you help me? Am i on the right way? If so how do i fix this error? -
my s3 bucket to serve my static files in Django is not working
I am in production (Heroku) and this is my settings.py extracts and I use django-storages INSTALLED_APPS = [ ... 'storages', ] AWS_ACCESS_KEY_ID = 'key' AWS_SECRET_ACCESS_KEY = 'secret' AWS_STORAGE_BUCKET_NAME = 'bucket' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' My href for static <link rel="stylesheet" type="text/css" href="{% static 'app/css/base.css' %}"> my static files are located in my app/static/app_name/ When i view my source code in the server, the href is still pointing to my local thing which is my 'appname.heroku.com/static/app_name/css/base.css' (my logs say it's not found) instead of the typical amazon s3 CDN url ?? I have uploaded the 'myapp/static' file in my bucket. What am i missing?? I am sort of new to using s3.. please help, since its production, I am nervous about messing it up, that's why I am reaching out for help... -
what is the diffrence between (in the body) are in django 3.1
is it just me or other people don't understand the title because docs.djangoproject.com wasn't clear enough, so I'm just asking what the differences between <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> -
add form fields's data to existing model fields in Django
I have 2 models, CustomUser and Teacher. Teacher model has a OneToOneFields with CustomUser. models.py class CustomUser(AbstractUser): # some other fields # For Teacher teacher_type = models.CharField(max_length=50, choices=type_choice, blank=True) teacher_department = MultiSelectField(choices=department_choice, blank=True) teacher_year = MultiSelectField(choices=year_choice, blank=True) class Teacher(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) department = models.TextField() year = models.TextField() type = models.CharField(max_length=50) def __str__(self): return '%s %s %s %s' % (self.user.email, self.department, self.year, self.type) forms.py class TeacherRegisterForm(UserCreationForm): class Meta: model = CustomUser fields = ['teacher_type', 'teacher_department', 'teacher_year', ...] def save(self, commit=True): user = super().save(commit=False) user.is_teacher = True user.save() teacher = Teacher.objects.create(user=user) teacher_department_after = ', '.join(self.cleaned_data.get('teacher_department')) print(teacher_department_after) teacher_year_after = ', '.join(self.cleaned_data.get('teacher_year')) teacher.department += teacher_department_after print(teacher.department) teacher.year += teacher_year_after print(teacher.year) teacher.type += self.cleaned_data.get('teacher_type') print(teacher.type) return user When the CustomUser is created, the Teacher object is also created in this line teacher = Teacher.objects.create(user=user) Then, I got the data from CustomUser's fields and get rid of [] and double quotes because teacher_department and teacher_year are MultiSelectField and add these data into department, year, and type inside Teacher model by using += operation. teacher_department_after = ', '.join(self.cleaned_data.get('teacher_department')) teacher_year_after = ', '.join(self.cleaned_data.get('teacher_year')) teacher.department += teacher_department_after print(teacher.department) teacher.year += teacher_year_after print(teacher.year) teacher.type += self.cleaned_data.get('teacher_type') print(teacher.type) When I print out the teacher.department and other 2 fields, … -
Django web service stack and concepts questions
I need to develop a web service with RESTful API on Django. I would be grateful if someone could clarify a few questions and point me in the right direction. It has to connect to a remote database and perform long queries and then return the rows to a user (I plan on returning csv files) I chose Django as a framework, but I am a bit lost with all the things I read Since queries take a long time to finish , the service should somehow work in async. The async concept in regards to web services especially in connection to Django is really complicated to grasp. Would using new Django 3.x async features be enough for this task? I've read about Celery the queue manager that is supposed to provide some degree of parallelisation (am I correct on this?) I've also read about nginx + wsgi + Django. Should I go with that? In regards to nginx and other web servers. Am I correct in understanding that Django in itself can function as a web server, but nginx can be used to somehow better the performance of a Django application? Should I use "django rest framework" for the … -
FieldDoesNotExist at /accounts/signup/, User has no field named 'username'
I am using django allauth, and I am using an AbstractBaseUser, but anytime I click on Sign Up, it says Trace: C:\Users\user1\.virtualenvs\allauthtest-RfdvfJzX\lib\site-packages\django\db\models\options.py, line 577, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) FieldDoesNotExist at /accounts/signup/ User has no field named 'username' I have tried this article, but it doesn't seem to help me. In my AbstractBaseUser, i decided to use email, and not username. What should I do? Am I missing some options? models.py class UserManager(BaseUserManager): """ Custom User Model manager. It inherits from BaseUserManager, and has 3 functions, create_user(), create_staffuser(), and create_superuser() It requires email field. """ def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ return self._create_user(email, password, False, False, **extra_fields) def create_staffuser(self, email, password, **extra_fields): """ Creates and saves a staff user with the given email and password. """ user=self._create_user(email, password, True, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): """ Creates and saves … -
Other APIs are fetching normal, but some APIs takes time 2-5 minutes to get response, jquery Ajax fetches in milli seconds same APIs
I need to integrate ShipStation with my Python web app. ShipStation APIs are executing very slower by python requests package, taking time about 2-5 minutes. I also tried to fetch more heavier APIs which are fetching normally. I tested Shipstation APIs using jQuery Ajax, Postman and it's taking time in milliseconds, or 1-2seconds. What's wrong with requests library. Please help me. Samples: python example -- taking minutes 2-5 import requests # request header headers = { 'Authorization': '' } # shipstaion carrier services listing api endpoint list_services = 'https://ssapi.shipstation.com/carriers/listservices?carrierCode=stamps_com' # making get request res = requests.get(list_services, headers=headers) # results print("services_list: ", res, " and type is: ", type(res)) jQuery Ajax example taking milliseconds or 1-2 seconds: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> </body> <script> $.ajax({ url: 'https://ssapi.shipstation.com/carriers/listservices?carrierCode=stamps_com', headers: { 'Authorization': '' }, type: "GET", success: function(response) { console.log(response);//does not print in the console } }); </script> </html> -
Two Django Projects with One Database
I built a dashboard with Django that all my customers use. I want to build an internal dashboard for myself so that I can monitor their activity. It should connect to the same database as the dashboard. I have a a question about how to do this: Do I just add the same database in settings.py and re-define the models in the internal dashboard? Thanks! If there's a better way to do this, let me know! -
How to send time to model usinig django-admin commands?
I was wondering how can i send a time to django DateTimeField by a django-admin command class , and by time i mean the actual hour and minute not the date. thanks my django admin command class class Command(BaseCommand): def handle(self, *args, **kwargs): title = 'new new post' try: MyModel.objects.create( title=title, mytime= '???', ) print('%s added' % (title,)) except: print('error') my model class MyModel(models.Model): title = models.CharField(max_length=250) mytime = models.DateTimeField(null=True, blank=True) def __str__(self): return self.title -
How to define a polymorphic relation?
Working on project kinda Reddit, and I am stuck somewhere. I have Post and Group models as in Reddit, and everything works pretty fine, I mean that i can create a post and choose a group, but i want to implement something like in Reddit, when you create a post and you can choose where exactly you will post that(in your profile or in one of your groups). I heard that polymorphism can help with this, and did't find anything useful. Thanks for help My models: class Group(models.Model): title = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=500) class Post(models.Model): title = models.CharField(max_length=150, db_index=True) body = models.TextField(max_length=5000, blank=True, null=True) author = models.ForeignKey(User, related_name='posted_p', on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) -
Reverse for 'createActivity' with no arguments not found. 1 pattern(s) tried: ['create_Activity/(?P<pk>[^/]+)/$']
hope you are doing well! I am having this error Reverse for 'createActivity' with no arguments not found. 1 pattern(s) tried: ['create_Activity/(?P<pk>[^/]+)/$'] it's working for createSousActivity but for createActivity it doesn't work. this is my urls.py path('create_Activity/<str:pk>/', views.createActivity, name="createActivity"), path('update_Activity/<str:pk>/', views.UpdateActivity, name="updateActivity"), path('delete_activity/<str:pk>/',views.DeleteActivity, name="deleteActivity"), path('create_SousActivity/<str:pk>/', views.createSousActivity, name="createSousActivity"), path('update_SousActivity/<str:pk>/', views.UpdateSousActivity, name="updateSousActivity"), path('delete_Sousactivity/<str:pk>/',views.DeleteSousActivity, name="deleteSousActivity"), this is my views.py def createActivity(request,pk): sdlc = SDLC_phase.objects.get(id=pk) form = ActivityForm(initial={'sdlc':sdlc}) if request.method == "POST": form = ActivityForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request,'activitiestasks/Activity_form.html', context) in my template <a class="btn btn-outline-success btn-sm btn-block" href="{% url 'createActivity' SDLCphases.id %}">Create Activity</a> do anyone know this problem ? -
Django Background Tasks that execute only after DB table field update
I am using django background tasks package for scheduling my background tasks. I am dividing my tasks into 2 categories say A and B. Assume A have 50 tasks and B have 30 tasks. Initially, all 50 tasks of A should run asynchronously and have to complete. Once completed, those tasks update the db table field. Now B tasks should read the db table field values. If all A tasks marked completed, then B has to trigger asynchronously. Help me on how to achieve this. -
How to inherit 2 admin classes in one admin class Django?
How to inherit 2 admin classes in one model admin? This code works from modeltranslation.admin import TranslationAdmin from .models import Insurance class InsuranceCompanyAdmin(TranslationAdmin): list_display = ["name"] admin.site.register(Insurance, InsuranceCompanyAdmin) I want to something like this (however it doesn't work). I tried use proxy but it didn't help me. How can I inherit 2 admin classes? from import_export import resources from import_export.admin import ImportExportModelAdmin from modeltranslation.admin import TranslationAdmin from .models import Insurance class InsuranceSource(resources.ModelResource): """Ingredient Resource class for importing and exporting.""" class Meta: """Meta class""" model = Insurance skip_unchanged = True report_skipped = True exclude = ('id',) fields = ('name',) class InsuranceImportAdmin(ImportExportModelAdmin): """Ingredient import-export Admin interface""" resource_class = InsuranceSource list_display = ["name"] class InsuranceCompanyAdmin(TranslationAdmin): list_display = ["name"] admin.site.register(Insurance, InsuranceCompanyAdmin) admin.site.register(Insurance, InsuranceImportAdmin) -
Django Queryset filter equivalency to SQL
To me, it is not clear or lack of example code to understand the documentation about how SQL language is internally used in Django ORM. My intended SQL is: SELECT projects_category.id, projects_category.name, projects_project.name FROM projects_category JOIN projects_project_categories ON projects_category.id = projects_project_categories.project_id JOIN projects_project ON projects_project_categories.project_id=projects_project.id WHERE NOT projects_project.is_mini ORDER BY projects_category.id; How to do the same in Django ORM or in Django view? I have tried filter and exclude (probably with the wrong arguments...) and it does not seem working according to output. There might be more options besides these two. Also, any other tricks would be appreciable. -
Custom nested routes django
I have a model class ExampleModel(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) image = models.ImageField(upload_to='photos') title = models.CharField(max_length=30) kind = models.CharField(max_length=30) size = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) my view class Example(viewsets.ModelViewSet): serializer_class = ExampleSerialzer queryset = Example.objects.all() my serializer class ExampleSerialzer(serializers.ModelSerializer): class Meta: model = Example fields = '__all__' Now in my urls.py file I want to be able to do something like router = NestedDefaultRouter() example_router = router.register('example', views.ExampleView) example_router.register('category', views.ExampleView, basename='example_category' lookups=['kind', 'size']) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] My idea with this is that I would be able to go to a route like /api/example/category/:kind/:size/ where the kind and size gets specified by clicking a photo or something of that nature which is not important. Basically, I want to filter from my model by kind and size field but my code does not work