Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django order by aggregate value from non-related table
I have two models, Accrual and Member, and the common field of these two models is register_no, but this field is not a foreign key class Accrual(models.Model): register_no = models.PositiveIntegerField(verbose_name=_('Register No')) amount=models.DecimalField(decimal_places=2, max_digits=17, verbose_name=_('Total Amount')) class Member(models.Model): register_no = models.PositiveIntegerField(unique=True, verbose_name=_('Register No')) I want to list the debt each member has. It can be done with @property; class Member(models.Model): register_no = models.PositiveIntegerField(unique=True, verbose_name=_('Register No')) @property def debt(self): ret_val = Accrual.objects.filter(register_no=self.register_no).aggregate( debt=Sum('amount')) debt = ret_val.get('debt', 0) return debt if debt else 0 but I can't use order_by this way. I want to sort each member by debt. How can I solve this problem? -
Reading HTML form name in Django views
I want to define a view that should display from which page the request is coming. for example: 'Request is coming from index page' 'Request is coming from home page' ................... ................ so on views.py def practice(request): return HttpResponse(request.POST) it is displaying all the form fields but I am not able to get the form name. Html: {% extends 'base.html' %} <html> <head> <meta charset="UTF-8"> </head> <body> {% block content %} <h1>Creating Incident</h1> <form name = "index" action = 'practice' method = "post"> {% csrf_token %} <center> <table> <tr><td>Support portal username</td><td>:</td><td><input type = 'text' name = USERNAME size="50"></td></tr> <tr><td>Your Email</td><td>:</td><td><input type = 'text' name = EMAIL size="50"></td></tr> <tr><td>Password</td><td>:</td><td><input type = 'password' name = PASSWORD size="50"></td></tr> <tr><td>Xtreme ID</td><td>:</td><td><input type = 'text' name = COMPANYID size="50"></td></tr> <tr><td>Customer email </td><td>:</td><td><input type = 'text' name = CUSTOMEREMAIL size="50"></td></tr> <tr><td>Event Note </td><td>:</td><td><textarea id="eventnote" name= EVENTNOTE rows="8" cols="48"></textarea></td></tr> </table><br> <input type = 'submit' value = 'submit'> <a href="Home"><input type="button" value="Home"></a> </center> </form> {% endblock %} </body> </html> -
assigning role for different users in Django Rest Framework
I have used AbstractUser defined in Django for user model and have a UserProfile model which is one to one relation with the User. Now I have to implement a role-based authorization for the CRM project that I am writing. What will be the best approach to assign a role? Should I use add fields inside the user model or inside the UserProfile model? Or I should use the already defined superuser,is_staff or active status inside User model. My models: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self,first_name,last_name,email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) #user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, first_name,last_name,email, password, **extra_fields): """ Create and save a SuperUser with the 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(first_name,last_name,email, password, **extra_fields) class CustomUser(AbstractUser): … -
DRF nested router serializer source fields from url
I have an author and books model. An author has many books with him class Author(Model): id = UUIDField(primary_key=True, default=uuid4, editable=False) name = CharField(max_length=50) email = CharField(max_length=50) class Book(Model): id = UUIDField(primary_key=True, default=uuid4, editable=False) name = CharField(max_length=50) author = ForeignKey(Author, on_delete=models.CASCADE) In my urls.py author_router = SimpleRouter() author_router.register( r"author", AuthorViewSet, basename=author" ) nested_author_router = NestedSimpleRouter(author_router, r"author", lookup="author") nested_author_router.register(r"book", BookViewSet) In my searlizers.py class BookSerializer(ModelSerializer): class Meta: model = Book fields = ( "id", "name", "author", ) extra_kwargs = { "id": {"required": False}, "author": {"required": False}, } class AuthorSerialzer(ModelSerializer): class Meta: model = Author fields = ( "id", "name", "email", ) extra_kwargs = { "id": {"required": False}, } In views.py class BookViewSet(GenericViewSet): queryset = Book.objects.all() serializer_class = BookSerializer def create(self, request, author_pk): data = request.data data["author"] = author_pk serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) Since books are related to the author and I am using nested routers the curl call would look like curl --location --request POST 'localhost:8000/author/1/book' --data '{"name": "Book Name"}' In my BookViewSet I end up manually adding the author_pk to the data object before calling serializer is_valid method. Is there a way to specify the source from URL route or any better way of doing this? -
Heroku: "No default language could be detected for this app" error thrown for node app
Heroku: "No default language could be detected for this app" error thrown for node app ... enter image description here -
how can i call all the emails in or i want to add more fields to it it this is my git repo https://github.com/rahullabroo0/django-react-auth-main.git
i am trying to know how can i call all the emails in it? or i want to add more fields to it it this is my git repo https://github.com/rahullabroo0/django-react-auth-main.git and is there any standard method to use login registration code. plz send me the links and also tell me to how to work on multiple table in django. in dashboard i want to show all the emails from table. this is the code -
Is it possible to determine routes to a location along with its distance using GeoDjango?
We have a food delivery project and we use GeoDjango for storing the locations of vendors and for determining the nearby vendors by calculating the distance of customers and vendors. Now, we want to filter the nearby vendors based on the distance of routes. Like for example, get the vendors that have 10km distance based on routes to the location of customer. Is it possible in GeoDjango? Can you recommend libraries that have that functionality? -
How to manipulate/compress uploaded image and save it to AWS S3 using boto3
I want to manipulate/compress the uploaded image and then save it on the S3 bucket. Here is what I have tried so far: S3 = boto3.client("s3", aws_access_key_id=settings.ACCESS_KEY_ID,aws_secret_access_key=settings.SECRET_ACCESS_KEY) image = Image.open(img) outputIoStream = BytesIO() temp_image = image.resize((1020, 573)) temp_image.save(outputIoStream, format='PNG', quality=60) outputIoStream.seek(0) img = InMemoryUploadedFile(outputIoStream, 'ImageField', " {}.png".format(img.name.split('.')[0]), 'text/plain', sys.getsizeof(image), None) key = f"post/" + str(request.user.id) + "/" + str(img) S3.put_object(Bucket="zappa- legends", Body=img, Key=key) I am getting the following error: An error occurred (BadDigest) when calling the PutObject operation (reached max retries: 4): The Content-MD5 you specified did not match what we received. What should I do to avoid such errors? -
Is there a way to subscribe and send personal messages to slack users in a workspace with python
I have a to create a webapp that sends messages to specific users asking them if they want to see a daily report of their progress. I have to develop this in django and celery. This is the requirement that got me in trouble: The employees should not be able to see other's reports. The slack reminders must contain an URL to today's report with the following pattern https://domain_of_my_app/report/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (an UUID), this page must not require authentication of any kind. I think that link must be unique to the users but I have no idea how to deal with this in slack Any ideas? -
How to get data from url in django?
I want to send contid and cid to the function through the url . I included the path in the urls.py path('contracts/ctinfo/<int:contid>/<int:cid>',contract.ctinfo), # when contid and cid both present path('contracts/ctinfo/<int:cid>',contract.ctinfo), # when only cid is present contract.py def ctinfo(request,cid=None,contid=None): print(cid,contid) return render(some.html) When I am accessing http://localhost:8000/contracts/ctinfo/15000/99 I am getting cid=99 but contid=0 Why I am getting 0? Is there any other way to do this? -
Django - Django not returning all entities from table on GET call
I have this get function def get(self, request): items = Post.objects.order_by('created').annotate( creator_name=F('creator_id__username'), goal_description=F('goal_id__description'), replies=Count('replypost', distinct=True), cheers=Count('cheerpost', distinct=True), ).prefetch_related( Prefetch('photo_set', Photo.objects.order_by('created')) ) serializer = FullPostDataSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_200_OK) It should ideally be returning all the posts ordered by time, but for some reason when I debug and return serializer.data all I get on the front-end is: But when I use PGAdmin to look at the table You can clearly see there are more recent posts than september 13th. What's going on? -
How to allow admin to update staff password and username django
I have created the page where admin is able to update user password and username when the admin click on the update button, it is supposed to redirect the admin to the update page when he click on the update button where he will fill in a new username and password for the staff but there is an error shown below. Image below is a part on how the admin side will looks like: views.py def update(request, id): context = {} user = get_object_or_404(User, id=id) if request.method == "POST": user.save() return HttpResponseRedirect("/update") return render(request, 'allstaff.html', context) urls.py urlpatterns = [ path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('delete/<int:id>/', views.delete, name='delete'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), ] allstaff.html {% extends "home.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <div style="padding-left:16px"> <br> <div class="form-block"> <table> <tr> … -
Whice configuration is better ? configure FastCGI module on IIS for a django web app using wfastcgi.exe or python.exe with an argument wfastcgi.py
So I have been learning to deploy a django web application on IIS Web Server. I had successfully deployed it. However, when configuring FastCgiModule on handler mapping, I noticed that the requested executable optional are .dll or .exe file. capture of the requested file for FastCgiModule But, I have read some tutorials and all of them are not using .dll or .exe file on their FastCgiModule, instead they use 'path to python.exe'|'path to wfastcgi.py' this way works. Then I tried another way to configure this using 'path to wfastcgi.py' and it also works. So I have surfed on internet a few days but I couldn't find the answer which way is better. -
Django Application and Apache Server with ERR_CONNECTION_RESET on AWS
I have a Django application running on two AWS EC2 instances with a load balancer. I am using Apache as a web application server. As you can see below, if I run logistic regression on MagicStat using those 8 parameters and the banking.csv file, everything runs fine after clicking the Analyze button. If I use one more parameter, i.e. 9 parameters, I end up with ERR_CONNECTION_RESET error. Even when I run the application directly inside the server using the same Apache (http://localhost), it doesn't work either. Note that I make AJAX calls in each request such as selecting the model and clicking the Analyze button. Interestingly, that doesn't happen, i.e. it works with those 9 parameters, if I run my Django application from local Apache server (http://localhost). . I don't know what is happening? Any suggestions? Note: Running 9 parameters with the banking.csv file crashes my apache server, so that's the reason why I didn't share the data file here. -
ImproperlyConfigured at /admin/auth/group/
I am trying to set multiple Databases in Django and use Djoser for user authentication. I was able to create a super user and log in to the admin site. However, when I try to go to http://127.0.0.1:8000/admin/auth/group/ I get the following error: "ImproperlyConfigured at /admin/auth/group/" It also happens when I use postman to test my Djoser User Create endpoint: ImproperlyConfigured at /auth/users/ settings.DATABASES is improperly configured. Please supply the ENGINE value This is my settings.py: DATABASES = { 'default': {}, 'users': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sapienslevel_users', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': get_secret('DB_PASSWORD') }, 'questions': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sapienslevel_questions', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': get_secret('DB_PASSWORD') } } DATABASE_ROUTERS = ['users.router.AuthRouter', 'questions.router.QuestionRouter'] This is my AuthRouter: class AuthRouter: route_app_labels = {'users', 'admin', 'contenttypes', 'sessions', } def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'users' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'users' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'users' return None And my custom user model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class … -
Add authentication to django rest framework openapi
I want to add authentication to swagger ui as declared here : https://www.django-rest-framework.org/topics/documenting-your-api/ I already know that drf-yasg and drf_spectacular support that but I wanna know how to do it by just using django rest framework code : <!DOCTYPE html> <html> <head> <title>Swagger</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url schema_url %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout", requestInterceptor: (request) => { request.headers['X-CSRFToken'] = "{{ csrf_token }}" return request; } }) </script> </body> </html> -
How to solve "Could not import 'todo.schema.schema' for Graphene setting 'SCHEMA'. ModuleNotFoundError: No module named 'typing_extensions'."?
I create the Django graphene project. Suddenly I get an error Could not import 'todo.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: module 'graphene' has no attribute 'string'. But I don't find how to solve it. My schema structure is: todo/schema/schema seting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party app 'graphene_django', 'django_filters', ] GRAPHENE = { 'SCHEMA': 'todo.schema.schema' } main urls.py: urlpatterns = [ path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True))), ] schema.py: class Query(TodoQuery, graphene.ObjectType): pass class Mutation(Mutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) What I have missed? Or maybe I do something wrong? -
How to display an image inside Django Admin's detail view of a model?
I want to display an image inside a detail view of a model, when browsing through Django Admin. I have seen other posts about displaying images in the list view of all instances of a model in Django Admin. But I'm interested in seeing the image on the page where you can edit the data. models.py class Label(models.Model): label = models.TextField() fragment = models.ForeignKey('Fragment', models.DO_NOTHING, null=True) in_english = models.BooleanField(default=True) validated = models.BooleanField(default=False) def __str__(self): return str(self.fragment) admin.py @admin.register(Label) class LabelsAdmin(admin.ModelAdmin): fields = ("label", "in_english", "validated", ) # What I tried. This is not working even after adding 'image' to the fields. I get an error. # def image(self, obj): # return format_html('<img src="{0}" />'.format(f"/static/fragments/{obj}.png")) -
django, creating qrcode.png file for a new instance in signals.py
I will like to create a qrcode.png file and store it in my S3 bucket once a instance gets created in models.Model (using signals.py). With my code below I managed to create the qrcode__png file in my local base directory but it does not upload to my external S3 bucket or save in my models.Model class. HELP! Thanks. Signals.py @receiver(post_save,sender=inventory) def create__url_qr(sender, instance, created, **kwargs): if created == True: qr = qrcode.QRCode( version=1, box_size=10, border=5) qr.add_data('/MyProperty/item/'+str(instance.id)) qr.make(fit=True) im=qr.make_image(fill_color="black", back_color="white") im.save('qrcode___'+str(instance.id)+'.png', format="png") print('XXXX') print(im) print('XXXX') inst1 = inventory.objects.get(pk=instance.pk) inst1.qr_code = im inst1.save() -
Django/Wagtail Serialization issue showing <modelcluster.fields.create_deferring_foreign_related_manager>
I have the following Models: from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.admin.edit_handlers import FieldPanel, InlinePanel from wagtail.core.models import Page class BaseCta(models.Model): text = models.TextField() destination_url = models.URLField() panels = [ FieldPanel("text"), FieldPanel("destination_url"), ] def __str__(self): return str( dict( title=self.text, destination_url=self.destination_url ) ) class Reports(Page): content_panels = Page.content_panels + [ InlinePanel("nav", label="Reports CTAs (Calls to Action)"), InlinePanel("hero", label="Hero entry"), ] def __str__(self): return str( dict( title=self.title, nav=self.nav, hero=self.hero ) ) class ReportsCta(BaseCta): report = ParentalKey(Reports, related_name="nav", on_delete=models.CASCADE) class ReportsHero(ClusterableModel): report = ParentalKey(Reports, related_name='hero', on_delete=models.CASCADE) image_url = models.URLField(blank=False, null=False) title = models.CharField(max_length=200, blank=False, null=False) subtitle = models.CharField(max_length=200) description = models.TextField() panels = [ FieldPanel("image_url"), FieldPanel("title"), FieldPanel("subtitle"), FieldPanel("description"), InlinePanel("cta", label=" Hero CTA (Calls to Action)") ] def __str__(self): return str( dict( image_url=self.image_url, title=self.title, subtitle=self.subtitle, description=self.description, cta=self.cta ) ) class HeroCta(BaseCta): reports_hero = ParentalKey( ReportsHero, related_name="cta", on_delete=models.CASCADE, unique=True ) and the following serializers: from rest_framework import serializers from .models import ( Reports, ReportsHero, ReportsCta, HeroCta ) class ReportsCtaSerializer(serializers.ModelSerializer): class Meta: model = ReportsCta fields = ( "text", "destination_url", ) class HeroCtaSerializer(serializers.ModelSerializer): class Meta: model = HeroCta fields = ( "text", "destination_url", ) class ReportsHeroSerializer(serializers.ModelSerializer): cta = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = ReportsHero fields = ( "image_url", … -
Add Sockets To Django View For Contact With Robot
I am trying to give commands to a robot from a Django site through sockets as this has been recommended as the best possible way to do it. I have been working with Django and sockets in isolation but I have not been able to find an applicable tutorial(only chat apps) on how to integrate the two. If anybody has any experience with this and knows how to add this to my view any help would be great. (I just need help with the server-side of it, I know how to setup the client) My Model: class Robot(models.Model): def fetch_choices(): scope = [REDACTED] creds = ServiceAccountCredentials.from_json_keyfile_name("dashboard/Files/creds.json", scope) client = gspread.authorize(creds) sheet = client.open("tutorial").sheet1 path_names = [] path_name_fetch = sheet.col_values(1) for i in path_name_fetch: if (i, i) not in path_names: path_names.append((i, i)) return path_names name = models.CharField(max_length=200) path_options = models.CharField(choices=fetch_choices(), default=fetch_choices(), max_length=100) status_choices = [('waiting', 'waiting'), ('running', 'running'), ('stuck', 'stuck')] current_status = models.CharField(choices=status_choices, default=status_choices[0], max_length=100) def __str__(self): return self.name + ' | Current Status: ' + self.current_status def get_absolute_url(self): return reverse('dashboard-home') My Form: class RobotDetail(UpdateView): model = Robot form_class = RobotUpdateForm template_name = 'dashboard/robotdetail.html' My Template: <!DOCTYPE html> <html lang="en"> <head> <title>Dashboard</title> </head> <body> {% extends 'theblog/base.html' %} {% block content … -
Failed to start gunicorn.socket
This is my first time of using digital ocean to host my Django site and I am trying to follow the documentation, but I am stuck at somewhere; [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=clifford Group=www-data WorkingDirectory=/home/clifford/revolvemart/backend ExecStart=/home/clifford/revolvemart/backend/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ revolvemart.wsgi:application [Install] WantedBy=multi-user.target I created the gunicorn.service file, but when I try to run sudo systemctl start gunicorn.socket I keep getting Failed to start gunicorn.socket: Unit gunicorn.socket has a bad unit file setting. Am I doing something wrong here? -
request post with python's requests package does not work
I am working with the django framework. I'm trying to send a post request with token using the requests package but it doesn't work. the status code of the request is 200.Here is my code: def modifier_periode_push(request): url = "ip_addr/openapi/device" option1,option2,option3 = "040A0001","041E0001","043C0001" headers = { "Accept-Encoding":"gzip","Content-Length":"286","Content-Type":"application/json","Token":"0h2PPw2AlcKM0R1xXymkFA==", "User-Agent":"Go-http-client/1.1" } if request.is_ajax() and request.method == "POST": if request.POST["periode"] == "10": payload = convertir_en_hexa(option1) elif request.POST["periode"] == "30": payload = convertir_en_hexa(option2) else: payload = convertir_en_hexa(option3) data = { "devEUI":request.POST["devEUI"], "confirmed":False, "fPort":int(request.POST["fPort"]), "data":payload } try: **req = requests.post(url, headers=headers, data=data)** print(req.status_code)# returns 200 except: print("Erreur") return HttpResponse("ok") else: return HttpResponse("Requete non authorisée") I want to know why it does not work and how to debug because the status code 200 does not give much information -
Django , unable to start on local:host
I am using dj4e in pythonanywhere.com , I am trying to start the project but it gives an error saying that port 8000 is already in use. I tried to run from another port but nothing. In dj4e's document, it says I cannot use "runserver" command in virtualenv. Could somebody help me running the local server, please? -
How to use External authentication in django app
I creating an app in which the authentication is done via web services of another app. But as I m trying to understand how things will work, I m trying to figure out how I can store each user data and posts to them if I m not using Django auth and then linking the models via forgien keys.