Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prometheus setup for a load balanced Django application
I have a doubt with respect to Prometheus setup for Django applications. If we have a load balancer which redirects to three application servers where the Django applications are running. Which of these setups will work and is optimally correct? Having Prometheus installed in one of the application servers and then having a job for every Django application that needs to be monitored. In this case, should we provide the host application details for all the application servers? Basic Prometheus setup Idea? Will installing Prometheus on any server and mentioning all the Django applications details in the targets entry in prometheus.yml file work? - Do we need to have ssh trust set up in this case when the setup has to be done like this? It will be very helpful if you guys please give some insights on this. If there is any other better way to configure Prometheus, please mention that as well. -
Email Problem Django: SMTP AUTH extension not supported by server
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' Just saying, this happens if I use the EMAIL_BACKEND = 'django.core.mail.backends.smpt.EmailBackend' method: SMTPNotSupportedError at /reset/ SMTP AUTH extension not supported by server. Again, please help!!!! -
NoReverseMatch at /api/users/request-reset-email/
This is not duplicate issue, I have already referred old question, but no answer was found. I am trying to implement rest password functionality using Django rest framework. But I am getting below error.. Reverse for 'api/password_reset_confirm2' with arguments '('uidb64', 'token')' and keyword arguments '{}' not found. 0 pattern(s) tried: [] If you look the patters searched error shows, it was unable read any url patters that are configured in URL.py. That is the worry. Reset Password Class: class RequestPasswordResetEmailAPIView(GenericAPIView): serializer_class = ResetPasswordEmailSerializer def post(self,request): serializer = self.serializer_class(data=request.data) email = request.data.get('email','') if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) uidb64 = urlsafe_base64_encode(smart_bytes(user.id)) token = PasswordResetTokenGenerator().make_token(user) current_site = get_current_site( request=request ).domain relativeLink = reverse('api/password_reset_confirm2' ,args={'uidb64':uidb64, 'token': token} ) absurl = 'http://'+current_site+relativeLink email_body = 'Hello'+absurl data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Reset password link' } Util.send_email(data) return Response('Success') My url.py for authentication app looks like this urlpatterns = [ url(r'^user/?$', UserRetrieveUpdateAPIView.as_view()), url(r'^users/?$', RegistrationAPIView.as_view()), url(r'^users/login/?$', LoginAPIView.as_view()), url(r'^users/request-reset-email/',RequestPasswordResetEmailAPIView.as_view(), name='users/request-reset-email'), url(r'^users/password-reset-confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$', PasswordResetTokenCheckAPIView.as_view(), name='password_reset_confirm2'), # path('password-reset/<uidb64>/<token>/', RequestPasswordResetEmailAPIView.as_view(), name='api/password_reset_confirm'), ] And in Main url.py, urls are connfigured like this url(r'^api/', include('apps.authentication.urls', namespace='authentication')), Please advice, Thank you -
MapBox marker Cluster in Django
help, please I have used Django Mapbox for my project and after adding all the marker I was unable to use Marker Cluster like this plugin in the link https://docs.mapbox.com/mapbox.js/example/v1.0.0/markercluster-with-mapbox-data/ this is my code to export the marker on the map mapboxgl.accessToken = MKey; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11?optimize=true', center: [6.83, 42.12], zoom: 4 }); {% for r in resto %} // dish of the day var today = new Date(); var thisday = today.getDay(); var weekend = "{{ r.date_de_fin|date:'m-d-Y'}}"; var end = moment(new Date()).format("M-DD-y"); var week = weekend>=end; console.log(thisday); console.log(weekend); console.log(end); console.log(week); if(week && thisday==0){ dish = '{{ r.dimanche }}'; price = '{{ r.prix_de_plat_D }}'; }else if(week && thisday==1){ dish = '{{ r.lundi }}'; price = '{{ r.prix_de_plat_L }}'; }else if(week && thisday==2){ dish = '{{ r.mardi }}'; price = '{{ r.prix_de_plat_M }}'; }else if (week && thisday==3) { dish = '{{ r.mercredi }}'; price = '{{ r.prix_de_plat_ME}}'; }else if(week && thisday==4){ dish = '{{ r.jeudi }}'; price = '{{ r.prix_de_plat_J}}'; }else if(week && thisday==5){ dish = '{{ r.vendredi }}'; price = '{{ r.prix_de_plat_V}}'; }else if(week && thisday==6){ dish = '{{ r.samedi }}'; price = '{{ r.prix_de_plat_S}}'; }else{ dish = "Désolé, il n'y a pas … -
How to get the whole data of the requesting users in Django Friendship
So I am using Django Friendship in order to make the friendship stuff in my web app. Everything is based on the documentation and set up properly. The app works properly but the problem is that I can see only the id of the users. In other words I cannot get access to the whole data of the users. from django.shortcuts import render from django.contrib.auth.models import User from friendship.models import Friend, Follow, Block def AddFriend(request, pk): other_user = User.objects.get(id=pk) Friend.objects.add_friend( request.user, other_user, message='Hi! I would like to add you') return render(request, 'friendshipapp/add_friend.html') def FriendsList(request): friends_list = Friend.objects.friends(request.user) return render(request, 'friendshipapp/friends_list.html', {'friends_list': friends_list}) def RequestsList(request): requests = Friend.objects.unread_requests(user=request.user) users_list = [] for request in requests: requesting_user = User.objects.filter(id=request) users_list.append(requesting_user) return render(request, 'friendshipapp/requests_list.html', {'requesting_users':users_list}) the urls file is set up properly in the requests_list.html I can only see the id of the users. As you can see I tried to loop through the id of the request dispatchers and get access to the user but "request" gives me object of user. How can go around this problem? Thanks in advance -
Django Reactjs object Object
While passing array of fields from reactjs - it is being passed as an object of array while getting the same in django converts it into string of Object Object. So unable to parse the object and get the values of the form fields. Example: We have a html array of fields price[] tags[], when it is passed from Reactjs it is going as addon [ {price:20, tags:"tag1"},{price:25, tags:"tag2"} ,{price:200, tags:"tag3"}] but in django restframework we get as "[ object Object, object Object]" hence unable to access the values. Any help how to solve is highly appreciated. -
How to query in python mongo where I need to get data between certain dates, where the date is stored in ISO format in Database?
Example of how date stored in db: "CreatedAt" : ISODate("2020-11-19T07:10:03.673Z") And i need query where my start date and end date is in following format: start_date = 2020-11-10 end_date = 2020-11-20 -
'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): …