Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a serializer for different fields
I am working on a project of blog application in Django Rest Framework. But here I am facing some trouble. At first checkout my code then I will explain the question. Here is the model.py class Contact(models.Model): id_no = models.AutoField(primary_key=True, unique=True) email = models.EmailField() name = models.CharField(max_length=1000) subject = models.CharField(max_length=1000) description = models.TextField() And here is the serializer.py class AddContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__' Now in a view function I want to use only email and name field of the Contact model and in another view function I want to use name and description field of that model. Can I use the same serializer class for different cases? Please help me. -
How do I import in django_cities_light?
I noticed I could not find Newport, Oregon in my django_cities_light django application. It is a small city with population slightly above 10k, so I downloaded cities1000.zip which contains cities with a population higher than 1k. I unzipped this file and started searching for Newport's id and indeed it is there: 5742750 Newport Newport N'juport,Newport (Oregon),Njuport,ONP,nyupoteu,nyupoto,nywbwrt,nywpwrt awrgn,Њупорт,Ньюпорт,Нюпорт,نيوبورت,نیوپورت، اورگن,نیوپورٹ، اوریگون,ニューポート,뉴포트 44.63678 -124.05345 P PPLA2 US OR ... Now, I have in my myapp/settings/development.py the following: CITIES_LIGHT_TRANSLATION_LANGUAGES = ['en'] CITIES_LIGHT_INCLUDE_CITY_TYPES = ['PPL', 'PPLA', 'PPLA2', 'PPLA3', 'PPLA4', 'PPLC', 'PPLF', 'PPLG', 'PPLL', 'PPLR', 'PPLS', 'STLMT',] CITIES_LIGHT_APP_NAME = 'jobs' CITIES_LIGHT_CITY_SOURCES = ['http://download.geonames.org/export/dump/cities1000.zip'] # <-- this added as part of this task I added CITIES_LIGHT_CITY_SOURCES following this post and the information here. I then tried to import from using the following command, which I understand downloads the cities1000 file specified in myapp.settings.development: python manage.py cities_light --settings=myapp.settings.development --force-all --progress Newport, Oregon, with id 5742750 is not found in my database. I also cannot see from the command that my settings file is used and that the value of CITIES_LIGHT_CITY_SOURCES is overridden properly. Does anyone know what I'm doing wrong and how to properly add from the source files? Thx! -
How to show hidden div that have data on edit page in Django forms
Iam trying to display an hidden div that have data, on the edit page using javascript in Django forms. This is the script const checkbox = document.getElementById('commute_id'); const box = document.getElementById('box'); checkbox.addEventListener('click', function handleClick() { if (checkbox. Checked) { box.style.display = 'block'; } else { box.style.display = 'none'; } }); </script> Checkbox code <div class="ui_kit_checkbox"> <div class="df mb20"> <span> {{form.commute_check|as_crispy_field }} </span> </div> </div> commute_check = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'id':'commute_id'})) Div to show and hide <div class="commute" ID="box" style="display:none" > <div class="mb20" STYLE=" display:inline-flex !important;" > <span style="padding-right:10px;"> {{ form.mon|as_crispy_field }} </span> </div> </div> This works when clicking the checkbox and adding data for the first time. But when in the edit page the check box is ticked but the div is hidden Need help. Please share if nay have better idea for this scenario. -
Using Django template together with React
Is it possible to use Django template together with React? If so, how should I do that? -
I'm trying to create user specific access to my todolist website with Django
I'm getting an error when I make migrations in the command line. Please help -models.py from django.db import models from django.contrib.auth.models import User class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", null=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def __str__(self): return self.text When I tried to make migrations in the command line, I got this error cmd-pic I used this command: python manage.py makemigrations python manage.py migrate I used the tutorial from TechWithTim(link: https://www.youtube.com/watch?v=sm1mokevMWk&t=7589s) to do this project. It works fine for him but not for me. Someone, please tell me where I went wrong. -
start primary key by 1001 in Django model, auto_increment gives error
Please describe how to start the primary key by 1001 in the Django model(database). I found some examples with auto_increment, but it gives me errors of undefined. Inside the project, we have to alter fields using migrations. So, Please notice that It does not affect our previous data. The database key must increment by 1 when we add another field or row. Thanks -
HttpResponseRedirect working properly but not redirecting to the next page, how can I solve that problem?
Currently I am building a resume builder website, but the problem is I can't redirect the user to the next page, it surely has problem with frontend, because backend worked properly and as I expected, because as you see the code down below, before the httpresponseredirect() method, it printed what I want, but it did not redirect the page to the next... This is not my first time question I gave this question before as well. I approached to the solution after my first time question, but now again problem, then I thought asking from stackoverflow was good idea! {% load static %} <!DOCTYPE html> <html style="font-size: 16px;" lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="utf-8"> <meta name="keywords" content="Let&amp;apos;s start with&nbsp;personal information"> <meta name="description" content=""> <title>Page 1</title> <link rel="stylesheet" href="{% static 'css/nicepage.css' %}" media="screen"> <link rel="stylesheet" href="{% static 'css/Page-1.css' %}" media="screen"> <script class="u-script" type="text/javascript" src="{% static 'js/jquery.js' %}" defer=""></script> <script class="u-script" type="text/javascript" src="{% static 'js/nicepage.js' %}" defer=""></script> <meta name="generator" content="Nicepage 4.18.5, nicepage.com"> <link id="u-theme-google-font" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i|Open+Sans:300,300i,400,400i,500,500i,600,600i,700,700i,800,800i"> <script type="application/ld+json">{ "@context": "http://schema.org", "@type": "Organization", "name": "", "logo": "images/Untitled1.png", "sameAs": [ "https://facebook.com/name", "https://twitter.com/name", "https://instagram.com/name" ] }</script> <meta name="theme-color" content="#478ac9"> <meta name="twitter:site" content="@"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="Page 1"> <meta name="twitter:description" content=""> <meta … -
Are django rest framework tokens safe
I'm using Django Rest Framework Token authentication. After logging in, the frontend saves the token as a cookie and sends it via the authorization header with every request. If an attacker could get a hold of the cookie that contains the token and sends it themselves, it would be impossible to detect whether the original user or an attacker sent the token, right? If so, what would be the best way to prevent a token from being compromised and used in a malicious manner? -
How to use Amazon SES with dynamic credentials?
I'm using Django/Python and I want to use multiple Amazon SES credentials on same server. I found boto3 to consume Amazon APIs but it requires to set the credentials using a file or environment variables. Which is I can't (or it's hard to) change it in the runtime. How can I set the credentials dynamically on runtime? I'm looking for a solution something like that: (boto3 is not mandatory, I can use any solution) CREDS = { "foo": { "AWS_ACCESS_KEY_ID": "XXX", "AWS_SECRET_ACCESS_KEY": "XXX", "AWS_DEFAULT_REGION": "us-east-1", }, "bar": { "AWS_ACCESS_KEY_ID": "YYY", "AWS_SECRET_ACCESS_KEY": "YYY", "AWS_DEFAULT_REGION": "us-east-1", }, } my_config = CREDS.get("foo") # or "bar" client = boto3.client('ses', config=my_config) How can I implement this? -
How to obtain a restaurant open hours in Django with reactjs
I would like to stock the schedules of my restaurants' list. What is the name of the field who can i do that: for example, the restaurants is open on Monday from 9 am to 11 pm. Can I do that? Thanks -
Why do the queries that I send ordered to the template from the django view arrive out of order?
I am making a query to the database, ordering it by date and then sending it to the template. The problem is that the query arrives out of order to the template This is the query from the view: recibos=grupo.recibos.all().order_by('-fecha_pago') This is the template code: {% if recibos %} <table class="table table-responsive-sm table-sm table-hover datatable"> <thead> <tr> <th>Responsable</th> <th class="text-center">Fecha</th> <th class="text-center">Monto</th> <th class="text-center">Forma de Pago</th> <th class="text-center"></th> </tr> </thead> <tbody> {% for recibo in recibos %} <tr> <td> <div>{{recibo.responsable.nombre}}</div> </td> <td class="text-center"> <div>{{recibo.fecha_pago}}</div> </td> <td class="text-center"> <div>${{recibo.importe|floatformat:"2g"}}</div> </td> <td class="text-center"> <div>{{recibo.forma_pago}}</div> </td> <td class="text-center"> <div>botones</div> </td> </tr> {% endfor %} </tbody> </table> {% endif %} -
What is the best way to validate data in Django REST framework?
I have tried validating incoming data in my serializer depending on the necessary validation. is there any standard I should follow when I am doing this. -
how can I add sidebar items
I'm doing control panel right now and how can I add sidebar items in django control panel, I searched I find some info but none of them how they add ready control panel? -
Gunicorn + Nginx - Resource temporarily unavailable while connecting to upstream
We are using gunicorn + supervisor + nginx to run django app using docker environment on beanstalk Issue is supervisor shows that gunicorn is up but all requests fails with 502 response code from nginx. Ideally I think supervisor should restart gunicorn process since it's not able to respond any request successfully. server_tokens off; upstream wsgi_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/run/django_app.sock fail_timeout=0; } server { location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Protocol $http_x_forwarded_proto; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 60s; proxy_read_timeout 60s; proxy_pass http://wsgi_server; } } 2022/10/10 12:35:26 [error] 21#21: *728396 connect() to unix:/run/django_app.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 172.31.53.68, server: *.service.vpc, request: "GET /user/ HTTP/1.1", upstream: "http://unix:/run/django_app.sock:/user/", host: "service.vpc" Additionally, How to debug hanged gunicorn worker to figure out where exactly the problem lies ? -
how do solve import error in django project
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable i have activated the virtualenv on many but yet I can't run the server -
Django/SQLite : Converting event-wise table to timeserie
I have a SQLite database (with Django as ORM) with a table of recorded change events (an Account is assigned a new Strategy). I would like to convert it to a timeserie, to be able to have on each day, the Strategy that the Account was following. Here is a preview of my table : and here is the expected output : For the sake of simplicity, I only showed one account as example but there is several, so a group by operation on account_id could be the start. Also, there can be more than 1 change/day. In this case, we select the last change of the day, as the desired timeserie output must have only one value per day. My question is completely similar to this one, but in SQL, not in BigQuery (and to be fully transparent I'm not entirely sure I understood properly what was hapenning in the unnest part they proposed). I have a working solution in pandas but it is very ugly (with reindex and fillna), and I'm quite sure there is an elegant and simple solution in SQL (or maybe even better with Django ORM). -
Django not showing new changes in production
I've changed env file and models.py for media app. When i check the files, the code shows the latest version, which is correct. When i visit the page, i don't see any changes. On my local environment i see the changes. I've done the following sudo systemctl restart nginx sudo systemctl restart uwsgi then i tried touch on uwsgi/admin.ini touch admin.ini sudo systemctl restart uwsgi then i deleted __pycache__ I restarted the instance and the changes aren't showing? I checked the env file and still using old credentials. There are no errors in the logs? How can i debug this? -
Django HttpResponseRedirect doesn´t lead to the page
I am working on the CS50 project2 commerce. I try to create a new list but when I click on the submit button, it doesn´t redirect to the index page as I want. Anybody can help please? enter image description here def createlisting(request): if request.method == "GET": allCategories = Category.objects.all() return render(request, "auctions/create.html", { "categories": allCategories }) else: # get the data from the form title = request.POST["title"] description = request.POST["description"] imageurl = request.POST["imageurl"] price = request.POST["price"] category = request.POST["category"] currentuser = request.user # get the contents categoryData = Category.objects.get(categoryName=category) #create new list object newListing = Listing( title=title, description=description, imageUrl=imageurl, price=float(price), category=categoryData, owner=currentuser ) newListing.save() return HttpResponseRedirect(reverse("index")) -
How to Display or accept names instead of ids in Django Superadmin while using GenericFroeignKey
I have a model for my project which is using GenricFroeignKeys for adding Stakeholders to Projects and Reposistories both. The model is from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType class StakeHolder(models.Model): """Model class for Stakeholders of Project and Repos""" name = models.TextField() email = models.EmailField() def __str__(self): return self.name class Role(models.Model): """This is the model for Role that the stakeholders will have o projects and repos""" name = models.TextField() def __str__(self): return self.name class ProjectRepoStakeHolder(models.Model): """This is a generic models used to define stakeholders on project and repos""" stake_holder = models.ForeignKey(StakeHolder, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) limit = models.Q(app_label='pr_reviews', model='repository') | \ models.Q(app_label='pr_reviews', model='project') # Fields that are mandatory for generic relations content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit,) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.stake_holder.name + "/" + self.role.name + "/" + self.content_object.name class Project(models.Model): """Model class for Project""" name = models.TextField(unique=True, blank=False, null=False) uuid = models.UUIDField(unique=True, blank=False, null=False) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Repository(models.Model): """Model class for Repository""" project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=False, null=False) name = models.TextField(unique=True, blank=False, null=False) uuid = models.UUIDField(blank=False, null=False) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = … -
What are these unknown client errors on GAE instance?
I deployed Django Application on GAE. After that, I'm getting a client error on unknown files. Those files are below. I know only favicon.ico because I haven't uploaded it yet. But I don't know others. Almost of them look about WordPress. Are these client errors attacks for WordPress files on GAE? How can I stop these? Thank you. -
sqlfuction to django method
I have this postgresql function. Can I convert this function to django-method? I have implemented these functions in sql, but I would like to implement these functions so that they can be used in django or may I ask if there is a way to use the raw-query function separately in django? CREATE EXTENSION IF NOT EXISTS "pgcrypto"; DO $$ BEGIN CREATE DOMAIN SHORTKEY as varchar(11); EXCEPTION WHEN duplicate_object THEN null; END $$; CREATE OR REPLACE FUNCTION shortkey_generate() RETURNS TRIGGER AS $$ DECLARE gkey TEXT; key SHORTKEY; qry TEXT; found TEXT; user_id BOOLEAN; BEGIN qry := 'SELECT id FROM ' || quote_ident(TG_TABLE_NAME) || ' WHERE id='; LOOP IF NEW.id IS NOT NULL THEN key := NEW.company_id; user_id := TRUE; IF length(key) <> 11 THEN RAISE 'User defined key value % has invalid length. Expected 11, got %.', key, length(key); END IF; ELSE gkey := encode(gen_random_bytes(8), 'base64'); gkey := replace(gkey, '/', '_'); -- url safe replacement gkey := replace(gkey, '+', '-'); -- url safe replacement key := rtrim(gkey, '='); -- cut off padding user_id := FALSE; END IF; EXECUTE qry || quote_literal(key) INTO found; IF found IS NULL THEN EXIT; END IF; IF user_id THEN RAISE 'ID % already exists in … -
My django project is running correctly on Heroku but the WebSocket request is not going
My django project is running correctly on Heroku but the WebSocket request is not going in working properly in local environment asgi.py import os import django from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'espere.settings') django.setup() # application = get_asgi_application() django_asgi_app = get_asgi_application() import chat_app.routing application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( chat_app.routing.websocket_urlpatterns ) ) ), }) settings.py # WSGI_APPLICATION = 'espere.wsgi.application' ASGI_APPLICATION = 'espere.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } Procfile web: daphne espere.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker -v2 -
Django REST framework returning empty queryset even though the shell/print returns items
My JSON response to GET http://localhost:8000/v1/tags/search is [] But it should contain a list of tags. I've registered the route with DRF: router.register(r"tags/search", TagSearchViewSet, basename='tag-search-list') The view: from taggit.models import Tag class TagSearchViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = TagSearchSerializer paginator = None def get_queryset(self): queryset = Tag.objects.all() print(queryset) return queryset The serializer: from taggit.models import Tag class TagSearchSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' That print() statement prints out <QuerySet [<Tag: something>, <Tag: else>, <Tag: mytag2>, <Tag: mytag1>, <Tag: mytag3>, <Tag: mytag4>]> In python manage.py shell I can also print out tags using > from taggit.models import Tag > tags = Tag.objects.all() > tags <QuerySet [<Tag: something>, <Tag: else>, <Tag: mytag2>, <Tag: mytag1>, <Tag: mytag3>, <Tag: mytag4>]> So why is the response an empty list? -
Control panel file manager
I'm making a basic panel with Django, I add sidebar, navbar some process but I need to add a file manager and I searched but couldn't find anything. Can you help me? -
Custom QuerySet for a Django admin action
# Customers model Customers(models.Model): name = models.CharField(max_length=255) emails = ArrayField(models.EmailField(), default=list, blank=True) ... ... ... I have a QuerySet which has all the information according to model of all the selected customers. # Django admin action def get_email_ids(self, request, queryset): """ QuerySet here is all the information according to model of all the selected customers. """ # new_queryset = ? return generate_csv( request, queryset, filename="email-ids.csv", ) I want a new custom QuerySet which only has the customer name and email id's. But it should be in the following way. If a customer has 10 email id's then there should be 10 rows for that customer in the QuerySet. e.g. customer1 email1@email.com customer1 email2@email.com customer1 email3@email.com customer1 email4@email.com customer2 emailother@email.com How to achieve this for new_queryset?