Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Docker Celery - Cannot assign requested address Is the server running on host
I am trying to run celery within a docker with django and postgres. My .env.dev is as follows DB_HOST=localhost DB_NAME=app DB_USER=postgres DB_PASS=supersecretpassword DB_ENGINE=django.db.backends.postgresql DB_PORT=6543 POSTGRES_DB=app POSTGRES_USER=postgres POSTGRES_PASSWORD=supersecretpassword POSTGRES_PORT=6543 My settings.py is as follows DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE'), 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), 'PORT': os.environ.get('DB_PORT'), } } My docker-compose is as follows version: "3.9" services: web: container_name: website build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/:/usr/src/app/ ports: - "8000:8000" env_file: - ./.env.dev depends_on: - db - redis db: container_name: database image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.dev environment: - POSTGRES_HOST_AUTH_METHOD=trust ports: - "6543:5432" redis: image: redis:6-alpine celery: build: context: ./backend command: celery worker server --loglevel=info --logfile=logs/celery.log volumes: - ./backend/:/usr/src/app/ env_file: - ./.env.dev depends_on: - db - redis - web volumes: postgres_data: The error message I get is /usr/local/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 6543? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 6543? -
"Module not found" while trying to debug with VSC a remote deployed containerized Django app
I have a django app inside a container that is deployed in a remote server. I have successfully set up VSC in order to debug my app. I have started debugging my django app but I get the error ModuleNotFound while debugging. Obviously, since the django app is deployed and working perfectly, all requirements modules do exists. Despite that, I get this error. Any ideas? -
getting input value on button click in django
i'm trying to get the input value on button click if request.method == 'POST': if request.POST['fah']: this is getting me False when page is loaded and if i click on button, it's not changing how can i write something like js addEventListener in django? my button <button type="button" class="bbtn" name="fah" id="fah" value="fah">Convert</button> -
Postman Django CSRF error when requesting obtain_auth_token route
Basically the same as this post which didn't get an answer, when I try to access the token route of the rest_framework using Postman, I get a 403 that says "CSRF cookie not set." I don't understand why I would need a token to request the route which is supposed to give me an authentication token, but most of all, I don't know how to get around this issue ! -
Django rest framework Login Authentication Problem
I'm using django rest framework for login. I tried this on postman app but it keep showing me something went wrong. help me out with this. Thanks in advance. Here is the code for views_api.py: from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.models import User from django.contrib.auth import authenticate , login class LoginView(APIView): def post(self , request): response = {} response['status'] = 500 response['message'] = 'Something went wrong' try: data = request.data if data.get('username') is None: response['message'] = 'key username not found' raise Exception('key username not found') if data.get('password') is None: response['message'] = 'key password not found' raise Exception('key password not found') check_user = User.objects.get.filter(username = data.get('username')).first() if check_user is None: response['message'] = 'invaild username, user not found' raise Exception('invaild username not found') user_obj = authenticate(username = data.get('username'), password = data.get('password')) if user_obj: response['status'] = 200 response['message'] = 'Welcome' else: response['message'] = 'invaild password' raise Exception('invaild password') except Exception as e: print(e) return Response(response) LoginView = LoginView.as_view() -
How to make ModelForm avoid form validation for instances coming in for update?
models.py class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) pattern = RegexValidator(r'(RT|rt|rT|Rt)\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') rt_number=models.CharField(max_length=15, validators=[pattern]) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=0) approval_date=models.DateField(default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) forms.py class ReceivablesForm(ModelForm): class Meta: model=Receivables fields='__all__' widgets={ "base_value":forms.NumberInput(attrs={"disabled":"on"}), "expected_value":forms.NumberInput(attrs={"disabled":"on"}), 'approval_date': DateInput(attrs={'type': 'date'}), } def clean(self): cleaned_data=super().clean() pt=self.cleaned_data['patient'] print('clean - receivables - instance: ', self.instance) if self.instance == None: if Discharge.objects.filter(patient=pt): dis1=Discharge.objects.filter(patient=pt) print('receivable form - dis1 value: ', dis1) try: pkg1=Package.objects.filter(patient=pt) dis2=dis1.order_by('-id').first() pkg2=pkg1.filter(date_of_admission__gt=dis2.date_of_discharge) if not pkg2: raise ValidationError('There is no Package value for this entry - 1!') except Package.DoesNotExist: raise ValidationError('No history of Package instance!') else: try: Package.objects.get(patient=pt) print(Package.objects.get(patient=pt)) except Package.DoesNotExist: raise ValidationError('There is no Package value for this entry - 2!') What this does is that it checks whether the data in the model prior to this model is already saved or not. If not saved already, it throws a validation error asking the user to fill in the previous form first. views.py def receivables_view(request): if request.method=='POST': fm_receivables=ReceivablesForm(request.POST) if fm_receivables.is_valid(): receivables=fm_receivables.save() ipd=IpdReport.objects.create(patient=receivables.patient, package=Package.objects.filter(patient=receivables.patient).order_by('-id').first(), receivables=receivables) print('Receivables ke views ka ipd value: ', ipd) OngoingReport.objects.create(ipdreport=ipd) fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) else: fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) Receivables update view def update_receivables_view(request, id): if request.method=='POST': print(request.POST) rec=Receivables.objects.get(pk=id) print(rec) form=ReceivablesForm(request.POST, instance=rec) print(form) if form.is_valid(): … -
How to register user using your own Model Django
I am having trouble registering a user as a PetOwner. I'm not sure what I am suppose to code in my signup view. I can signup a user and that user does not have admin or staff status which is great because they should not have these privileges. Problem is that I do not just want them to be a user but I want them to be a PetOwner. Currently, they are only a User not a PetOwner. What am I doing wrong here or what do I have to add. in models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User class PetOwner(models.Model): """Model representing a pet owner.""" user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, help_text="Enter owner's first name") last_name = models.CharField(max_length=50, help_text="Enter owner's last name") email = models.EmailField( max_length=50, blank=True, unique=True, help_text="Enter owner's email" ) phone_number = models.CharField( max_length=15, blank=True, unique=True, help_text="Enter owner's phone number" ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, null=True, blank=True ) class Meta: """Controls default ordering of records when querying the Model type.""" ordering = ["first_name", "last_name"] def __str__(self): """String for representing the Model object.""" return self.first_name def get_absolute_url(self): """Returns the url to access a detail record of this pet owner.""" return … -
How to add data to the model whose column are referenced(Foreign Field) from other model in Django
I am trying to add data to my Cart Model but getting the error as In the field in which I am trying to enter the data is the ForeignField whose reference is Items. Cannot assign "9": "Cart.pid" must be a "items" instance. Here is my code:- Views.py def add_cart(request): pid = request.POST.get('cart_id') quantity = request.POST.get('quantity') details = items.objects.filter(pk = request.POST.get('cart_id')) name = None price = None for i in details: name = i.name price = i.price pid = i.id user_id = request.user.id total = int(quantity)*price instance = Cart(pid = pid,quantity = quantity,pro_name = name,pro_price = price,user_id = user_id,total = total) return redirect('home') Models.py class items(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100,default='Item') desc = models.TextField(max_length=500, default='Best') price = models.IntegerField() category = models.CharField(max_length=50,default='Product') image = models.ImageField(upload_to="media",default='Item Image') class Cart(models.Model): pid = models.ForeignKey('items',on_delete=CASCADE,related_name="proid") name = models.ForeignKey('items',on_delete=CASCADE,related_name="proname") price = models.ForeignKey('items',on_delete=CASCADE,related_name="proprice") quantity = models.IntegerField(default=1) user_id = models.ForeignKey(User,on_delete=CASCADE) total = models.IntegerField(default=0) Please help!!! -
Django: ModuleNotFoundError: No module named 'psycopg2' on Mac
I have installed psycopg2-binary 2.9.1(pip install psycopg2-binary) in virtualenv, but when I execute python manage.py migrate, that appears "django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'", and python console also can't import psycopg2. how to fix the problem? -
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'), ]