Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use sockets to connect to Sqlite database in Django
I'm trying to write external scripts to my django project that will connect a socket to the sqlite database to listen to changes that happen to the tables. I will have threads supplying data to these tables and then I want to calculate the time taken for the system to detect changes in the database while monitoring it through sockets. I'm not sure if this is even possible, but I have been given this task. How can I achieve this? Do I need to use the standard channels module and setup consumers.py and routing.py for this or can I accomplish it in an external script? I have gone through websocket tutorials for django but I haven't been abole to figure out how I can connect to my database with what I learned. I am using Sqlite3 by the way. Any help is appreciated, thanks -
dajngo rest framework serializer.is_valid() not working [closed]
[enter image description here][1] please help [1]: https://i.stack.imgur.com/CWL8h.png -
Looking for suggestion, Django auth contrib groups, validate user if admin to a company
I'm looking for suggestions. What I have: User model Company model Groups (Admin, User) User can belong to many Company, but can only have one role on each company. Company 1 User 1 (admin), User 2(User) Company 2 User 1 (User), User 2(Admin) I would like to validate if User 1 is an ADMIN to Company 1, so I can give permission to user one on Company 1. As of now, I'm using django auth contrib group to give Role to user. Admin group (can create, update, delete) User group (can view only) What I have as of the moment is: request.user and request.user.groups.filter(name="Admin").exists() this is to validate if the user belongs to Admin. But I need to validate if the user is an ADMIN to Company. What I have in my head is: request.user and request.user.groups.filter(name="Admin").exists() and Company.objects.get(user__email='user1@example.com') #this validate if company has this user But this does not validate if User 1 is an Admin to Company 1. Looking for suggestions. I'm new to programming. Thank you! -
AWS ElasticBeanstalk failed to deploy Django/Postgres app
I'm having a hard time deploying my app built with Django, Postgres, DjangoQ, Redis and ES on AWS Elastic Beanstalk, using docker-compose.yml. I've used EB CLI (eb init, eb create) to do it and it shows the environment is successfully launched but I still have the following problem. On the EC2 instance, there is no postgres, djangoq and ec containers built like it says in the docker-compose file as below. Only django, redis and ngnix containers are found on the ec2 instance. The environment variables that I specified in the docker-compose.yml file aren't being configured to the django container on EC2, so I can't run django there. I'm pretty lost and am not sure where to even start to fix the problems here.. Any insight will be very much appreciated.. version: '3' services: django: build: context: . dockerfile: docker/Dockerfile command: gunicorn --bind 0.0.0.0:5000 etherscan_project.wsgi:application env_file: .env volumes: - $PWD:/srv/app/:delegated depends_on: - redis - db - es django-q: build: context: . dockerfile: docker/Dockerfile command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py qcluster" env_file: .env volumes: - $PWD:/srv/app/:delegated depends_on: - redis - db - django - es db: image: postgres:latest expose: - 5432 env_file: .env volumes: … -
i have a problem doing mutation to add product which has one to many relationship with another model in graphQL
my problem in i want to create a new internship from internship model and link it to cv in CV model with foreign key here is the models file class CV(models.Model): photo = models.ImageField(upload_to='CV/%Y/%m/%d/', null=True) headline = models.CharField(max_length=250) education = models.CharField(max_length=250) employment=models.CharField(max_length=250) class Internships(models.Model): employer=models.CharField(max_length=250) position=models.CharField(max_length=250) internship=models.ForeignKey(CV,on_delete=models.CASCADE,related_name="cv_internship") schema file class InternshipsType(DjangoObjectType): class Meta: model = Internships fields=("id","employer","position") class CVType(DjangoObjectType): class Meta: model = CV fields = ("id", "photo",'headline','education','employment','cv_internship') class InternshipsInput(graphene.InputObjectType): employer=graphene.String() position=graphene.String() class CvInput(graphene.InputObjectType): photo=graphene.String(required=True) headline=graphene.String(required=True) education=graphene.String(required=True) employment=graphene.String() internship=graphene.Field(InternshipsInput,id=graphene.Int()) class createCV(graphene.Mutation): cv=graphene.Field(CVType) class Arguments(): cv_data=CvInput() @staticmethod def mutate(root, info, cv_data): cv = CV.objects.create(**cv_data) return createCV(cv=cv) class createInternships(graphene.Mutation): class Arguments(): employer=graphene.String(required=True) position=graphene.String(required=True) internship=graphene.Field(InternshipsType) @classmethod def mutate(cls,root,info,employer,position,internship): internship=Internships(employer=employer,position=position) internship.save() return createInternships(internship=internship) i want to add an internship and link it to already existed cv with foreign key where i can write the foreign key in the createinternship class in the schema file here is aslo the query i write mutation{ addInternship(employer:"employername",position:"poition name"){__typename} } and here is the error mutate() missing 1 required positional argument: 'internship' -
Load data continuously even not connected to WebSocket
So, I have this data that needed to load before the connection. Is it possible to ready the data before the connection accept? so that the data is continuously sending even if not connected this is my consumer.py from . import eventhubreader class GraphConsumer(AsyncWebsocketConsumer): async def connect(self): event = eventhubreader.EventReader() async def cb(partition, events): data = events[len(events)-1] await self.send(json.dumps({'value': data.body_as_json()})) print(data.body_as_json()) await self.accept() while True: await eventHubReader.startReadMessage(iotconfig['connection_string'],iotconfig['consumer_group'],cb) this is the startReadMessage class EventReader: def __init__(self): data:str pass async def startReadMessage(self,iot_string,consumer,cb): eventHubString = self.iotConnToEventConvert(iot_string) consumerClient = EventHubConsumerClient.from_connection_string(eventHubString, consumer) async with consumerClient: try: await consumerClient.receive_batch(cb, starting_position="-1") except Exception as e: print(e) async def runIot(self,iot_string,consumer,cb): while True: await self.startReadMessage(iot_string,consumer,cb) this is the data def generateMockData(self,event): data = {} now = datetime.now() print(now) data["temperature"] = random.randint(23,25) data["tss"] = random.randint(5,8) data["vss"] = random.randint(1,4) data["bod"] = random.randint(1,7) data["doc"] = random.randint(8,13) data["cod"] = random.randint(5,12) data["ph"] = random.randint(2,13) data["turbidity"] = random.randint(1,5) data["conductivity"] = random.randint(1,7) data['datetime'] = now.strftime("%d/%m/%Y %H:%M:%S") return data -
How to Django queryset orderd_by in minimum time likes average max?
Info: I want to get queryset with order_by max like at minimum average time. In other words, In minimum time likes average max. Which have more average likes in less average time. current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") Model.objects.values( 'published_at', 'likes', ).aggregate( viewers=Avg(F('current_time') - Avg(F('published_at')) / F('likes')) ).order_by('-viewers') -
How create identifying and non identifying relationship in Django
Please somebody can teachme how create identifying and non identifying relationship in Django, similar the image for reference. Thank you. Image for reference. https://i.stack.imgur.com/ai8HP.jpg -
Django - How to calculate age of 10 years above
I have a Model with the normal date_of_birth = models.DateTimeField(blank=True, null=True) Please help me calculate those that are 10 years and above and display them in html. I need to set it so that as soon as someone turns 10 on todays date it automatically displays them. -
Validating data within a queryset
I have a case where I need to merge records into one. Pretty much frontend would provide a bunch of ids, Django will pull the records, validate the data, and create a new db record. In theory, most of the fields should contain the same value, but one field (we are copying the value from all records to the new record). Before creating the new record, I would like to add a validator to make sure the values are equal. What would be the best way to run the comparisons? My thought process is as follow: Get all the records for the given ids Use the first record as the source of truth ( everything else will get compared against this record ) Compare the values (Here is where I am getting stuck) Create new record Also, if you guys have idea on how to avoid hitting the db every time I need to compare a value would be great, this particular model has many fields and I feel hitting the db for every comparison isn't very efficient I have added a dummy model to give a better idea of what I am trying to accomplish class Book(models.Model): name = … -
Nonetype has no Attribute error in Django rest framework
Facing 'NoneType' object has no attribute 'role_access' when role is None. How to prevent this error by return just empty [] class AccessListSerializer(serializers.RelatedField): def to_representation(self, value): return value.access.code class MyInfoSerializer(serializers.ModelSerializer): approvers = ApproverSerializer(many=True) email = serializers.EmailField(source="user.email") username = serializers.CharField(source='user.username') domain = DomainSerializer() role = RoleSerializer() access = AccessListSerializer( source='role.role_access',many=True, read_only=True) class Meta: model = Employee fields = ['email', 'username', 'role', 'domain', 'approvers', 'access'] -
Django DRF serializers, how to add new field, fusion of two models?
I have two models, I have to make an endpoint where the results of two tables should appear in the json, which have a fongeringkey that joins them. My code is the following: models.py class Property(models.Model): address = models.CharField(max_length=120) city = models.CharField(max_length=32) price = models.BigIntegerField() description = models.TextField(blank=True, null=True) year = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'property' class StatusHistory(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE) status = models.ForeignKey(Status, on_delete=models.CASCADE) update_date = models.DateTimeField() class Meta: managed = False db_table = 'status_history' views.py class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = "page_size" max_page_size = 1000 class PropertyListView(viewsets.ModelViewSet): http_method_names = ['get', 'head'] serializer_class = PropertyListSerializer queryset = Property.objects.all() pagination_class = StandardResultsSetPagination def get_serializer_class(self): if self.action == 'list': return PropertyListSerializer return PropertyListSerializer def get_queryset(self): queryset = Property.objects.all() if self.request.GET.get('year'): queryset = queryset.filter(year=self.request.GET.get('year')) if self.request.GET.get('city'): queryset = queryset.filter(city=self.request.GET.get('city')) if self.request.GET.get('status'): queryse = queryset.filter(statushistory__status=self.request.GET.get('status')) else: queryset = queryset.order_by('-year') return queryset def list(self, request): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) serializers.py class PropertyListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Property fields = ('id', 'address', 'city', 'price', 'description', 'year') class StatusHistoryListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = StatusHistory fields = ('property', 'status', 'update_date') I … -
AttributeError: 'Session' object has no attribute 'region'
I'm trying to run an application on AWS and when I'll get the results it returns 'Session' object has no attribute 'region', more info below: Request Method: POST Request URL: http://mochila.us-west-2.elasticbeanstalk.com/page2 Django Version: 4.0.5 Exception Type: AttributeError Exception Value: 'Session' object has no attribute 'region' Exception Location: /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/braket/aws/aws_device.py, line 258, in _get_non_regional_device_session Python Executable: /var/app/venv/staging-LQM1lest/bin/python Python Version: 3.8.5 Python Path: ['/var/app/venv/staging-LQM1lest/bin', '/var/app/current', '/var/app/current/$PYTHONPATH', '/usr/lib64/python38.zip', '/usr/lib64/python3.8', '/usr/lib64/python3.8/lib-dynload', '/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages', '/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages'] -
Django Invalid HTTP_HOST header: '/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035
I need some help. I've a Django website, i added admin notification and Django keep sending me Invalid HTTP_HOST header notification. The complete error message is [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: '/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035. Here is my Nginx configuration server { if ($host !~ ^(XX.XX.XX.XX|example.com|www.example.com)$ ) { return 444; } # Deny illegal Host headers if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name example.com www.example.com XX.XX.XX.XX; access_log off; return 301 https://$host$request_uri; } server { server_name example.com www.example.com XX.XX.XX.XX; if ($host !~ ^(XX.XX.XX.XX|example.com|www.example.com)$ ) { return 444; } # Deny illegal Host headers location = /favicon.ico { access_log off; log_not_found off; } location /assets/ { root /home/joe/example; } location /media/ { root /home/joe/example; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } -
Is there another way to use WSGIScriptAliasMatch for a Django app running through Apache / mod WSGI?
I'm running a Python 3.9/Django 3 app through Apache, connected through WSGI (4.9). Is WSGIScriptAliasMatch not supported any more in Apache? I had previously configured this in a virtual hosts file, /etc/apache2/sites-enabled/000-default-le-ssl.conf, WSGIScriptAliasMatch ^/api/(.*) /var/www/html/web/directory/wsgi.py/$1 process-group=ssl_directory but now when I restart Apache or check its config, I get this error complaining about the above line $ sudo apachectl configtest AH00526: Syntax error on line 41 of /etc/apache2/sites-enabled/000-default-le-ssl.conf: Invalid option to WSGI script alias definition. Action 'configtest' failed. The Apache error log may have more information. Is there another way to write WSGIScriptAliasMatch? -
Creating a Google Cloud Kubernetes Job fails with unauthorized message
I have implemented a Google Cloud Kubernetes Job creating mechanism using Django / Python application. The code is below : credentials, project = google.auth.default( scopes=['https://www.googleapis.com/auth/cloud-platform', ]) credentials.refresh(google.auth.transport.requests.Request()) cluster_manager = ClusterManagerClient(credentials=credentials) cluster = cluster_manager.get_cluster(name=f"projects/MYPROJECT/locations/us-central1/clusters/cluster-1") with NamedTemporaryFile(delete=False) as ca_cert: ca_cert.write(base64.b64decode(cluster.master_auth.cluster_ca_certificate)) config = client.Configuration() config.host = f'https://{cluster.endpoint}:443' config.verify_ssl = True config.api_key = {"authorization": "Bearer " + credentials.token} config.username = credentials._service_account_email config.ssl_ca_cert = ca_cert.name client.Configuration.set_default(config) # Setup K8 configs api_instance = kubernetes.client.BatchV1Api(kubernetes.client.ApiClient(config)) def kube_create_job(manifest, output_uuid, output_signed_url, webhook_url): # Create the job definition # container_image = "gcr.io/videoo2/github.com/videoo-io/videoo-render:87fc058a1fc8f30d5a6bda15391a990e5e0f0b80" container_image = get_first_success_build_from_list_builds() name = id_generator() body = kube_create_job_object(name, container_image, env_vars={}) try: api_response = api_instance.create_namespaced_job("default", body, pretty=True) print(api_response) except ApiException as e: print("Exception when calling BatchV1Api->create_namespaced_job: %s\n" % e) return body Somehow, it works fine with local environment, but when I deploy the Django application to Cloud Run, it gives the following error : Default 2022-08-19T00:36:51.688763Z Exception when calling BatchV1Api->create_namespaced_job: (401) Default 2022-08-19T00:36:51.688788Z Reason: Unauthorized Default 2022-08-19T00:36:51.688800Z HTTP response headers: HTTPHeaderDict({'Audit-Id': '7e39553a-264a-43e7-bd08-575604c13397', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Fri, 19 Aug 2022 00:36:51 GMT', 'Content-Length': '165'}) Default 2022-08-19T00:36:51.688809Z HTTP response body: { Default 2022-08-19T00:36:51.688818Z "kind": "Status", What shall I do in order to overcome this authorization failure to trigger a job on Google Cloud Kubernetes Engine ? -
Can't get Form validation error in Django
I am trying to get the form validation error message and put it in a Django message. When I try entering the wrong data in the form field to try and produce an error, I get nothing in the error message but the form is raising the validation error. If I submit the correct data in the form fields, the success message shows. Here is my code: def job_details(request, job_id): job_details = job.objects.get(id=job_id) job_tags = jobTag.objects.all() form = JobApplicationForm() if request.method == 'POST': form = JobApplicationForm(request.POST, request.FILES) if form.is_valid(): application = jobApplicant( email = form.cleaned_data['email'], cv = form.cleaned_data['cv'], job = job_details ) application.save() messages.success(request, f"Application submitted successfully!") print("message sent") return redirect ('job_details', job_id) else: for error in form.errors: messages.error(request, error) form = JobApplicationForm() context = {'job_details': job_details, 'job_tags': job_tags, 'form': form} return render(request, 'job-details.html', context) What am I doing wrong? -
How to save checkbox value in django?
I am using checkboxes in Html and everytime I refresh my page, the checkboxes are unchecked again. How do I prevent this from happening ? Do I have to use JS ? I tought about booleans fields but I don't really know how to implement them ... I looked at other threads and it talked about javascript, but I do not understand anything at all about it, nor how to implement it. Here is my code : views.py : ' @login_required(login_url='/login') def home(request): check=False MyToDo = Todo.objects.filter(user=request.user) formtoDo = forms.TodoForm() if request.method == 'POST' and 'todosub' in request.POST: formtoDo = forms.TodoForm(request.POST) if formtoDo.is_valid(): todoit = formtoDo.save(commit=False) todoit.user = request.user todoit.save() return HttpResponseRedirect('/home?') [...] data ={'form': form, 'formtoDo': formtoDo, 'MyToDo': MyToDo, 'check':check} return render(request, "capygenda/entries.html", data) ' html : <form method="POST", class="Entry"> {% csrf_token %} <p>{{ formtoDo|crispy}} <button type="submit" name="todosub" >Add</button></p> </form> {% csrf_token %} {% for toto in MyToDo %} <form method="POST"> {% csrf_token %} <ul class="list"> <li class="list-item"> <input type="checkbox" class="hidden-box" id="{{ toto.id }}" autocomplete="off"/> <label for="{{ toto.id }}" class="check--label"> <span class="check--label-box"></span> <span class="check--label-text">{{ toto }}</span> </label> <button class="button-24" role="button"><a href="{% url 'delete_todo' toto.pk %}" class="delete">Delete</a></button> </ul> </form> -
tags are not getting displayed in template, Django
context['d_tags'] = Blog.objects.filter(is_published=True).values('tags__name').order_by('tags__name').distinct() print(context['d_tags']) this prints the out put as below <QuerySet [{'tags__name': 'ev'}, {'tags__name': 'yoga'}]> how can I show it on templates, tried the following way {% for tag in d_tags.all %} <li>{{ tag }}</li> {% endfor %} gives an out put in template as {'tags__name': 'ev'} {'tags__name': 'yoga'} but if I do this way {% for tag in d_tags.all %} <li>{{ tag.name }}</li> {% endfor %} doesn't gives any thing in display, how I can get just the values in template -
How to use update in django admin with custom function
this is my first question in Stack Overflow. I am trying to make an admin action to update the price of an asset. It firsts set the last_update_date to today/now and I want to set the last_price to the current market price. The last part is not working as it is not updating. Admin.py @admin.action(description='Update asset price') def update_price(modeladmin, request, queryset): queryset.update(last_update_date = timezone.now()) for q in queryset: q.last_price = get_close_price(q.ticker) #does not change anything class AssetAdmin(admin.ModelAdmin): actions = [update_price] admin.site.register(Asset, AssetAdmin) Models.py class Asset(models.Model): ticker = models.CharField( verbose_name="Ticker", max_length=5, unique=True, ) last_price = models.DecimalField( verbose_name="Last Price", max_digits=8, decimal_places=2, validators=[MinValueValidator(0)] ) last_update_date = models.DateTimeField( verbose_name="Last update date" ) class Meta: ordering = ['ticker'] def __str__(self) -> str: return self.ticker Custom function (from Alpha Advantage API) def get_close_price(SYMBOL): params["symbol"] = SYMBOL close_price = get(URL, params).json() close_price = close_price["Global Quote"]["05. price"] return close_price #returns an int -
DJANGO - The HTTP GET Request return nothing
I was running a python script that returned URLs of google search about a topic and it worked so I tried to embed this script in Django to display these URLs on a webpage but it doesn't work anymore and does not display any error Where did I go wrong? urls.py in AppWEB from django.urls import path from . import views urlpatterns = [ path('', views.scrap, name='scrap') ] view.py in AppWeb def fetch( query): params = { 'q': query, 'sxsrf': 'ALiCzsbh0YEbk_cEHlMBgzgq_tPEfVLYiQ:1660146922900', 'ei': '6tTzYrPNNsWM9u8PyLOOuAc', 'ved': '0ahUKEwiz6vSc0bz5AhVFhv0HHciZA3cQ4dUDCA0', 'tbs': 'qdr:d', 'gs_lcp': 'Cgdnd3Mtd2l6EAMyBAgjECcyCAguEIAEENQCMgUILhCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCC4QgAQyCAguEIAEENQCMgsILhCABBDHARCvATIFCAAQgAQ6BAgAEEM6DgguEIAEEMcBENEDENQCOgsILhCABBDHARDRAzoFCAAQkQI6BwgjEOoCECc6BwguENQCEEM6BAguEENKBAhBGABKBAhGGABQAFjWFmCDGWgCcAF4AoABkweIAfQekgELMi00LjIuMC4xLjKYAQCgAQGwAQrAAQE' } headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', 'cache-control': 'no-cache', 'cookie': 'OTZ=6594569_52_56_174240_52_315300; SID=Mwgr1yh_8pdqxcCW4bAmUDoP5GOeVkusbuzcWHdOYXlNadWmdbOUtPITFz1UUQ3OM8vseA.; __Secure-1PSID=Mwgr1yh_8pdqxcCW4bAmUDoP5GOeVkusbuzcWHdOYXlNadWmRmqrl9iD_9UOIZNkvbqX-Q.; __Secure-3PSID=Mwgr1yh_8pdqxcCW4bAmUDoP5GOeVkusbuzcWHdOYXlNadWm-ywqR6vV-7MXRA_OAoLNSQ.; HSID=APDjrCSjYxzBvkMxC; SSID=AsSz-gQXwFFeJqQzw; APISID=5Qwkn_cNhMDuRqpZ/AYczojbKYldQo2t5b; SAPISID=wxHQFonmSjj6gGfI/A6yfUPmtjo4OFWvWX; __Secure-1PAPISID=wxHQFonmSjj6gGfI/A6yfUPmtjo4OFWvWX; __Secure-3PAPISID=wxHQFonmSjj6gGfI/A6yfUPmtjo4OFWvWX; OGPC=19022622-1:; SEARCH_SAMESITE=CgQIjpYB; AEC=AakniGMUfMDPvK8aZ7e5s1miz5lAntjOEygTd68cx9N_z5Fn3uDUsuzpZvs; 1P_JAR=2022-08-12-11; NID=511=tk_V5K8omiV0ceKov6QEdmx7ZHv09DNibXnysZs-9qSzgrEd0Q2PhMZVvo4OLQNzxU7NEruKDmY-DIAvlXwIooK6EPJ2dFHgSc_gb3ukJxpdYSyf6cUl30ZMJb_p-9whuvDcv-EUGed7mD7e1Vn4BzICgaDnrL1gw3PGPA78T188TXjPfPQg-DULaqdIOiwxgEsFD2zz5SbHuW0G9bm5dOq2n22Hw4d2lVGSA6w9nBzpLaeMHQUObSp_Aua2CKm1WqKdwH4Isjd84aNc1cMdEGYeqcIScj32M0xBvThOCynpQutIyszjHl0NaN9js0m06wrM51XHJ-EXidLPoVCqRE88txdEmKDJ8qcSREpYbuddzCMBKIg7u1NEpAm81nih; SIDCC=AEf-XMRyfzEKl27JhtXmvgFbTAk1-0YKLGcy9fOOR6lPAULVKhiY3ZfPQVTib3S3S1BmrDf1O0U; __Secure-1PSIDCC=AEf-XMTBmMvKCbMLFwPKBRDd3u1rlbKfgVxzVV1SQZFKucrNE9q-FEczUfVA1miYsfyX_0ypDJk; __Secure-3PSIDCC=AEf-XMSO1Xh3vQg15LldTb_mzifg8hacgWmM70oDPo8lo-jutQ7Ho9dEoeegIgEW6Yr2iaAsGuoz; DV=o66_OU3929pTIBy4P1MyROsAdBYeKRhfk61DJytXfAAAAAAifm2YC1-efQAAAHh0x-PxVD2eJgAAAGy871Dv-DMjFQAAAA', 'referer': 'https://www.google.com/', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36 OPR/89.0.4447.83' } base_url = 'https://www.google.com/search' params['q'] = query # Make HTTP GET request return requests.get(base_url, params=params, headers=headers) def scrap(request): response = fetch('Parti Authenticité et Modernité(pam)') context = { 'url': response.url, 'code': response.status_code, } return render(request, 'index1.html',context) index1.html <p>Google search URL is : {{context.url}}</p> <p> status of code is : {{context.code}}</p> I got as a result -
Can't add a new Django model instance through admin "Can't resolve Keyword"
When I go to my admin panel and try to add a new instance of my Clip model I get the error message Cannot resolve keyword 'title' into field. Choices are: clip, description, endChapter, id, name, order, saga, saga_id, startChapter, even though the only fields the Clip model has at the moment are description, arc, chapter, viewers, characters, author, order, videoURL, verboseDescription. I've have no migrations to make so really unsure what's gone wrong. -
Docker: pg_config executable not found in docker?
i am trying to use docker in my django project, i am new to using docker and i do not really know where the error is coming from. I have read so many stackoverflow questions related to this issue but all the solution are not working for me. Maybe there is a new way to fix the bug. Please what the really the issue and how can i fix it? This is how my Dockerfile looks: FROM python:3.8.13-slim-buster WORKDIR /app COPY ./my_app ./ RUN pip install --upgrade pip --no-cache-dir RUN pip install psycopg2 --no-cache-dir RUN apk del build-deps --no-cache-dir RUN pip install -r /app/requirements.txt --no-cache-dir RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev && \ python3 -m pip install -r requirements.txt --no-cache-dir && \ apk --purge del .build-deps CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] # CMD ["gunicorn", "main_app.wsgi:application", "--bind"] This is the full trace_back PS C:\Users\Destiny\Desktop\StridEarn-master> docker build -t myimage . Sending build context to Docker daemon 12.13 MB Step 1/9 : FROM python:3.8.13-slim-buster ---> 289f4e681a96 Step 2/9 : WORKDIR /app ---> Using cache ---> 06ecbb3b2e23 Step 3/9 : COPY ./my_app ./ ---> Using cache ---> f00b6ccdae31 Step 4/9 : RUN pip install … -
JOIN multiple SELECT statements results and group by seperate SELECT Statement
I am trying to get specific stock provided per supplier between a date range and ordered in descending order: something like this NAME LOCATION TYPE STOCK PROVIDED Tesco Towcester Supermarket 200g Waitrose Towcester Supermarket g SOFEA Milton Keynes Charity g Tesco Daventry Supermarket g I can currently receive the total weight during the collection period like this: # Collections in date range - returns string list of collection ids in date range cursor.execute('SELECT id FROM app1_collection WHERE created_at BETWEEN %s AND %s AND larder_id = %s', [start_datetime, end_datetime, larder_id]) collection_ids = re.findall(r'\d+', str(cursor.fetchall())) collection_ids_string = "'"+"','".join(collection_ids)+"'" print(collection_ids_string) # Total weight of products in date range from collection ids cursor.execute("SELECT SUM(weight) FROM app1_product WHERE collection_id IN ("+collection_ids_string+")") total_weight_in = cursor.fetchone()[0] print(total_weight_in) My Products table looks like: id name weight collection_id ...etc 1 twix 46.0 12 2 mars 540.0 11 3 coca-cola 330.0 11 etc... My Collection table looks like: id created_at larder_id supplier_id volunteer_id 1 2022-08-18 17:31:18.274780 1 3 1 2 2022-08-18 17:31:44.209567 1 3 1 etc... My Supplier table looks like: id name addressFirstLine postCode Type date created_at 1 Tesco Towcester NN12 7BA Supermarket 2022-08-18 17:29:14.477425 2022-08-18 17:29:14.477450 2 Waitrose Towcester NN12 8AB Supermarket 2022-08-18 17:29:30.119565 2022-08-18 17:29:30.119592 etc... My … -
Django "if request.method == 'POST':" is return False
I'm making django app and I have an issue I've never had problem with before. As always in form view, I'm checking if request.method == 'POST' but somehow it returns False, (I can see "request method is not correct" in console) my code looks like that: def recipe_create_view(request): context = {} form = RecipeForm(request.POST or None) IngredientFormset = formset_factory(IngredientForm) formset = IngredientFormset(request.POST or None) context['form'] = form context['formset'] = formset if request.method == 'POST': if form.is_valid(): if formset.is_valid(): form.save() print("made a recipe") for form in formset: child = form.save(commit=False) child.recipe = parent child.save() print("made an Ingredient") else: print("formset is not valid") else: print("form is not valid") else: print("request method is not correct") return render(request, 'recipes/create_recipe.html', context) create_recipe.html file: <form method="POST"> {% csrf_token %} <label>recipe</label> <p>{{form}}</p> <label>ingredients</label> {% for form in formset %} <ul> <label>name</label> <li>{{ form.name }}</li> <label>quantity</label> <li>{{ form.quantity }}</li> </ul> {% endfor %} <div> <input type="submit" value="submit" class="button-33" role="button"> </div> </form> where is the problem >?