Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django parler translatable field saving automatically
I am using django-parler plugin to make a model translatable to English and Hindi. when i create a model instance say in English i want Django to convert English word to Hindi using google translator api and save the model instance with both Hindi and English values. How to achieve this??? -
App Services Docker container: didn't respond to HTTP pings on port: 80, failing site start
I'm having problems with deploying my Django Application to Azure App-services. I'm getting the error when checking the logs: didn't respond to HTTP pings on port: 8000, failing site start. See container logs for debugging. I've followed the instructions as stated here to resolve the problem, but still no luck: https://docs.microsoft.com/en-gb/archive/blogs/waws/things-you-should-know-web-apps-and-linux#NoPing This is my set-up I have this in my Dockerfile: EXPOSE 80 EXPOSE 8000 This is my dockercompose.yml version: '3' services: web: build: . command: bash -c "python projectile/manage.py makemigrations && python projectile/manage.py migrate && python projectile/manage.py runserver 0.0.0.0:8000" container_name: image_service volumes: - .:/image_service ports: - "80" - "8000" I have these settings in the App Service Config in the portal WEBSITES_PORT 8000 What's wrong here? Would be awesome if someone could help. me out. -
Does Cast Function perform rounding before casting Django?
I expect the Cast function of Django, to do only casting e.g 7.6 will be 7 without performing any rounding. For example in Mysql the following: select CAST(((<value> - 1) div 30) AS SIGNED INTEGER) With a value equal to 227 will produce 7. But with Django's Cast, the following: MyModel.objects.annotate(time_window = Cast((F('field') - 1) / 30, IntegerField())) will produce 8 for some record having the value 227 for field. Are my expectations are wrong, or there is some flag to prevent this rounding behavior? -
cant do a simple route in flask
i am trying to learn flask , i have an issue with routing , i want to use another file for my routes ,it seems ok but i am getting 404 in 127.0.0.1:5000/user/signup , cant undrestand why heres the files tree : app: ----->env ----->static ----->templates ----->user: ---------->__init.py ---------->models.py ---------->routes.py app.py app.py: from flask import Flask, render_template app = Flask(__name__) # Routes from user import routes @app.route('/') def home(): return render_template('home.html') @app.route('/dashboard/') def dashboard(): return render_template('dashboard.html') if __name__ == "__main__": app.run() routes.py: from flask import Flask from app import app from user.models import User @app.route('/user/signup', methods=['POST']) def signup(): return User().signup() and models.py : from flask import Flask from flask.json import jsonify class User: def signup(self): user = { "_id" : "", "name" : "", "email" : "", "password" : "" } return jsonify(user),200 init.py is an empty file , please help me this is making me crazy , thanks -
getting error on book multiple pass at time using date picker function
@login_required def generate_commuter_pass(request): commuter_trips = Trip.objects.exclude(service_type=3) login_time = {} logout_time = {} for one in commuter_trips: if Trip_Stops.objects.filter(Trip_id = one).exists(): am_first_stop = Trip_Stops.objects.filter(Trip_id = one,status=True).order_by('time_am').first() am_last_stop = Trip_Stops.objects.filter(Trip_id = one,status=True).order_by('time_am').last() pm_first_stop = Trip_Stops.objects.filter(Trip_id = one,status=True).order_by('time_pm').first() pm_last_stop = Trip_Stops.objects.filter(Trip_id = one,status=True).order_by('time_pm').last() if one.trip_time == 0: login_time[one.pk] = am_first_stop.time_am logout_time[one.pk] = pm_last_stop.time_pm elif one.trip_time == 1: login_time[one.pk] = am_first_stop.time_am logout_time[one.pk] = am_last_stop.time_am elif one.trip_time == 2: login_time[one.pk] = pm_first_stop.time_pm logout_time[one.pk] = pm_last_stop.time_pm else: login_time[one.pk] = "00:00" logout_time[one.pk] = "00:00" >>> when pass the date from template the date is from datepicker that here we select the multiple date so that many pass can e generate if request.method == "POST": commuter_id = Commuter.objects.get(pk=request.POST['commuter_id']) trip_id = Trip.objects.get(pk=request.POST['trip_id']) vendor_trip_obj = Vendor_Trips.objects.get(Trip_id=trip_id) vehicle_seats = Vehicle_Seats.objects.filter(Vehicle_id=vendor_trip_obj.Vehicle_id) from_location = Trip_Stops.objects.get(pk=request.POST['from_location']) to_location = Trip_Stops.objects.get(pk=request.POST['to_location']) pass_date = request.POST['pass_date'] time = request.POST['time'] date_obj = [] all_dates = pass_date.split(",") for two in all_dates: date_new = datetime.strptime(two, "%Y-%m-%d").strftime("%Y-%m-%d") if time == '1': pass_time = 'am' no_pass_tm = 1 from_stop = from_location to_stop = to_location start_at = date_new+" "+str(from_stop.time_am) expire_at = date_new+" "+str(to_stop.time_am) else: pass_time = 'pm' no_pass_tm = 2 from_stop = from_location to_stop = to_location start_at = date_new+" "+str(from_stop.time_pm) expire_at = date_new+" "+str(to_stop.time_pm) select_seat = [] todays_date = date.today() year = str(todays_date.year) if … -
get() missing 1 required positional argument: 'to_date'
I am trying to return users created between certain dates and have decided to filter the user. But it gives "get() missing 1 required positional argument: 'to_date'" error even though I am passing the 'to_date' argument. What am I missing? Views.py class RegisteredUserFilter(APIView): serializer = RegisteredUserFilterSerializer def get(self, from_date, to_date): userondate = User.objects.filter(created_at__range=[from_date, to_date]) return Response({"User": userondate}) serializers.py class RegisteredUserFilterSerializer(serializers.Serializer): from_date = serializers.DateField() to_date = serializers.DateField() model = User -
Django filter many to many relation, by its primary key in admin
How would you create a filter in django admin, that filters by the primary key of many to many relation? Example: I have 3 models: class Country(models.Model): name = models.CharField(max_length=30) class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) class Person(models.Model): favourite_cities = models.ManyToManyField(City) Now in the admin dashboard under Person, I want to filter favourite cities, by countries. I don't want to show all the cities, just cities that are for example in Germany, or France. Is this possible? Thank you for your answers -
Customize image field in forms, django
The template .html {{form.image}} models.py image = models.ImageField(upload_to="data", null=True, blank=True) forms.py image = forms.FileField() The uploading is working but it is showing uncorrectly like this https://files.slack.com/files-pri/TLMTH8LJY-F02L2EZ70KH/screen_shot_2021-11-08_at_10.02.11_am.png I want to show only img tag and the input type file to change it Thanks in advance! -
the pages to block with the robots.txt [closed]
hello I am a python specialist, js I would like to know that they are the pages to put in the robots.txt as disallow I presume that the admin page is part User-Agent: * Disallow: (url admin) Sitemap: (url sitemap.xml) -
How do I include 400 validation errors in drf-spectacular?
I want to view validation details in 400 response. Something like this 200: Success 400: [ { "organisation_id": [ "This field is required." ] } ] #include any validation errors that can come from the serializer My code currently is this @extend_schema( summary="Create a new transaction", responses={ 201: OpenApiResponse( description='Success', ), 400: OpenApiResponse( description='Bad request. One or more errors occured.', ), }, ) And currently this outputs 200: Success 400: Bad request. One or more errors occured. -
How can I resolve a django.db.models.query.QuerySet error? I'm trying to use .groupby() to group my elements in my api response
I'm using django and I'm having trouble using the .groupby() method from the pandas library. The error message I'm getting in Postman is 'Value Error: Invalid file path or buffer object type: <class 'django.db.models.query.QuerySet'>'. I've tried searching for a sensible answer on Stack, the django docs and elsewhere but I don't understand what I'm looking for and what a potential solution could look like. Currently, returning serialize_user_logs give the API response below, however, returning the grouping_by_programme produces the QuerySet error. Desired outcome for the API response to group exercise data by type of programme as follows: User = { id: 1, username: 'asd', email: 'asd£gmail.com', programmes: { chest: [ { exercise_name: 'benchpress', weight: [0], lastweight_update: [] }, { exercise_name: 'fly', weight: [0], lastweight_update: [] } ], back: [ { exercise_name: 'rows', weight: [0], lastweight_update: [] }, { exercise_name: 'lat-pulldown', weight: [0], lastweight_update: [] } ], shoulders: [ { exercise_name: 'Overhead Press', weight: [0], lastweight_update: [] }, { exercise_name: 'lateral-raise', weight: [0], lastweight_update: [] } ], arms: [ { exercise_name: 'bicep-curl', weight: [0], lastweight_update: [] }, { exercise_name: 'dips', weight: [0], lastweight_update: [] } ], legs: [ { exercise_name: 'squats', weight: [0], lastweight_update: [] }, { exercise_name: 'leg-press', weight: [0], lastweight_update: … -
How to use Pyinstrument with django rest framework running in Django?
My question is regarding Pyinstrument. I am not sure how to use it with Django, django rest framework and Docker. The user guide was not clear to me. Django is running in docker, and I am able to do pyinstrument manage.py runserver --nothreading --noreload 0.0.0.0:8001 within the docker and I get bunch of results But how can I see the results of Pyinstrument when executing this django rest framework URL for example? self.client.post("api/cars/", data= { "type": 1 }) -
How to write python unittest case for except block which just uses a logger statement
Code for celery task: import logging from celery_once import QueueOnce from celery import shared_task, current_task from test.set_data import set_data_in_db logger = logging.getLogger("celery") @shared_task(base=QueueOnce, once={"graceful": True}, ignore_result=False) def set_data_task(): try: logger.info("Set data in db initiated") set_data_in_db(value=None) except Exception: logger.error("data could not be set", exc_info=True) My unittest case is covering everything which is in the try block. How can I force my unittest to cover except block as well ? -
Setting up aws ses with django site hosted on elastic beanstalk
I am attempting to use amazon ses to send user verifcation emails for a django site deployed using elastic beanstalk. I have allauth managing the user sign up, and using anymail to manage the emails. I have successfully completed the DKIM setup at namecheap (who host the domain) I am receiving a permission related error though, any advice appreciated: AnymailAPIError at /accounts/signup/ An error occurred (AccessDenied) when calling the SendRawEmail operation: User `arn:aws:sts::873836696822:assumed-role/aws-elasticbeanstalk-ec2-role/i-0ce34e11fac257334' is not authorized to perform `ses:SendRawEmail' on resource `arn:aws:ses:us-west-2:873836696822:identity/newuser@testing.com' botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the SendRawEmail operation: User `arn:aws:sts::873836696822:assumed-role/aws-elasticbeanstalk-ec2-role/i-0ce34e11fac257334' is not authorized to perform `ses:SendRawEmail' on resource `arn:aws:ses:us-west-2:873836696822:identity/newuser@testing.com' -
TypeError at /contact/ - "to" argument must be a list or tuple - Django
I want to send contact form email data to the domain email ID, but as i as am filling all fields of contact form and submitting it, getting error - Exception Value: "to" argument must be a list or tuple views.py code from django.contrib.messages.api import error from django.shortcuts import render from django.core.mail import send_mail from website.models import Contact from django.contrib import messages def contact(request): if request.method == 'POST': name = request.POST['name'] phone = request.POST['phone'] email = request.POST['email'] address = request.POST['address'] subject = request.POST['subject'] message = request.POST['message'] # All Filling Fields Values sending to the contact page so that fields values can be available during any error form_data = {'name': name, 'phone': phone, 'email': email, 'address': address, 'subject': subject, 'message': message} # send an email send_mail( name, # Subject phone, # message email, # from email address, # Address subject, # Subject message, # message 'mail@domain.com', # from Email ['toemail@gmail.com',], # To email ) # Form Validation error_message = None if (not name): error_message = "Name Required !!" elif name: if len(name) < 3: error_message = "Name must be 3 character long" elif not phone: error_message = "Phone Number Requird" elif len(phone) < 10: error_message = "Phone number must be 10 … -
ImproperlyConfigured at /api/customereport/
i am getting this error, which was not there previously , having trouble to rectify help needed in this class MeterSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="meter_reading:meters-list") customer_reports = CustomerReportSerializer(source='customerreport_set', many=True,read_only=True) class Meta: model = Meter fields = ['number','customer_reports','customer','url'] class CustomerReportSerializer(serializers.ModelSerializer): meter_no = serializers.SerializerMethodField(method_name='meter_num') customer_name = serializers.SerializerMethodField(method_name='cust_name') customer_number = serializers.SerializerMethodField(method_name='cust_number') class Meta: model = CustomerReport fields = ('meter_no','meter','customer_name','date','customer_unit','unit_rate','bill_amount','consumer_number','customer_number','pending_units',) routers.py router.register('customer', CustomerViewSet) router.register('meters',MeterViewSet,basename='meters') router.register('issues',IssueViewSet) router.register('customereport',CustomerReportViewSet,basename='customerreport') # router.register('users',UserViewset) urlpatterns = router.urls urls.py urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('meter_access/', MeterAccess.as_view(),name='meter_access'), ] -
How can I send back an array from Django to React after fetching POST request?
So my web app is a combination of Django, React and BigQuery. What I want to do is to make a POST request from React to Django, and Django will fetch the table data from BQ before sending the table data back as an array to the React frontend. How can I achieve this? What I have so far: app.js const handleConfirm = () => { fetch("http://localhost:8000/get-data-instance/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(tableName), }); }; views.py def get_data_instance(request): client = bigquery.Client() if request.method == 'POST': table_requested = json.loads(request.body) query_string = f""" SELECT * FROM `project-id.dataset-id.{table_requested}` """ result = ( client.query(query_string) .result() ) records = [dict(row) for row in result] data_instance = json.dumps(str(records)) return render(request, 'frontend/index.html') I basically want to send back the data_instance created above. If I try to print data_instance, i get the correct output >> "[{'key': 1, 'Date': '2021-11-10', 'Hour': 1, 'Measurement': 2.0}]" So, now I'm just stuck on how can I pass this data back to React? Note: I'm not using DRF for this project. -
javascript exception Django [closed]
So I was following along a MapBox Tutorial on Django, and I was trying to initialize the for loop for the address of each house that I developed in my model, but I get an error for adding a for loop. It seems that you cannot instantiate the for loop in javascript, but the guy in the video was able to do it at 32 minutes. Any suggestions? I am on VScode. https://www.youtube.com/watch?v=65flD9ScEQM enter image description here -
Deploying Django App to AWS elasticbeanstalk, No './Library/Application Support/Insomnia/SS'
I tried to create an env with eb command. But after the eb create myenv-envruns this error follows. ERROR: FileNotFoundError - [Errno 2] No such file or directory: './Library/Application Support/Insomnia/SS' I am not very sure what causing this? Maybe is it somehow about the M1 mac? -
Many to Many field values not showing up in queryset in Django
These are my models: class Tasks(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Users(models.Model): GENDER = [ ('male', 'Male'), ('female', 'Female'), ('others', 'Others'), ] name = models.CharField(max_length=20) age = models.IntegerField() gender = models.CharField(max_length=6,choices=GENDER,default='male') tasks = models.ManyToManyField(Tasks) problems = models.TextField(blank=True) def __str__(self): return self.name In views when I do users = Users.objects.values() I am getting all the fields except tasks. I am not able to access the tasks list. <QuerySet [{'id': 1, 'name': 'Tom', 'age': 23, 'gender': 'Male', 'problems': ''}, {'id': 2, 'name': 'Thomas', 'age': 45, 'gender': 'Male', 'problems': ''}, {'id': 3, 'name': 'Lara', 'age': 34, 'gender': 'Female', 'problems': ''}]> Also while iterating in users for u in users: print(u['tasks']) gives key error, and u.tasks.all() is also not working -
Relate one model field to another model field twice Django
I am making an inventory system, and one thing I would like to be able to track is transfers. I have two models class Location(models.Model): class FacilityChoices(models.TextChoices): warehouse = 'Warehouse' location = 'Location' name = models.CharField(max_length=255, null=False, blank=False) street_ad = models.CharField(max_length=128, verbose_name='Street address') city_ad = models.CharField(max_length=128, verbose_name='City Address') state_prov = models.CharField(max_length=30, verbose_name='State/Province') country = models.CharField(max_length=50, verbose_name='Country') zip_code = models.CharField(max_length=20, verbose_name='Zip/Postal code') facility_type = models.CharField(max_length=30, choices=FacilityChoices.choices, default=FacilityChoices.warehouse) ... class Transfer(models.Model): item = models.ForeignKey(Stock, on_delete=models.CASCADE) quantity = models.IntegerField() location_send = models.ForeignKey(Location, on_delete=models.CASCADE) location_receive = models.ForeignKey(Location, on_delete=models.CASCADE) but I receive an error (fields.E304) when I do this. What would be the best way to accomplish this? -
Django Error While Hosting It Using Apache Web Server
I'm using the below version of the packages, and the aim is to configure the apache to host the django application. I'm using python in a virtual environment. OS Version: Centos 7.9 **Apache Version** [root@localhost ~]# httpd -version Server version: Apache/2.4.6 (CentOS) Server built: Oct 19 2021 13:53:40 Python Version: 3.7.12 **Python Packages and Version:** (myprojectenv) [rafiq@localhost ~]$ pip3.7 list Package Version ----------------- -------- asgiref 3.4.1 Django 3.2.9 pip 21.3.1 pytz 2021.3 setuptools 58.3.0 sqlparse 0.4.2 typing-extensions 3.10.0.2 wheel 0.37.0 I have installed the sqlite3 from the source, below are the details of the sqlite3 version and the path of the sqlite3. I can able to import sqlite3 in python3.7.12 (myprojectenv) [rafiq@localhost ~]$ sqlite3 --version 3.36.0 2021-06-18 18:36:39 5c9a6c06871cb9fe42814af9c039eb6da5427a6ec28f187af7ebfb62eafa66e5 (myprojectenv) [rafiq@localhost ~]$ whereis sqlite3 sqlite3: /usr/bin/sqlite3 /usr/local/bin/sqlite3 /usr/include/sqlite3.h /usr/share/man/man1/sqlite3.1.gz I'm new to python and apache. I followed the digital ocean website to configure the django apache, the url is listed below. https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7 I have two folders inside /home/rafiq. myproject - django project myprojectenv - python virtualenv The settings of my apache configuration listed below. [rafiq@localhost ~]$ cat /etc/httpd/conf.d/django.conf Alias /static /home/rafiq/myproject/static <Directory /home/rafiq/myproject/static> Require all granted </Directory> <Directory /home/rafiq/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/rafiq/myprojectenv:/home/rafiq/myprojectenv/lib/python3.7/site-packages WSGIProcessGroup … -
pwa and serviceworker showing on page
I've converted my django app into a pwa using django_pwa. I used a custom serviceworker.js since the autogenerated one kept throwing 404s because I didn't have the files it was looking for. However, as soon as I tried to go to another page, I get the serviceworker showing up. Why is this? I put the serviceworker.js in my static that is in my base directior, and in my settings.py, I added PWA_SERVICE_WORKER_PATH. Can anyone help me? -
Configure the raspberry pi so that the 2D scanner works with rasberry pi
I have already hosted my django project onto the xampp apache server, right now i need to configure my raspberry pi so that my 2D barcode scanner will work. My raspberry pi at the end of the day will be just sitting at 1 corner with the 2D barcode scanner connected to the raspberry pi and my raspberry pi will not be accessing my hosted website and it also won't be connected to the monitor or any other screen. Both my pc and the raspberry pi will be connected to the same internet with the same static ip address that I already configure on the apache server. How do I confiure my raspberry pi to work with the 2D barcode scanner so that when the user use the scanner, the barcode information will be sent to the Xampp apache and will automatically appear at the user's windows pc? I am stuck here for a very long time, any help will be appreciated! -
What is wrong with my Django Redis Sentinel settings
I have a code where I use Celery and Redis. For Redis we have Sentinel with 3 nodes where 1 is master and 2 are slaves. So please help me write settings in Django settings for this code. I have it now this way: CELERY_BROKER_URL = "sentinel://'my_ip':26379/0;sentinel://'my_ip2':26379/0;sentinel://'my_ip3':26379/0" CELERY_BROKER_TRANSPORT_OPTIONS = {"visibility_timeout": 3600, "master_name": "master" "PASSWORD": 'password',} And somethig is wrong here, because I got error "beat: Connection error: No master found for 'master'. Trying again in 0 seconds..." If I delete this master_name part, I got beat: Connection error: No master found for None. Trying again in 0 seconds... What am I doing wrong?