Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'a user with that username already exists' is not in Django UserCreationForm anymore?
I'm studying Django and have come across a question. In several of the Django Youtube Tutorials, I see the Youtuber using the UserCreationForm to create teh signup page and then experimenting with the form to show the viewers about the page. And there comes a time when they signups a user with perhaps a username "test1" and then tries to signup a user with the same username as "test1" and they get the error message 'a user with that username already exists' However, when I've followed these tutorials, I see that there is no error message appearing anymore and it just pops up the original UserCreationForm again in the webpage. Is this error message removed? And I've been looking through the Django Github files and the Django Documentation, but it doesn't mention anything about the username error, so... I'm thinking that it's removed, but I want to be sure. -
Django: Is it possible to add fieldset to ModelForm?
I've read Django doc and post here but could not find how to add fieldset in Django? It is possible in Django admin but doesn't seems to be the case for ModelForm (and other Django forms)... Is there an easy way? -
How and where to deploy deep learning models, as an Webapp or API ? Need complete suggesion for a beginnier
I have created a deep learning model using TensorFlow/PyTorch, and now I want to deploy it both as an Webapp and API(I guess The webapp will also use the API) To explain, suppose I have a model that detects cars, in images, and returns the co-ordinates, around the bounding box.Or it might might return the image I sent, but after drawing bbox around the cars. What things do I need to learn, better if they are related to python.(I know the webapp part would need JavaScript, but apart from that, for the backend work what do I need to learn)? I don't have clear idea about where to host the model, or how to keep it running, can I do it using Flask or Django? Where can I deploy the model? How much will it cost? Is there any free service for the deployment? I have heard about HeRoku, but not sure if its free tire will cover my requirements. Can you provide any good source(free) , where I can learn machine learning model deployment in detail.(Video or blog, both are welcomed) I believe the question is quite popular for those who want to move from playing with deep learning … -
Django ModelForm how to remade a datetime after splitdatetime before saving data
I am trying to make a beautiful form with Modelform on django. My model have three datetime. I would like the user to be able to fill them in easily on the form. I managed to get the desired display but I can't save the data as I wanted to, an error occurs. I know that this error comes from the SplitDateTimeWidget which gives me two data (date and time). I can combine both in the model but I don't know how to do it. This is my form in Frenchglish: my form This is my error in general terms: my big horrible error This is my model: DEVICE_CHOICE=[("Lucas Nuelle","Lucas Nuelle"),("Objet260 Connex3","Objet260 Connex3"),("uprintp51225","uprintp51225"),("Yumi","Yumi")] class Delay(models.Model): delayDevice=models.CharField(max_length=100,choices=DEVICE_CHOICE) orderRef=models.CharField(max_length=100,default="not known",blank=True) orderDate=models.DateTimeField(blank=True) predictedDate=models.DateTimeField() deliveryDate=models.DateTimeField() delayComment=models.CharField(max_length=500,default="no comment",blank=True) submitDate=models.DateTimeField(auto_now_add=True) ``` This is my views.py: ``` from .models import Delay,Breakdown,NonComplyingProduct from .forms import ReportDelay,ReportBreakDown,ReportNonComplyingProduct def index(request): if request.method=="POST": form=ReportDelay(request.POST).save() return redirect("/report") else: form=ReportDelay return render(request,'delayForm.html',{'form':form}) and so finally my form.py: from .models import Delay, Breakdown, NonComplyingProduct import datetime as dt class ReportDelay(forms.ModelForm): class Meta: model = Delay fields = ['delayDevice', 'orderRef', 'orderDate', 'predictedDate', 'deliveryDate', 'delayComment'] labels = { 'delayDevice': 'Appareil', 'orderRef': 'Reference de la commande', 'orderDate': 'Date de la commande', 'predictedDate':'Date de livraison prévue', 'deliveryDate':'Date de … -
"Media" folder not being created with Django's FileSystemStorage. Files don't get saved if made manually either
So, I always test out new things in a separate project and the example that I used to test this out worked. However, trying to integrate the same in my project doesn't give me the results I need. I've spent close to 4 hours on this now and nothing so far. First off, here's the code: index.html <form id="data" enctype="multipart/form-data"> <div class="col-md-4"> <label class="file"> <input type="file" id="file1" name="document" multiple> <span class="file-custom">Documents</span> <button type="button" onclick="enterdata()">Submit</button> </div> </form> <script> function enterdata(){ if ($"data")[0].checkValidity(){ alert('validity success'); var token = ''{{ csrf_token }}; alert('csrf generated'); $.ajax({ type:'POST', url:'/user', data: { doc1:$('file1').val() }, header: {'X-CSRFToken': token}, success: function(){ alert("Added"); $('#data').trigger("reset"); } }) }else{ $('data')[0].reportValidity() } } </script> views.py def testing_data(request): if request.method == 'POST': doc11 = request.POST['doc1'] request_file = request.FILES['document'] if 'document' in request.FILES else None if request_file: # save attatched file # create a new instance of FileSystemStorage fs = FileSystemStorage() file = fs.save(request_file.name, request_file) # the fileurl variable now contains the url to the file. This can be used to serve the file when needed. fileurl = fs.url(file) landform.objects.create ( mutdoc=doc11, ) return HttpResponse('') models.py class landform(models.Model): mutdoc = models.CharField(max_length=255) urls.py urlpatterns = [ path('user', testing_data), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root … -
Django localhost refusing connection from another django localhost
I have two django applications, currently running on localhost. I plan to have them on two separate servers, but for now, they are running on my machine. App A is running on :8000 App B is running on :8010 When I try to make a request from A to B by using: import requests requests.post('http://0.0.0.0:8010/api/plan', data=post_data) I get a connection error: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='0.0.0.0', port=8010): Max retries exceeded with url: /api/plan (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f82fed36630>: Failed to establish a new connection: [Errno 111] Connection refused',)) In my B app I have ALLOWED_HOSTS = ['*'] Anyone has any idea what am I missing? -
postgresql: Invalid data directory | Can't open PID file /var/run/postgresql/10-main.pid (yet?) after start: No such file or directory
This error is showing after running this command: sudo systemctl status postgresql@10-main.service postgresql@10-main.service - PostgreSQL Cluster 10-main Loaded: loaded (/lib/systemd/system/postgresql@.service; indirect; vendor preset: enabled) Active: failed (Result: protocol) since Tue 2020-12-01 14:21:40 UTC; 2s ago Process: 1603 ExecStart=/usr/bin/pg_ctlcluster --skip-systemctl-redirect 10-main start (code=exited, sta Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 systemd[1]: Starting PostgreSQL Cluster 10-main... Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 postgresql@10-main[1603]: Error: Invalid data directory Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 systemd[1]: postgresql@10-main.service: Can't open PID file /va Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 systemd[1]: postgresql@10-main.service: Failed with result 'pro Dec 01 14:21:40 ubuntu-s-1vcpu-2gb-sgp1-01 systemd[1]: Failed to start PostgreSQL Cluster 10-main. Here is the content of /etc/postgresql/10/main/postgresql.conf file: # ----------------------------- # PostgreSQL configuration file # ----------------------------- # # This file consists of lines of the form: # # name = value # # (The "=" is optional.) Whitespace may be used. Comments are introduced with # "#" anywhere on a line. The complete list of parameter names and allowed # values can be found in the PostgreSQL documentation. # # The commented-out settings shown in this file represent the default values. # Re-commenting a setting is NOT sufficient to revert it to the default value; # you need to reload the server. # # This file is read … -
Django Only non-relations and foreign keys permitted
I'm trying to create a script here that looks at my staff table list that analyzes staffs email addresses and compares it to the login names in the system to assign them to their classrooms, but my script keeps on crashing. What's the goal ? The goal is I have a table called sections, sections are classrooms . Each classroom has a teacher assigned to them. However, in order for the teacher to see the classrooms they are assigned to, im linking this by the users login name which is their email address. However, although my logic from a print statment does work on my queries, it fails on updating the many to many fields. Here is my code. FUNCTION def AssignLoginToSection(): users = User.objects.all() for user_email in users: email = user_email.email print('Getting Email addresses in system.') if Section.objects.filter(staffpsid__email = email): section = Section.objects.filter(staffpsid__email = email) print("Found Matching Login Name.") print('The following sections were found with this users email.', section) Section.objects.filter(staffpsid__email = email).update(teacher_username= email) print('Added user login name to section.') else: print("No matching login name.") return("Done") MODELS # Section Information Stored class Section(models.Model): sectionpsid= models.CharField(primary_key = True, default = "", max_length = 50) schoolpsid = models.ForeignKey(School,on_delete = models.CASCADE, default = … -
Python, Django: Unique combinations inside a models.py-class?
Good afternoon, I would like to ask, if there's a way to define a unique combination inside my django-model? For example: class Example(models.Model): value_01 = models.Foreignkey(xyz, null=False, blank=False, on_delete=models.CASCADE) value_02 = models.Charfield(max_length=25, null=False, blank=False) Instead of making these two values unique on their own, is it possible to define a unique combination of these two values? Thanks a lot for you help and effort! -
How to post a list in django REST
I tried to get this: output { "counter": 2, "items": ["a", "a", "b", "c"] } serializers.py class OrderSerializer(serializers.ModelSerializer): items = serializers.ListField() counter = serializers.PrimaryKeyRelatedField(queryset=Counter.objects.all()) class Meta: model = Order fields = ['counter', 'items'] but I got this error: error Got AttributeError when attempting to get a value for field `items` on serializer `OrderSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Order` instance. Original exception text was: 'Order' object has no attribute 'items'. Should I create a variable in models.py called "items" because I tried it doesn't work either? -
Django IndexError at /viewissuedbookbystudent
so I happen to have this error while trying to run django projects. It saysIndexError at /viewissuedbookbystudent This was the project that I want to develop from https://github.com/sumitkumar1503/librarymanagement enter image description here Can anyone please help :) really need it.This is the viewissuedbookbystudent def, also I am very new at this so please help. def viewissuedbookbystudent(request): student=models.StudentExtra.objects.filter(user_id=request.user.id) issuedbook=models.IssuedBook.objects.filter(enrollment=student[0].enrollment) li1=[] li2=[] for ib in issuedbook: books=models.Book.objects.filter(isbn=ib.isbn) for book in books: t=(request.user,student[0].enrollment,student[0].branch,book.name,book.author) li1.append(t) issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year) expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year) #fine calculation days=(date.today()-ib.issuedate) print(date.today()) d=days.days fine=0 if d>15: day=d-15 fine=day*10000 t=(issdate,expdate,fine) li2.append(t) return render(request,'library/viewissuedbookbystudent.html',{'li1':li1,'li2':li2}) -
HTTP request function, indicates that there is no model attribute - DJango
I've implemented a model and a view function. The problem is that the function, which takes the http resquest, tells me that an attribute of the model does not exist. And I don't know what could be happening. views.py def home (request , data=None): #item.objects.filter(radius) items_area_location =item.objects.filter(radius<data) response = serialize('json', items_area_location) return HttpResponse(response) Models.py class item (models.Model): certificate=models.ImageField(default=None) provider = models.ForeignKey(serviceProvider, on_delete=models.CASCADE) radius = models.FloatField(default=None) description= models.TextField(blank = True) hour_init = models.TimeField() hour_end = models.TimeField() urls.py urlpatterns = [ path('admin/', admin.site.urls), path('home/<int:data>/', home, name='home'), ] This is what I get when there is a GET resquest with domain/home/somenumber: name 'radius' is not defined > NameError at /home/10/ name 'radius' is not defined Request > Method: GET Request URL: http://127.0.0.1:8000/home/10/ Django > Version: 2.2.12 Exception Type: NameError Exception Value: name > 'radius' is not defined Exception > in home, line 15 Python Executable: /usr/bin/python3 Python > Version: 3.8.5 Python Path: > ['/home/julian/Documentos/Programación/CallServiceBackEnd', > '/usr/lib/python38.zip', '/usr/lib/python3.8', > '/usr/lib/python3.8/lib-dynload', > '/home/julian/.local/lib/python3.8/site-packages', > '/usr/local/lib/python3.8/dist-packages', > '/usr/lib/python3/dist-packages'] Server time: Tue, 1 Dec 2020 > 13:46:46 +0000 -
Django is not sending an email
I'm currently making a Django website want to make sure that my user gets the email I sent but I get it in the console. Nothing is working. I'm using Django version 2.1.5 if it helps. Please help me!! Here is my code: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TDS = False EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' Again, please help!!!! -
How to use serializer inside serializer?
Now this is my plan: I want to be able to show followers for users,but i have a problem.I have to use nested serializers to show serializers which gives me this error: followers_set= UserSerializer(source='followers',many=True) NameError: name 'UserSerializer' is not defined``` Now i am using this kind of modelling in my API: Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE, related_name='followers') profile = models.ForeignKey(User,on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now=True) And here are my serializers: Serializers.py class UserSerializer(serializers.ModelSerializer): followers_set= UserSerializer(source='followers',many=True) class Meta: model = User fields = ('id','email','username','followers_set') How can i modify it in a way that it shows serializers inside serializer?? -
HOW TO FILTER BY BOOLEAN FIELD IN SEARCH BAR - DJANGO
I'm working on a Django Project that is a project management system. Basically in the navbar I've implemented a searcher to search for specific projects, the user can search for the title, the client, the description, ecc... I'd like to give them the possibility of searching also the projects that are urgent (urgent in my Project model is a boolean field), but the way I implemented it doesn't work. This is my Project Model: class Project(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=1000) client = models.ForeignKey(Cliente, on_delete=models.CASCADE) complete = models.BooleanField(default=False) urgent = models.BooleanField(default=False) deadline = models.DateField() ... To make the search bar (that in my html file is:) <form method="get" class="form-inline"> <input class="form-control mr-sm-2" name="q" id="id_q" type="text" placeholder="Search..." aria-label="Search" value="{{query}}"> <button class="btn btn-outline-dark my-2 my-sm-0" type="submit"> <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-search" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M10.442 10.442a1 1 0 0 1 1.415 0l3.85 3.85a1 1 0 0 1-1.414 1.415l-3.85-3.85a1 1 0 0 1 0-1.415z"/> <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zM13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0z"/> </svg> </button> work I've implemented this function: def get_projects_qs(proj, query=None): queryset = [] queries … -
password not geting hashed django rest framework
i'm using using customuser and trying to create user with drf but password not getting hashed. its returning raw password and because of that i can't use authentication its working with only user created by admin class CustomUserMananager(BaseUserManager): """ Custom user model manager where email will be unique identifier """ def create_user(self, email, password, **extra_fields): """ create and save user with given email and password """ if not email: raise ValueError(_('email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save superuser with given email and password """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('SuperUser must have is_staff=True')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('SuperUser must have is_superuser=True')) return self.create_user(email, password, **extra_fields) serializer: class CustomUserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp') def create(self, validated_data): return CustomUser.objects.create_user(**validated_data) views: @api_view(["POST"]) @permission_classes((AllowAny,)) def register(request): #permission_classes = [(AllowAny, )] serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): serializer.is_active = False user_otp = randint(999, 9999) otp_code = str(user_otp) email = request.data.get('email') send_mail( 'Otp verification', otp_code, 'jv', [email], fail_silently=False, ) serializer.save(otp=user_otp) return Response({'response': 'User registered successfully, … -
Django FilteredRelation is not working with GenericRelation
I have the following models: class Workspace(Model): pass class Event(Model): workspace = ForeignKey(Workspace) limit = FloatField(default=0) entity_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) entity_id = models.PositiveIntegerField() entity = GenericForeignKey('entity_type', 'entity_id') class Entity(Model): events = GenericRelation(Event, content_type_field='entity_type', object_id_field='entity_id') class Meta: abstract = True class SomeEntity(Entity): pass Now I need to build a queryset to sort objects of SomeEntity by the limit of their events inside a given Workspace The SQL query I'm hoping to have is something like this: SELECT "some_entity"."id", workspace_events."id", COALESCE(workspace_events."limit", 0) AS "limit" FROM "some_entity" LEFT OUTER JOIN "event" workspace_events ON ( "some_entity"."id" = workspace_events."entity_id" AND workspace_events."entity_type_id" = SOME_ENTITY_CONENT_TYPE_ID AND workspace_events."workspace_id" = GIVEN_WORKSPACE_ID ) ) ORDER BY "limit" DESC' Where: SOME_ENTITY_CONTENT_TYPE_ID is the content type id of the SomeEntity model. GIVEN_WORKSPACE_ID is the workspace id I want to filter the events on. The queryset I'm using is this: SomeEntity.objects.annotate( workspace_events=FilteredRelation('events', condition=Q(events__workspace_id=GIVEN_WORKSPACE_ID)), limit=Coalesce('workspace_events__limit', 0), ).values('id', 'workspace_events__id', 'limit').order_by('-limit') But the query I'm getting from the above queryset doesn't include the workspace condition in the join at all! SELECT "some_entity"."id", workspace_events."id", COALESCE(workspace_events."limit", 0) AS "limit" FROM "some_entity" LEFT OUTER JOIN "event" workspace_events ON ( "some_entity"."id" = workspace_events."entity_id" AND workspace_events."entity_type_id" = SOME_ENTITY_CONENT_TYPE_ID AND ) ) ORDER BY "limit" DESC' What am I doing wrong? Why … -
Staff user can't login to django admin panel
I am trying to create a custom user model in my django app. But Whenever I tried to do so, I can't login with "staff user" created by the "super user" from the admin panel. It says: "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitve." app name: Backend Backend/models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) # Create your models here. class UserManager(BaseUserManager): def create_user( self, username = None, email = None, password = None, is_active = True, is_staff = False, is_admin = False ): if not username: raise ValueError("Users must have a username") if not password: raise ValueError("Users must have a password") if not email: raise ValueError("Users must have a email") user_obj = self.model( username = username ) user_obj.email = self.normalize_email(email) user_obj.set_password(password) user_obj.is_active = is_active user_obj.is_staff = is_staff user_obj.is_admin = is_admin user_obj.save(using=self._db) return user_obj def create_staffuser(self, username, email, password): user_obj = self.create_user( username = username, email = email, password = password, is_staff = True ) return user_obj def create_superuser(self, username, email, password): user_obj = self.create_user( username = username, email = email, password = password, is_staff = True, is_admin = True ) return user_obj class User(AbstractBaseUser): … -
DRF - Custom Social Authentication
I want to ask a question about Social Auth WorkFlow. I was using simple JWT for my learning project and I wanted to add Social Auth which may work together with simple JWT. I searched and I found a lot libraries like allauth, python-social, social-app-django, drf-socialoath2 and etc. but they all were really complex to be honest to manage and customize so I decided to write my own direct way to authenticate with Facebook. In my code I am not keeping application secret in my backend and I am not using it at all. The procedure is as follow: Client click on "Sign in with Facebook" button and front-end gets access token from API call. No redirectURI Frontend send this access token to DRF Serializer validates the token and using python Facebook SDK, I check this token with Facebook If token is valid, I receive user information from Facebook. If user exists, authenticate it, if doesn`t, register with social password (which is really complex, long and is in environmental variables). After authenticating I send refresh, access token gotten from Simple JWT back to front end and remaining is same as before. It was really comfortable for me to do this … -
I want the data of the same row whose check box I will click.my table row is in for loop
I want the data of the same row whose check box I will click. my table row is in for loop and i want to display total price at end but it displaying all the boxes. And i have take the value by name in my views but here my form component are in for loop so if data is not there it should not come. here is my index.html: {% for j in package %} <tr class="valid-container"> <td style="cursor:pointer;"> <input type="checkbox" name="c1" id="c1">&nbsp; {{ j.visa_type }} </td> <td height="52"> <select class="custom-select processing_type" name="processing_type" data-id="{{ j.id }}" required> <option value="{{ j.price }}" selected>Normal</option> <option value="{{ j.express_price }}">Express</option> </select> </td> <td height="52"> <select class="custom-select no_of_person" name="no_of_person" data-id="{{ j.id }}" required> <option value="1" selected>1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </td> <td width="190" height="60"> <div class="input-group date" data-date-format="dd.mm.yyyy"> <div class="input-group mb-2"> <input type="text" class="form-control" name="travel_date" id="date" placeholder="dd.mm.yyyy"> <div class="input-group-text"><i class="ti-calendar"></i></div> <div class="input-group-addon"> </div> <div class="input-group-prepend"> </div> </div> </div> </td> <td>{{ j.currency_type }}&nbsp;&nbsp; <output name="result">{{ j.price }}</output>.00</td> </tr> {% endfor %} and this is my package.js: $('.valid-container').ready(function() { var date = $(this).find('#date').attr('required',true); $('select').on('change', function() { var id = $(this).data("id"); var … -
what number of apps is too much for django
I am working on a Django project which might have 20 apps in the end. I wanted to know how many apps a Django project can have. I am concerned about the speed of the project as it grows. -
What is the is_admin in Django?? and how is it different from is_staff?
I'm trying to make a custom user model in Django and was looking through the documents in the Django website and had some queries that I wanted to ask. There are explanations for is_superuser and is_active, is_staff and etc. However, I couldn't find the explanation for the is_admin. What is this is_admin and how is this different from is_staff? I'm guessing that it's kind of similar to the is_staff. This is found in the https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#a-full-example part, where you can see the user.s_admin=True -
How to import urls from apps in django main urls file
I have the following project structure. This is my INSTALLED_APPS array. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'climemanage.clients' ] Then I tried to add the clients.urls file in the parent urls file as the below. from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('clients/', include('clients.urls')) ] But I'm getting this error. ModuleNotFoundError: No module named 'clients' I can solve this by using the following path. include('climemanage.clients.urls') but I want to skip climemanage from the path. I have tried different ways as, import clients import climemanage.clients from climemanage import clients But nothing is working. -
Sending notification from Django Backend to Flutter application
I am implementing single device only login using django-rest-framework, but in order to log out the user from previously logged in device i want to send some notification from backend to frontend, in order to achieve this what would be the possible options present for django? -
DjangoRestFramework - How can I use 'pk' to filter a list?
I want to filter a list of BatchLog objects according to pk that I send through the request - which is their batch_id. Is there a way to access it on views.py file? I have this in my urls.py file path('feed/<int:pk>', GetFeedItemView.as_view()) And in my views.py file I want to access a BatchLog object by filtering its batch_id class GetFeedItemView(RetrieveAPIView): serializer_class = FeedSerializer def get_queryset(self): return BatchLog.objects.filter(batch_id=self.request.pk) This filter(batch_id=self.request.pk) doesn't work but I want to implement it in the same logic. How can I achieve this? Thanks a lot.