Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to check for string in list of dicts in jinja templating?
I have a modal inside of a Django app that opens with dynamic data. This data is a list of dicts, that has the form: [{"name": <name>, "ip": <ip>}]. One host at a time can be configured for special treatment, so there is a template variable elevated_host. I am trying to write a template where, if the elevated_host is in targets, I show a div, however I haven't been able to get it. Things I have tried: {% if elevated_host and elevated_host in targets|map(attribute='name') %} TemplateSyntaxError: Invalid filter: 'map' {% if elevated_host and elevated_host in [t.name for t in targets] %} TemplateSyntaxError: Could not parse the remainder: '[t.name' from '[t.name' I also tried writing and loading a custom filter but it always returned true. According to requirements.txt, we are using Jina2=2.7.2. How would I go about checking if this elevated_host string is in the name field of a list of dictionaries? -
Swapping the source of an image based on a boolean value
Here's my models: class Product(models.Model): title = models.CharField(max_length=120) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='products') thumbnail = models.BooleanField(default=False) html template: {% if product.productimage_set.all %} {% for image in product.productimage_set.all %} {% if image.thumbnail %} <img src="{{ image.image.url }}"> {% endif %} {% endfor %} {% else %} <img src="image template when no image at all"> {% endif %} What I am trying to achieve is to use the image that has a "thumbnail" field equal to true by default, but if a Product have an image but none with "thumbnail" equal to true, it should use any image with foreign key that is matching this product, but if a product doesn't have any image then just use a template image. I have tried using {% else %} after checking if image is a thumbnail, but If a product have more than one image, then it would show them all. -
Why is text in django form validator not translated?
I import translation with from django.utils.translation import gettext as _ and have this Form definition class SearchSubstance(forms.Form): search_string = forms.CharField(max_length=100, validators=[validators.MinLengthValidator(4), too_much_compounds_validator]) with this custom validator def too_much_compounds_validator(query): raise ValidationError(_("translate this")) now the error message of MinLengthValidator is nicely translated (in Dutch) but somehow "translate this" is not translated. What am I doing wrong? -
django.db.utils.ProgrammingError: can't adapt type 'User' only in Postgres
I have this really odd error that I can't seem to figure out. I have solved how to fix it but it could be a weird error for others so I am posting anyways. I have this view function that allows users to invite team members to their team. @login_required def invite_team_member(request): if request.method == "POST": form = forms.InviteTeamMemberForm(request.POST, team=request.user.profile.team) if form.is_valid(): user = form.clean_username_or_email() try: models.TeamInvite.objects.create(from_user=request.user, to_user=user, team=request.user.profile.team) message = _("User successfully invited") except IntegrityError: message = _("This user has already been invited to your team") except ValidationError as e: if e.code == "team_full": message = _("Your team is full, no further users can be invited") else: raise e return render( request, "tracker/tracker_home/invite_team_member.html", {"invite_team_member_form": form, "message": message}, ) else: form = forms.InviteTeamMemberForm(team=request.user.profile.team) return render(request, "tracker/tracker_home/invite_team_member.html", {"invite_team_member_form": form}) Users enter a username or email into a form and the form determines whether it is valid to invite a user with that username or email. class InviteTeamMemberForm(forms.Form): username_or_email = forms.CharField(label=_("Username or Email")) def __init__(self, *args, **kwargs): self.team: models.Team = kwargs.pop("team") super().__init__(*args, **kwargs) def clean_username_or_email(self): data = self.cleaned_data["username_or_email"] try: user = User.objects.get(Q(username__iexact=data) | Q(email__iexact=data)) if user.profile.team == self.team: raise ValidationError(_("This user cannot be invited since they are already on this team")) return … -
Django: Get list item content from a list of hyperlinks
I'm stuck with a list of anchor tags and getting their content to views.py. Background: I have a input form for addresses. If the entered/submitted address is not specific as needed, for example because there are two cities with the same name, then I want to display a list of the potential addresses. Therefore, I have prepared a list of the potential target addresses also with an anchor tag. html page: <ul> <form action="{% url 'analytics' %}" method="GET"> {% for item in list_addresses %} <li><a href="{% url 'analytics' %}" name="pot_address" >{{ item.post_code }}</a></li> {% endfor %} </form> </ul> My urls.py: urlpatterns = [ path('', views.home, name = 'home'), path('/analytics', views.analytics, name = 'analytics'), ] Now I want to pass the address (content of the list item in html) to my views.py file. The views.py file looks like this: def analytics(request): if request.method == 'GET': pot_adress = request.GET['pot_address'] After having this address in views.py I want to use it to fetch specific data from a database. Could somebody help me with this issue?