Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-rearart sequence of postgres id field with 0 instead of 1
I want to reset the sequence of a "postgresql" table to start from "0" in a django application. My code is: views.py sequence_sql = connection.ops.sequence_reset_sql(no_style(), [ModelName]) with connection.cursor() as cursor: for sql in sequence_sql: cursor.execute(sql) print("sequence reset") The sequence is restarted successfully; but with "1". I want the sequence to start from 0. How can I achieve that? -
Change date format to "dd-mm-yyyy" in Django rest framwork
Hi below is my request payload and i am using normal serializer and i want to save date in "dd-mm-YYYY" format in DB { "start_date": "2022-10-10", "end_date": "2022-12-10" } Here is my serializer class StudentSerializer(serializers.Serializer): start_date = serializers.DateField() end_date = serializers.DateField() Note: I don't want to change the requested payload date format only change on saving the record by changing the format to "dd-mm-YYY". -
502 Bad Gateway | Gunicorn - ngnix - django
I wanted to that my dango app run in server and I tried with gunciron. When i run my app with gunicorn, server is working. I mean `# gunicorn --bind 0.0.0.0:8000 myapp.wsgi` is working But if i disconnect with server, server is not working. So i used ngnix. I followed this source https://github.com/satssehgal/URLShortnerDjango- . I did all them. I controlled my path but all path is right. What can i do for server work? -
Randomize Quiz Answers Order Django
hi everybody i want to randomize quiz answers in django this is models.py class Questions(models.Model): question = models.CharField(max_length=264, unique=True) point = models.PositiveIntegerField() def questionanswers(self): return self.question_answers.all() def __str__(self): return self.question class Answers(models.Model): question_id = models.ForeignKey(Questions, on_delete=models.CASCADE, related_name='question_answers') answer = models.CharField(max_length=20) is_true = models.BooleanField() def __str__(self): return self.answer and this is views.py question_list = Questions.objects.all().order_by('?')[:6] context['questions'] = question_list return context and this is template {% for answer in question.questionanswers.all %} <li class="col-sm-6" style="margin-bottom: 10px"> <button class="btn btn-primary" type="button" id="{{answer.id}}" value="{{answer.id}}">{{answer}}</button> </li> {% endfor %} </ol> </div> </div> {% endfor %} -
Get E-commerce products based on past searches
I am building an e-commerce store with django. I want the product page to return products based on the past searches of the user. If user A has always searched for cars and bikes, the product page would return more cars and bikes products more than other products. What is the best way to go about this? Do I save every search users make and run an algorithm to get results for that user or there are better ways to go about this. -
Django+React : CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response
I am using Django for my backend and React for my Frontend. When I try to send a POST request, I receive : Access to XMLHttpRequest at 'http://localhost:8000/package/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response. I have combined a lot of answers that I found such as How to use csrf_token in Django RESTful API and React? and Django and React: csrf cookie is not being set in request header but still no luck. 'corsheaders' is in my INSTALLED APPS Middleware settings MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS settings: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CSRF_TRUSTED_ORIGINS = ['http://localhost:3000'] from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ('cache-control',) Django view.py from django.shortcuts import render from django.views.generic.edit import CreateView from .forms import PackageForm from django.utils.decorators import method_decorator from django.views.decorators.csrf import ensure_csrf_cookie class PackageFormView(CreateView): form_class = PackageForm initial = {'key': 'value'} template_name = 'package_form.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) @method_decorator(ensure_csrf_cookie) def post(self, request, *args, **kwargs): form = … -
How to enable GEOS in Spatialite on Windows 10?
I am installing Spatialite for use in GeoDjango on a Windwos 10 64 bit system. I have already installed GEOS, PROJ, and GDAL from source in my command prompt. As spatialite requires using nmake on windows, I am using the Visual Studio 2017 command prompt to build it, however, in the README for libspatialite 4.2.0 it states that > cd c:\libspatialite-3.1.0 > nmake /f makefile.vc > nmake /f makefile.vc install Please note: standard definitions in 'makefile.vc' assumes: - enabling PROJ - disabling GEOS If you want to alter the default behaviour then make modifications in 'makefile.vc'. Also note that 'libspatialite-geos.def' contains those external symbols to be exported from the DLL when you build GEOS. as I am using GeoDjango for geographic queries I think that GEOS will be necessary. How can I enable GEOS in the makefile.vc? It doesn't seem clear to me how to do that. For convenience, here is the full makefile.vc below. # $Id: $ # # NMAKE Makefile to build libspatialite on Windows # !INCLUDE nmake.opt LIBOBJ = src\gaiaaux\gg_sqlaux.obj src\gaiaaux\gg_utf8.obj \ src\gaiaexif\gaia_exif.obj src\gaiageo\gg_advanced.obj \ src\gaiageo\gg_endian.obj src\gaiageo\gg_ewkt.obj \ src\gaiageo\gg_geodesic.obj src\gaiageo\gg_geoJSON.obj \ src\gaiageo\gg_geometries.obj src\gaiageo\gg_geoscvt.obj \ src\gaiageo\gg_gml.obj src\gaiageo\gg_kml.obj \ src\gaiageo\gg_relations.obj src\gaiageo\gg_shape.obj \ src\gaiageo\gg_transform.obj src\gaiageo\gg_vanuatu.obj \ src\gaiageo\gg_wkb.obj src\gaiageo\gg_wkt.obj \ src\gaiageo\gg_extras.obj … -
APIView post function not adding to database
I have my follow model: class Follow(models.Model): user = models.ForeignKey( "User", related_name="follower", on_delete=models.CASCADE) following_user = models.ForeignKey( "User", related_name="following", blank=True, on_delete=models.CASCADE) date_followed = models.DateTimeField(editable=False, default=timezone.now) class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'following_user'], name="unique_followers") ] ordering = ["-date_followed"] def __str__(self): return f"{self.user.username} follows {self.following_user.username}" and serializer: class FollowSerializer(serializers.ModelSerializer): class Meta: model = Follow fields = ['user', 'following_user', 'date_followed'] Then in my views I have an APIView that creates the follow: class FollowingView(APIView): permission_class = [permissions.IsAuthenticated] queryset = Follow.objects.all() serializer_class = FollowSerializer def post(self, request): user = request.data.get('user') following_user = request.data.get('to_user') try: follow = Follow.objects.create( user=user, following_user=following_user) follow.save() serializer = FollowSerializer(follow) print(serializer.data) def __str__(self): return f"{self.request.username} follows {self.following_user_id.username}" return Response(serializer.data, status=status.HTTP_201_CREATED) except: return Response(status=status.HTTP_400_BAD_REQUEST) Not sure what is wrong. I am able to print the params but seems like the create function isn't going through. Appreciate any help! -
Share large python objects efficiently among requests in Django?
I'd like to share some large python objects in Django. They are just big tables of data that I'd like to quickly randomly access in memory. Think of just reading a dict that's, say 35M on disk. So, not huge, not small. I'm considering them immutable. That is, read in on initialization, never change them. I'm willing to restart the server to get changes. What is the best, most Django-friendly way to do this? This question is like mine. This answer describes how to use Django's low-level in-memory cache. Reading the documentation, there is an in-memory cache that is in-process and thread-safe. Perfect. However, only objects that can be pickled. I don't want my 35M python object pickled, that seems awkward. And then does getting it back out unpickle it again? Per request? That sounds slow. This blog post mentions django-lrucache-backend, that skips the pickling. However, it was last updated 2 years ago, and also says not to use it for "large data tables" (not sure why). Recommendations? -
the request in postman works but in angular it doesn't
enter image description here I send the bearer token returned by the login and it works enter image description here the token arrives but the api response is Authentication credentials were not provided. -
How to run "SELECT FOR UPDATE" instead of "SELECT" when adding data in Django Admin?
In PersonAdmin():, I overrode response_add() with select_for_update() so that write skew doesn't occur then only 2 persons can be added on Add person and overrode save_model() so that obj.save() works only when changing a person on Change person as shown below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): # Here obj_count = super().get_queryset(request).select_for_update().all().count() if obj_count < 2: obj.save() return super().response_add(request, obj, post_url_continue) def save_model(self, request, obj, form, change): last_part_of_path = request.path.split('/')[-2] if last_part_of_path == "change": obj.save() # Here But, when adding a person on Add person as shown below: SELECT is run instead of SELECT FOR UPDATE as shown below. *I use PostgreSQL and these logs below are the queries of PostgreSQL and you can check On PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": So, how can I run SELECT FOR UPDATE instead of SELECT when adding a person on Add person? -
Django: render django-countries's countries as a dropdown list (with search option)
I'm trying to make a drop down list, so users can: 1.- Select country they wanna see: from home, they'd be redirected to specific country. example: mydomain.com to: mydomain.com/mx 2.- to help them, they could also type and search specific country, and then would be redirected. I've this: forms.py: from django import forms from django_countries.fields import CountryField class CountryForm(forms.ModelForm): class Meta: model = CountryField fields = ['country'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['country'].widget.attrs.update({"class": "form-control"}) # or iterate over field to add class for each field for field in self.fields: self.fields[field].widget.attrs.update({'class':"form-control"}) html: {% extends '_base.html' %} {% load static %} {% block title %}Home page{% endblock title %} {% block content %} <form method="post" class="form-group"> {% csrf_token %} <div class="form-group col-md-12 mb-3"> <label for="{{ form.owner_name.label }}">{{ form.owner_name.label }}</label> {{ form.owner_name }} </div> <div class="form-group col-md-12 mb-3"> <label for="{{ form.car_type.label }}">{{ form.car_type.label }}</label> {{ form.car_type }} </div> <hr class="mb-4"> <button type="submit" class="btn btn-secondary btn-lg btn-block">Go to country</button> </form> {% endblock content %} -
Django signals pre_delete accessing request.user
Is there a way to access request.user within pre_delete signal? I found an answer but that was 10 years ago and doesn't work with the current version of Django. -
How to add a custom field to the Django admin login page
To authenticate, 3 fields are needed: user_id password account_id Each account_id defines an isolated space and the user_id is unique only inside its respective account_id. I've created a custom backend authentication and I can authenticate successfully. The problem is that the login Django Admin form has user_id and password fields by default. I would like to add the account_id field in the original Django form template by only subclassing AuthenticationForm, is it possible? There's a similar question here but he's using a custom login template: Add custom field to Django Admin authentication form Existing code.. Model: class HeliosUser(AbstractUser, DateModelBase): username = None user_id = models.CharField(max_length=255) USERNAME_FIELD = "user_id" REQUIRED_FIELDS = ["account_id", "role", "email"] objects = HeliosUserManager() email = models.EmailField() account_id = models.ForeignKey( "agent.Agent", on_delete=models.RESTRICT, ) ... Backend: class SettingsBackend(BaseBackend): def authenticate( self, request, user_id=None, account_id=None, password=None, **kwargs ): try: user = HeliosUser.objects.get( user_id=user_id, account_id=account_id ) except HeliosUser.DoesNotExist: return None if user.check_password(password): return user return None def get_user(self, user_id, account_id): try: return HeliosUser.objects.get( user_id=user_id, account_id=account_id ) except HeliosUser.DoesNotExist: return None Admin site: class HeliosUserAdmin(admin.AdminSite): site_title = "Helios Administration" site_header = "Helios Administration" index_title = "Helios Administration" login_form = HeliosAuthenticationForm admin_site = HeliosUserAdmin() Authentication form: class HeliosAuthenticationForm(AuthenticationForm): account_id = forms.ModelChoiceField(queryset=Agent.objects.all()) Thank's in … -
Is there any way to automatically set Debug True Django application
I have a Django API that is being deployed in PythonAnywhere. For that, I can not let the default option in settings.py as True: DEBUG=True However, the app also has a Swagger page using drf-yasg library. For that to work locally, I have to set the debug option as true. However is being troublesome to maintain it, and I often mistakenly commit it as True to the repository. Is there anyway I could manage this option so whenever I am running locally, it will automatically set it to True, but leave it as False by default? DEBUG=False -
Pass parameters or re use attributes in django serializer methods
i have this code: class InvoiceSerializer(serializers.ModelSerializer): val = serializers.SerializerMethodField() cost = serializers.SerializerMethodField() class Meta: model = Facturacion fields=["val", "cost", "others..."] def get_cost(self, object, va): print(va, "myvalue") return 1 def get_val(self, object): val = Va.objects.get(id=1) serializer = ValSerializer(valorUnitario) self.get_cost(self, object, (serializer.data)['val']) return (serializer.data)['val'] the (serializer.data)['valorUnitario'] is returning a number, i just want to pass this value to the get_cost function but it give me the message InvoiceSerializer.get_cost() takes 3 positional arguments but 4 were given. I dont want to make all the process of get_val again for optimization reasons, i just want to use the same data but in get_cost. Another form i was trying was this: def get_cost(self, object): return self.val val its supposed to be filled with the get_val method (and it shows correctly when i consume the api); but it gives the message: AttributeError: 'InvoiceSerializer' object has no attribute 'val' how can i re-use the attribute val? -
How to get ImageField url when using QuerySet.values?
qs = self.items.values( ..., product_preview_image=F('product_option_value__product__preview_image'), ).annotate( item_count=Count('product_option_value'), total_amount=Sum('amount'), ) product_option_value__product__preview_image is an ImageField, and in the resulting QuerySet it looks like product_preview_images/photo_2022-12-10_21.38.55.jpeg. The problem is that url is a property, and I can't use media settings as images are stored in an S3-compatible storage. Is it possible to somehow encrich the resulting QuerySet with images URLs with a single additional query, not iterating over each one? -
LTM Load Balancer drops connection while App waiting for big SQL query response
Newly implemented LTM Load Balancer drops connection while our App is waiting for big SQL query response. Now i need to find some workaround because appearently extending timeouts on LB is not a way to go. App runs on Django and MSSQL Is there any possibility to lets say send query to DB -> get some kind of transaction ID (JWT?) -> close connection -> create GET with some transaction ID to check if there is result of this query? (Not sure how this transaction ID would be stored on DB side tho) Is Pagination doin something like this? I would like to avoid making this like this: Create API endpoint which runs queries to DB -> Send request to API -> DB process with query and put results in new table -> send query to new table -
504 Gateway Timeout (Gunicorn-Django-Nginx) Docker Compose Problem
There is one process backend which take around 1-2 minutes to process. The loading screen runs for 1 minute and shows 504 Gateway Timeout Here's the log in nginx.access.log 172.18.0.2 - - [16/Dec/2022:23:54:02 +0000] "POST /some_request HTTP/1.1" 499 0 "http://localhost/some_url" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" But from the django debug log, I can see that the POST request is still processing at the backend docker-compose.yml timeout is set to 300, without it, the browser will return 502 error (connection prematurely closed) services: web: image: genetic_ark_web:2.0.0 build: . command: bash -c "python manage.py collectstatic --noinput && gunicorn ga_core.wsgi:application --bind :8000 --timeout 300 --workers 2 --threads 4" This is all the params I have tried in nginx.conf but still the 504 timeout is returned after 60s server { # port to serve the site listen 80; # optional server_name server_name untitled_name; ... # request timed out -- default 60 client_body_timeout 300; client_header_timeout 300; # if client stop responding, free up memory -- default 60 send_timeout 300; # server will close connection after this time -- default 75 keepalive_timeout 300; location /url_pathway/ { proxy_pass http://ga; # header proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_connect_timeout 300s; proxy_send_timeout … -
Django Comments Xtd Comments are not nesting
I followed the tutorial on https://django-comments-xtd.readthedocs.io, everything seems to work find, the forms and the comments are working, but on the website they are not displayed properly. instead of looking like this: They all look like this The reply is not nesting under the comment but in the admin its working you can see how it nests take a look: Please help -
Is it an antipattern to use `request.POST or None` to initialize a Django form?
I came across a blog post arguing that the following is an antipattern: def some_view(request): form = MyForm(request.POST or None) # … Source: https://www.django-antipatterns.com/antipattern/using-request-post-or-none.html However, I'm not clear on the problems that using it could cause. I have used this to keep my views concise, without noticing any unexpected behavior. Is this an antipattern? If so, why? -
Error after migrating django database to postgresql
I have recently changed my database from sqlite3 in django to postgresql as I prepare my app for production. After making changes in settings.py, I have tried making migrations and I am getting an error. After running python manage.py migrate --run-syncdb I get the error below in the terminal System check identified some issues: WARNINGS: users.Document.uploaded_at: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` users.Order.amount: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field users.buyer.uploaded_at: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` Operations to perform: Synchronize unmigrated apps: channels, chatapp, crispy_forms, messages, payments, staticfiles, users Apply all migrations: admin, auth, contenttypes, sessions Synchronizing apps without migrations: Creating tables... Creating table users_user Creating table users_document Creating table users_buyer Creating table users_category Creating table users_service Creating table users_profile Creating … -
Editing it in html when we pull data from Django
The news saved in the system will come to my page. I pulled data from django. Currently the data is coming one after the other. I want to pull 3 data side by side after it's will be 3 data below again and so it will go like that. How can i do this? My kategori.html: {% extends "homebase.html" %} {% block title %} {{ setting.title }} {% endblock %} {% block keywords %} {{ setting.keywords }} {% endblock %} {% block description %} {{ setting.description }} {% endblock %} {% block head %} <link rel="icon" type='image/png' href='{{ setting.icon.url }}'/> {% endblock %} {% block header %}{% include 'header.html'%}{% endblock %} {% block sidebar %}{% include "sidebar.html" %}{% endblock %} {% block content %} {% load static %} <section id="news" data-stellar-background-ratio="2.5"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="section-title wow fadeInUp" data-wow-delay="0.1s"> <h2>TIBBİ BİRİMLER KATEGORİSİ</h2> </div> </div> <div class="col-md-4 col-sm-6" > <!-- NEWS THUMB --> <div class="news-thumb wow fadeInUp" data-wow-delay="0.4s"> {% for rs in category %} <a href="kategori.html"> <img src="{{rs.image.url}}" class="img-responsive" alt=""> </a> <div class="news-info"> <span>{{rs.create_at}}</span> <h3><a href="bos-sayfa.html">{{rs.title}}</a></h3> <p>{{rs.description}}</p> <div class="author"> <div class="author-info"> <p>{{rs.keywords}}</p> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </section> {% endblock %} {% … -
Postgresql with heroku
I have a Postgres database on my PC with all data that I need so far in the project, my app is deployed on Heroku without any data in the database Heroku gave to me. I want to provide my app on Heroku with data from my DB. I tried using pg_dump but couldn't figure out what I was doing wrong, I thought I could host my DB and then somehow connect it. -
Filtering Django API by time not working before "10:00:00"
I made this Django API to search by date and time, the date filter works perfectly but once I start trying to filter by time it only filters data from 10:00:00 to 24:00:00 and completely disregards filtering anything stamped 00:00:00 to 09:59:59. Here's an example of the way I'm storing my data in my db: "id": 10, "added_date": "2022-12-16", "added_time": "10:12:54", "name": "Name", Here is my code: class Search(generics.GenericAPIView): def get_queryset(self): start_date= self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') start_time= self.request.query_params.get('start_time') end_time = self.request.query_params.get('end_time') try: search= objects.filter(added_date__range=[start_date, end_date], added_time__range=[start_time, end_time]) return search.all() except Exception as exception: return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR) def get(self, request): try: queryset = self.get_queryset() serializer = SearchSerializer(queryset, many=True) response = Response(serializer.data) return response except Exception as exception: return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR) I believe the "0" in front of times such as 09:30:00 is throwing off the search. However in the table 09:04:10 would show up as 9:4:10 and it still giving problems. Any help would be greatly appreciated, thank you!