Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't i see the text of description in my url?
In home category i have elf as a description : image I tried this code in my views to be able to display elf in my templates: def home(request ): p=get_object_or_404(category,pk=1) return render(request,'home.html',{'p':p}) and in templates i used this code <p id="id">{{p.description}}</p> to display it but it is not working i can not see the description or elf in this path path('',views.home), models: class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) urls: urlpatterns = [ path('api/', include(router.urls)), path('',views.home), path('admin/',admin.site.urls), ] Why can't i see the text of description in my url? -
GCP/Django - Server cannot serve a simple htmlresponse
So while I've successfully got the django app to locally serve and use the GCP SQL as backend, I'm having a hard time trying to get successful requests out of the django app using Google App Engine (Standard). Even a simple htmlresponse message doesn't work. Any advice here? Some odd things to note: there are 500 requests about the "favicon.ico" even though I don't use an ico file but a png. Removing the use of the favicon entirely yields similar results but now says "GET / HTTP/1.1 500" (Don't know what this is about) views.py (abbreviated) def index(request): return HttpResponse("Congratulations!") app.yaml runtime: python39 env_variables: BUCKET_NAME: "mystoragebucket" APPENGINE_URL: https://my-project-123456789101.uk.r.appspot.com/ handlers: - url: /static static_dir: static/ - url: /.* script: auto settings.py (abbreviated) DEBUG=False APPENGINE_URL = os.getenv('APPENGINE_URL') ALLOWED_HOSTS = [APPENGINE_URL[8:]] CSRF_TRUSTED_ORIGINS = [APPENGINE_URL] SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True STATIC_URL = "https://storage.googleapis.com/mypublicstaticbucket/static/" SECRET_KEY = 'django-insecure-randomstringhere' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '/cloud_sql/my-project-123456789101:us-east4:MYSQLInstanceNameHere', 'PORT' : 5432, 'NAME': 'MyDBNameHere', 'USER': 'myUsername', 'PASSWORD': 'MyPassword', } } -
Implementation of info in a web form
Im making a website for applying to jobs using django. The home page will display the different offers. I have 2 search bars, one for looking up a country or city and one for looking up job titles. The respective searches will come up. I want a drop down menu where you can pick a salary. The thing is when the person presses the salary i dont want a request to be sent just for the salary to be saved to a form. When a search is made I want both the salary and whatever is in the search bar to be sent to the backend -
how to authentication using react native and django
Hi I'm new to a react native I used to build full-stack pages using react js and Django in the backend but with react native I am facing a lot of problems with expo is there good documentation for that? -
Django '>' not supported between instances of 'NoneType' and 'int' Overlapping Checking
I am trying to make the code to check the overlapping in django forms , my code in form.py is , a = [] if count > 1: for i in range(count): first_number = self.data.get(f'newevent_set-{i}-first_number', []) last_number = self.data.get(f'newevent_set-{i}-last_number', []) new_run = self.data.getlist(f'newevent_set-{i}-new_run', []) a.append((i, first_number, last_number, new_run)) for i, base_data in enumerate(a): for check_data in a[i + 1:]: if float(base_data[1]) > float(check_data[0]): raise ValidationError ("Overlap Happening") -
How to stop scrapy from paginating the pages with repetitive records?
I tried to crawl a website whit pagination by scrapy, and it was ok! But, as this website gets update and new posts are added to this website, I need to run my code every day, so each time I run my code, it crawls all the pages. Fortunately, I'm using django and in my django model, I used unique=True So there are no duplicate records in my database, but I want to stop the pagination crawling as soon as it finds a duplicate record. how should I do this? here is my spider snippet code: def parse(self, response, **kwargs): next_page = response.xpath('//a[@class="next page-numbers"]/@href').get() news_links = response.xpath('//div[@class="content-column"]/div/article/div/div[1]/a/@href').getall() # print('*'*50) for link in news_links: yield scrapy.Request(url=link, callback=self.parse_item) if next_page: yield scrapy.Request(url=next_page, callback=self.parse) def parse_item(self, response): item = CryptocurrencyNewsItem() ... return item -
How to insert a variable from some premises created previously with the django query?
I'm building a query and I would like when the student is present and the justification is rejected that the value_x be placed, but the "Value" does not allow me to place a variable in it. Does anyone know a way to do this in django? Here's code below: inscritos = Inscricao.objects.all().annotate(valor_x=(Subquery(CursoValores.objects.filter(Q(curso__id_curso=OuterRef('Turma__Curso__id_curso'))&Q(data_inicio__lte=OuterRef('Turma__dt_hr_inicio'))&Q(data_fim__gte=OuterRef('Turma__dt_hr_inicio')) ).annotate(Max('valor')).values('valor__max'),output_field=FloatField())), valor_t=Case(When(Q(Presente=False)&Q(justificativa__situacao='I'), then=Value(valor_x)), default=Value(0), output_field=IntegerField(), ) -
Access to django filter data on view
I want to display information regarding the filter criteria received in the form, in the template. What is the best way to access this data in the view? -
Python subprocess doesn't find the PYTHONPATH
I'm using subprocess to call a python script but it doesn't work because it doesn't find my PYTHONPATH. I have a my PYTHONPATH put and it goes inside my folder. let's say my PYTHONPATH contains this path: /home/myproject. My architecture is this one: /myproject/djangoView/view_x.py from my view_x.py I use subprocess to launch a script that is on /myproject/scripts/script.py Then I start my server django, I have to click on a button and it should launch my script.py, to be clear it does work in local, but it doesn't work in preprod which is a server ubuntu. The error I have is ModuleNotFoundbecause in my script I call/utils/utils.py` So I just don't really understand why I have an error, my PYTHONPATH is set and correct, all the imports calling /utils/utils.py are working except when I'm using subprocess in my preprod server. I can't reproduce it in local. Is someone have an explanation for this behavior ? Here is my call: subprocess.run(["nohup python3 /home/myproject/scripts/script.py &"], shell=True) Thanx. -
how can i create a html file template in django application?
I'm learning Django and I have a problem that there is no answer for it on internet here is the problem, I created a folder as 'app', and I create another folder in app as 'challenges' (in VS Code in a Django application), so we have 2 nested folders now I want to create an HTML page, and I create a file as 'index.html', but VS Code cannot know this file as an HTML file -
how to send multi args to Django custom templates from JS code inside HTML template
I'm trying to use a custom template tag to run a specific function on a variable that I get in JS inside my HTML template. here is a sample of what I tried : python template tag def calculate_km(value, arg): """ Calculate the km from the source """ args_list = eval(arg) layer_id = value return f"layer_id_is:{layer_id}, args_list:{args_list}" then am using it inside my HTML js block like this : const args_data = "[" + kmlEvent.featureData.id + "," + kmlEvent.latLng.lat + "," + kmlEvent.latLng.lng + "]"; console.log(`{{single_layer.id|calculate_km: ${args_data} }}`); The problem here is in adding the JS variable inside the template tag , as you see using args_data inside the string that should return syntax for normal Django template so what is expected is that the console.log line renders as follows : {{12|calculate_km:[12,Foo,123,456]}} But the problem is that it is not reading the value of the variable args_data and it is being rendered as : {{12|calculate_km: ${args_data}}} and of course, that returns an error which is : django.template.exceptions.TemplateSyntaxError: calculate_km requires 2 arguments, 1 provided so it seems like not even reading the value of args_data -
Django annotation + filtering
I've some data that I've loaded from SQLite to PSQL using pgloader, it works more or less but some types are a bit clunky, so that's why my dates are in string, but I don't think that's the issue ( might be wrong here) Consider the following models: class User(models.Model): hash_id = models.TextField(primary_key=True) first_name = models.TextField(blank=True, null=True) last_name = models.TextField(blank=True, null=True) class Education(models.Model): hash_code = models.ForeignKey('Users', models.CASCADE) startdate = models.TextField(blank=True, null=True) enddate = models.TextField(blank=True, null=True) class Job(models.Model): hash_code = models.ForeignKey('Users', models.CASCADE) jobends = models.TextField(blank=True, null=True) jobstarts = models.TextField(blank=True, null=True) I'm trying to get all the jobs after X years from the user's first Education. So far I've got a Subquery, to get the first education's start date for each user: # This should return a date eg: '2000-01-01' mba_start_subq = Educations.objects.filter(hash_code=OuterRef('hash_code')) .order_by('startdate') .values('startdate')[:1] ) Then I append this to each Job via: jobs = (Job.objects.all() # .distinct('hash_code') .order_by('hash_code') .annotate(mba_start = Subquery(mba_start_subq)) ) So far so good, the issue is when I try to add a .filter() afterwards it takes ages to get the response (basically an infinite loop kind of thing) # Filtering with date strings works jobs.filter( Q(jobstarts__lt = '2000-01-01'), Q(jobends__gt = '2002-01-01') ) # this is the desired … -
how to get object position in a queryset without for loop?
i have a queryset with length = 10000 users sorted_users = User.ojbects.all().order_by("-money") and i need to get a position of a particular user in this sorted query set, i can do it with foor loop: user_position = 1 for account in sorted_users: if account.username == "admin": break my_position += 1 print(user_position) it works fine, but in case of growing user numbers for example to 100 000, it would take a long time to count users position every time, for loop is slow how can i make it faster, without a for loop? -
Nginx raising 403 Forbidden when accessing Staticfiles in Django app on Digital Ocean
having completed a django project on local development in my system, i followed the Digital Ocean tutorial to deploy a django app here Digital Ocean Django ASGI setup Tutorial. i configured gunicorn according to the tutorials and all tests and confirmations are passed But when i load my site from its Public IP address the site loads without any styles or designs and no images...just as plain text (just html content) my nginx configuration is as follows server { listen 80; server_name XXX.XX.XXX.XX; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/username/projectdir/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and my django Project setting is as follows # The absolute path to the directory where collectstatic will collect static files for deployment. STATIC_ROOT = BASE_DIR / 'staticfiles' # The URL to use when referring to static files (where they will be served from) STATIC_URL = '/static/' # extra places to find static filed outside static folder inside installed apps STATICFILES_DIRS = [ BASE_DIR/"static" ] MEDIA_ROOT = BASE_DIR/"media" can any solution be suggested. i have seen all the other related stackoverflow questions that had similar issues but their solutions did not work for … -
DRF : 'DemoView' should either include a `queryset` attribute, or override the `get_queryset()` method
I want to create a serializer without model. myproject/myapp/views.py : from rest_framework import viewsets from rest_framework.response import Response from .serializers import DemoSerializer class DemoView(viewsets.ModelViewSet): def get(self, request): my_data = [{"name": "Harsha"}, {"name": "Harsha"}] results = DemoSerializer(my_data, many=True).data return Response(results) myproject/myapp/urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('demo', views.DemoView, basename='Demo') urlpatterns = [ path('', include(router.urls)), ] myproject/myapp/serializer.py from rest_framework import serializers # from .models import Demo class DemoSerializer(serializers.Serializer): name = serializers.CharField() When I goto URL: http://localhost:8000/demo/, it is giving me following error: DemoView should either include a queryset attribute, or override the get_queryset() method. How can I resolve this error? -
DRF SerializerMethodField ignoring result
I have 2 serializers (one nested in the other). I need to pass context so that I can get an absolute url. I can see it works based on printing as it runs. But the actual result ignores the method and just returns standard (im assuming because it doesnt think it has a context). class ProjectNoteFileSerializer(serializers.ModelSerializer): thumb = serializers.SerializerMethodField() def get_thumb(self, obj): try: print(self.context.get("request")) #this actually prints like it does have it thumbnail = get_thumbnailer(obj.path)["big"].url return self.context.get("request").build_absolute_uri(thumbnail) except: return None class Meta(object): model = models.ProjectNoteFile fields = ("id", "path", "thumb") class ProjectQuestionnaireSectionSerializer(serializers.ModelSerializer): note_files = serializers.SerializerMethodField() def get_note_files(self, obj): serializer_context = {"request": self.context.get("request")} serializer = ProjectNoteFileSerializer( obj.note_files.all(), many=True, context=serializer_context, ) print(serializer.data) #prints results as expected return serializer.data class Meta(object): model = models.ProjectQuestionnaireSection fields = ( ... "note_files", ... ) My actual result is "note_files": [ { "id": 1, "path": "/media/project_notes/project_note_d5c598da-d4e8-480e-a50a-c474d57a7d44.png", "thumb": null } ], I have other versions of this working across the app. Maybe I am missing something basic? -
Django restrict foreign key to common order
Below is an extract from my models.py. For the foreign key ce_hostname I am getting the options to include all ce_hostnames that exist within the database. What I actually want is the ce_hostname which only share the same order_reference. How can I achieve this? class Cx_Base(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) #Order reference cx_hostname = models.CharField(max_length=15, validators=[CX_HOSTNAME_REGEX]) #Hostname of router i.e. PENNER-DCNCE-01. Always required. ce_hostname = models.ForeignKey(Ce_Base, null=True, on_delete=models.CASCADE) #Hostname of router in which the module will be inserted. -
DRF, Firebase FCM. Sending push notifications
I am creating a DRF project and want to implement sending push notifications to devices. I have configured firebase in Django settings. But after that I faced a problem as I can't send test notification even from admin, I get an error: enter image description here I understand that FCM registration token is required, but there is no way I can get it on backend side. Please advise if anyone has come across how is it possible to generate registration token on backend. -
Django- How can I allow only a set number of duplications with UniqueConstraint?
I'm making a webpage - a rental place that can rent movies, music cd's and books. I've created a model of cd - class Cd(models.Model): cd_band=models.CharField(max_length=100) cd_title=models.CharField(max_length=100) CD_GENRE= ( ('POP', "POP"), ("HIP", "Hip-Hop"), ("ROC", "Rock"), ("BLU", "Blues"), ("SOU", "Soul"), ("COU", "Country"), ("JAZ", "Jazz"), ("CLA", "Classical music"), ) cd_genre=models.CharField(max_length=3, choices=CD_GENRE) cd_length=models.DurationField() cd_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1) def __str__(self): # return self.cd_title, '\n', self.cd_band, '\n' return "{} {} {}".format(self.cd_band,self.cd_title,self.cd_genre) But there is a rule that I have to apply here: -One band can offer cd's in up to 2 genres. So let's say I create a cd of Band1 - Band1 can have cd's in only 2 genres - f.e rock and blues. I have no idea how to implement that. I'm thinking about making a constraint, but I don't know what condition to implement: UniqueConstraint.condition(fields=['cd_band','cd_genre'],condition=??????, name='unique_cd') I've also thought of restructurizing my entire database - making a separate classes for bands and music genres, and then linking it with foreign keys, setting up validators. I think it should work, but I'd have to put in so much work. Is there any other way of doing it? -
Please help me to host django project [closed]
Please help me to know how to host a django. https://i.stack.imgur.com/VmCkz.jpg /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/core/wsgi.py File line 24 , in setup " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/init.py " , apps.populate ( settings . INSTALLED APPS ) line 91 , in populate File " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/registry.py " , app_config AppConfig.create ( entry ) ) File " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/config.py " , line 239 , in create " % s must supply a name attribute . " % entry ********************************** you're seeing -
DRF - make query parameter's key case insensitive
is it possible in DRF to make url query keys case insensitive. food_id = self.request.query_params.get("food_id") get value of food_id even if it is passed as FOOD_ID or food_ID and etc. Thank you in advance. -
Django Access to font gives origin has been blocked by CORS policy:
I have been trying to load fonts in my django html template but I am always seeing this error. Access to font at 'https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Bold.woff2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. small part of my html code is here. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <style> @font-face { font-family: 'Noah-Medium'; src: url( 'https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.eot'); src: url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.eot?#iefix') format('embedded-opentype'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.woff2') format('woff2'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.woff') format('woff'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.ttf') format('truetype'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.svg#Noah-Medium') format('svg'); font-weight: 500; font-style: normal; font-display: swap; } my CORS config are here. CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:8000"] CORS_ALLOW_HEADERS = list(default_headers) + [ "user-id", "phone-number", ] Any reason for the issue above? -
Is a heroku hobby dyno and hobby basic postgres a fixed monthly cost or can it become variable?
I'm interested in purchasing a heroku hobby dyno and hobby basic postgres for deploying my django app as it seems they are fixed prices which means I would have predictable pricing. My concern however is that since I am an amateur, I am worried about accidentally attracting a large bill which seems to happen with people using other modern deployment platforms. The cost should be $16 US per month. I get confused because it says charges are based on usage. Hasn't the price already been provided as a fixed cost? I simply want to deploy my django mvp web app and not have any surprise costs regardless of traffic or whatever could possibly incur extra charges. I'm quite confused can anyone help? -
Django-PayPal: I have 3 models and 3 signal receiver functions, but I’m unable to specify which should be called when a payment is received
I am using Django-Paypal to receive payments for 3 different services. Each service has a separate model (say, Service1, Service2 and Service3) but all are within the same app ‘payments’. I need to update the payment status of the correct model to ‘paid=True’ after receiving payment for the corresponding service. I have 3 payment processing views (each per service) which are working well, as all payments are completed successfully. Similarly, I have created 3 signals/receiver functions (each per model) and placed them in signals.py. When I test one signal at a time, it works well. The payment status is successfully updated to ‘paid=True’. However, when I include all the three signals in signals.py, things stop working. I noted that each time a payment is received, the first 2 receiver functions are fired, leading to an error. See the code at the bottom How do I specify which receiver function should be called when a payment is received from a specific model? Or which is the best way to implement the above successfully? When I am using inbuilt signals such as pre-save, it is possible to specify the model to be updated by adding the sender at the decorator e.g. @receiver(pre-save, … -
django allauth sign up error showing csrfmiddlewaretoken= in url
I am working on a project. I am using django allauth for authentication and I have properly configured the installation and application of django allauth. Login is working properly but when I go to signup form is takes the input but nothing happens on the screen but a little change appears on the url it shows : localhost:8000/accounts/signup/csrfmiddlewaretoken=...