Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GCP-Django-IP Address based error: write EPROTO error:100000f7 OPENSSL_internal
This is among the strangest issues I have seen. When I make a postman GET api call to this url in the US, I do not have any problems, it gives me the JSON I need. However, when I make the same API call in Canada (even using the same computer), it gives the following error: Error: write EPROTO error:100000f7:SSL routines:OPENSSL_internal:WRONG_VERSION_NUMBER:../../third_party/boringssl/src/ssl/tls_record.cc:242: You don't need Postman, you can also just navigate to the url to see the response. The API is hosted on GCP (Google Cloud Platform) and uses the Python Django framework. There's no IP Address restrictions that I setup personally I have gone through several responses with this error, but none have any solution that worked, and I'm not sure what to look for now -
Dropdown values for django form not showing up in view
I am trying to make a todo app in django but I am not able to get a dropdown to set a category populate. This is what the form looks like when I render everything: What I am expecting was that the dropdown would have the options 'Personal' and 'Professional' This is my model: from django.db import models class Category(models.Model): CATEGORY = (('Personal', 'Personal'), ('Professional', 'Professional')) type = models.CharField(max_length=100, null=True, choices=CATEGORY) def __str__(self): return self.type class Item(models.Model): created_at = models.DateTimeField(auto_now=True) task = models.CharField(max_length=200) completed = models.BooleanField(default=False) category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) def __str__(self): return (f"{self.created_at}: {self.task}") This is the form I am trying to use: from .models import Item from django import forms class AddItem(forms.ModelForm): class Meta: model = Item fields = ['task', 'category'] This is the template: <div> <h1>Your todo task</h1> <br> <form method="POST" action="{% url 'home' %}"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-secondary">Add a task</button> </form> </div> Thank you for your time and any information you can provide. -
Solve Django Rest Framework TypeError: Cannot set GeoPoint SpatialProxy (POINT) with value of type: <class 'dict'>
I am working with Django, Django Rest Framework, Django Rest Framework GIS and POSTgis database to create an endpoint that should upload a geografical point and all its related information. I have defined a Model, Serializer and View for that purpose. But when making a request using postman i am getting the following error: TypeError: Cannot set GeoPoint SpatialProxy (POINT) with value of type: <class 'dict'> I am currently working with: Django==3.2.16 djangorestframework==3.12.0 djangorestframework-gis==1.0 Model definition: from django.contrib.gis.db import models from django.utils.translation import gettext_lazy as _ class GeoPoint(models.Model): POINT_TYPE_CHOICES = ( ("limite_cusaf","Límite CUSAF"), ("limite_cusaf_di","Límite CUSAF y DI"), ("limite_2_di","Límite 2 DI"), ("limite_3_di_mas","Límite 3 DI o más"), ("otros","Otros"), ) geom = models.PointField(verbose_name=_("Localización"), srid=4326) id_cusaf = models.CharField(_("ID CUSAF"), max_length=50) code = models.CharField(_("Código Punto"), max_length=50) point_type = models.CharField(_("Tipo de Punto"), max_length=50, choices=POINT_TYPE_CHOICES) observations = models.TextField(_("Observaciones"), null=True, blank=True) def __str__(self): return self.cod_punto class Meta: db_table = 'aggregate_geopunto' managed = True verbose_name = 'Punto' verbose_name_plural = 'Puntos' Serializer: from rest_framework_gis.serializers import GeoFeatureModelSerializer class GeoPointSerializer(GeoFeatureModelSerializer): class Meta: model = GeoPoint geo_field = "geom" fields = ('id','geom','id_cusaf','code', 'point_type','observations',) read_only_fields = ['id',] View: class GeoPointAPICreate(generics.CreateAPIView): authentication_classes = [] permission_classes = () queryset = GeoPoint.objects.all() serializer_class = GeoPointSerializer This is the image of the POSTman request: { "type": "Feature", "geometry": … -
Django Many To Many table filter makes too many sql queries
I'm filtering my Department model with django_filters. But it makes too many queries. How can I fix it? # models.py class Branch(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Branches" def __str__(self): return self.name class Department(models.Model): name = models.CharField(max_length=100) branch = models.ManyToManyField(Branch, related_name="department") def __str__(self): return self.name _ # views.py class DepartmentListAPIView(generics.ListAPIView): queryset = Department.objects.all() serializer_class = DepartmentSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = DepartmentFilter _ # serializers.py class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = "__all__" _ # filters.py class DepartmentFilter(filters.FilterSet): branch = filters.CharFilter(field_name="branch__id", lookup_expr="in") class Meta: model = Department fields = "__all__" -
Creating a superuser in custom user model
I have a custom user model as follows. When i try to create a superuser, it asks me organisation (organisation_id) which i don't want to give for superusers(because it makes sense only if the users give the organisation, as i need create a superuser just to view database and also superusers don't fall under any organisation). So what should i do to rectify this problem. #models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class Organisation(models.Model): organisation_name = models.CharField(max_length = 256) contact_no = models.IntegerField() email = models.EmailField() class Meta(): unique_together = ['organisation_name','email'] def __str__(self): return self.organisation_name class MyUserManager(BaseUserManager): def create_user(self, username, organisation, email, password): email = self.normalize_email(email) user = self.model(username=username, email=email, organisation=organisation) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, username, email, password, organisation): user = self.create_user(username=username, email=email, password=password,organisation=organisation) user.is_superuser = True user.is_staff = True user.save() return user class MyUser(AbstractBaseUser): username = models.CharField(max_length=256,unique=True) email = models.EmailField(max_length=256) organisation = models.ForeignKey(Organisation,on_delete=models.CASCADE,null=True) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email','organisation'] objects = MyUserManager() def __str__(self): return self.username #views.py class Create_Accounts(CreateView): model = models.MyUser fields=('__all__') template_name = 'accounts/create_account.html' success_url = reverse_lazy("accounts:inner_index") #settings.py AUTH_USER_MODEL = 'accounts.MyUser' -
How to get mail after filling contact form using Django
If the user fills the contact form and submits it, how can the details filled in the contact form be mailed to the admin using this mail? Am I storing the contact details in database but they should come through mail Please help thanks -
How to make telegram bot constructor?
I need to make a website in django that creates single telegram bots. The user enters the bot token and the site creates and launches the bot. But I don't know how to do it, what to use and how to run how many telegram bots? Is it even possible to do this? I searched for the source codes of similar sites but did not find anything useful Thanks in advance for your replies. -
How to create i18n switcher for Django Admin?
I could create i18n switcher for English and French below in Django following The set_language redirect view and this is how I set up translation(English and French) in Django. *I use Django 4.2.1: # "core/settings.py" from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path("my_app1/", include('my_app1.urls')), ) urlpatterns += [ path("i18n/", include("django.conf.urls.i18n")) ] # "templates/index.html" {% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> {% translate "Hello" %} {% trans "World" %} Then, I can switch French to English as shown below: And, I can switch English to French as shown below: But, I don't know how to create it for Django Admin. So, how can I create i18n switcher for Django Admin? -
Django API header cannot be fetched
Frontend is sending POST request with code and then I want to return qr code and a token. When I try to fetch 'token' header it returns none @api_view(['POST']) @csrf_exempt def Create_new_doc(request): code = json.loads(request.body) code = code['code'] characters = string.ascii_letters + string.digits token = ''.join(random.choice(characters) for _ in range(20)) generate_qr_code.generate_qr(token) image_path = f"/files/qr_{token}.jpg" image_file = open(image_path, 'rb') response = FileResponse(image_file, content_type='image/jpeg') response['token'] = token response.status_code = 200 return response This is frontend part - getting image url works just fine fetch('http://127.0.0.1:8000/create-new', requestOptions) .then((response) => { if (response.ok) { return response.blob().then((blob) => { var tokeN = response.headers.get('token'); console.log(response.headers.get('token')) console.log('Token:', tokeN); const imageUrl = URL.createObjectURL(blob); console.log('Image URL:', imageUrl); return { tokeN, imageUrl }; }); } Yeah, literary have no idea why it does not work -
How to run an infinite loop function in django celery on startup?
I want to make a django website that will display data from the database. And the parser will add information to this database. And I want to make it so that during the launch of the site it also starts (only once) and parses information in an endless loop. Or make it so that django celery calls a function, but only if this function is not already called. And I would like to know how to do it. I tried to write this in the view.py file from .tasks import my_task my_task.delay() But as I understand it, this is bad because when I wrote any command in the terminal, I opened a browser for parsing -
Django CSRF Protect During POST to External URL?
Context I am building a website in Python using the Django Framework and Stripe for user payment. I am currently In the testing/debug phase in local development, still far from a production build. Currently at a brick wall with CSRF Protection and can not find a solution. My checkout works perfectly with no CSRF Protection. There are other topics of very similar issues on here but due to my lack of knowledge around CSRF protection itself, I hope someone can enlighten me on what to do in my specific scenario. This situation should have a common practice solution but I've studied the majority of both Django and Stripe's Documentation with no luck. Criticism is welcome, this is my first StackOverflow post. The Problem I have a view function which enables the purchase of a product on my site by sending the user to Stripes External Checkout page. views.py @csrf_exempt # CSRF Protection disabled for testing def create_checkout_session(request): if request.method == 'POST': try: checkout_session = stripe.checkout.Session.create( ... ) except Exception as e: ... return redirect(checkout_session.url) During testing I disabled CSRF Protection on my view function using Django's @csrf_exempt decorator. I did this in order to bypass the '403 CSRF Verification failed' … -
Django + Elastcisearch index is not generate getting direct access to system indices will be prevented by default
While trying to create elasticsearch index using rebuild command (myenv) C:\Misc\Django_elasticsearch>python manage.py search_index --rebuild C:\Misc\Django_elasticsearch\myenv\Lib\site-packages\elasticsearch\connection\base.py:200: ElasticsearchWarning: this request accesses system indices: [.security-7], but in a future major version, direct access to system indices will be prevented by default warnings.warn(message, category=ElasticsearchWarning) Are you sure you want to delete the '' indices? [y/N]: y But index did not generate I have added ELASTICSEARCH_DSL and added rest_framework,django_elasticsearch_dsl,django_elasticsearch_dsl_drf in seetings.py Please help... Check Elasticsearch server: Confirm that your Elasticsearch server is running and accessible. Getting proper response from localhost:9200 -
django-haystack Decimal __lt query
I have django project with django-haystack and xapian backend. I have created an index: sugar=indexes.DecimalField(null=True) Now I'm trying to filter the SearchQuery with different arithmetical operators, and I'm getting strange results (trying lt, lte, gt and gte with filter like: sqs.filter(sugar__lt=60)). I'm then filtering out None's, sorting the results and converting to float to get a better view on it. sqs.count()=130, len(sqs_lt)=114, len(sqs_gt)=130, len(sqs_lte)=0, len(sqs_gte)=16 vals_lt=[0.1, 0.1, 0.3, 0.3, 0.4, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.6, 0.6, 0.7, 0.8, 0.8, 0.8, 0.8, 1.0, 1.1, 1.1, 1.1, 1.1, 1.1, 1.3, 1.33, 1.4, 1.5, 1.8, 1.8, 2.0, 2.0, 2.0, 2.0, 2.1, 2.2, 2.2, 2.4, 2.5, 2.5, 2.78, 2.8, 2.9, 3.0, 3.07, 3.2, 3.2, 3.4, 3.6, 3.9, 4.0, 4.9, 6.0, 6.0, 6.2, 6.3, 6.3, 6.6, 12.0, 12.0, 12.4, 12.5, 13.7, 14.0, 18.0, 20.0, 22.0, 22.0, 23.0, 24.1, 24.8, 26.0, 26.0, 26.5, 27.7, 30.96, 34.0, 39.0, 40.0, 40.0, 41.0, 42.2, 42.5, 43.0, 46.0, 48.0, 51.1, 52.0, 54.0, 100.0] vals_gt=[0.1, 0.1, 0.3, 0.3, 0.4, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.6, 0.6, 0.7, 0.8, 0.8, 0.8, 0.8, 1.0, 1.1, 1.1, 1.1, 1.1, 1.1, 1.3, 1.33, 1.4, 1.5, 1.8, 1.8, 2.0, 2.0, 2.0, 2.0, 2.1, 2.2, 2.2, 2.4, 2.5, … -
Django and Ajax: prevent a page from refreshing when I click on the button (without jQuery)
In the home.hmtl page i have a combobox (independent, it is not connected to the database but to a list) and a textarea. I don't use the database. When I click on the button then I would like to print some text in the textarea (text which is in a list of the views.py file) What do I want to get? Everything happens correctly, but the page reloads immediately after clicking on the button. I tried to solve the problem using only Django, but I failed (maybe it's not possible), so I read what solutions are to use Ajax, jQuery and something in Javascript. I would like to solve the problem with AJax (without jQuery, and possibly without Javascript). I'm new to Django Considerations: I searched many question on Stackoverflow or various tutorials, but I couldn't solve. Apparently even though it's are similar questions, each solution is a different case with different problem and solutions. One solution I've found often, but it's not for me, is to replace type=submit with type=button and then add onclick which binds to a function in Javascript. I wouldn't need this function in Javascript, because I would like to keep everything in py files (the … -
IIS ignore persian character in url django project
I have developed a Django app on IIS that has some Persian URLs parts. The Problem is that the application completely ignore Persian parts. i config .NET Globalization like this:enter image description here but the urls ignored When I run the project locally on the server, the URLs work -
Trying to Publish a django app with a MySQL Database and a React front end to Heroku
I am trying to publish a django app with a MySQL database and a React front end to Heroku. It runs locally just fine, but I cannot get it to work on Heroku. My code is here: https://github.com/rmoscoe/odyssey, but there's not much of it yet. I'm just getting started. I'm able to push to Heroku, and the build and deployment complete with no errors. But when I visit the site, it just says "Bad Request (400)." The console similarly just says "Failed to load resource: the server responded with a status of 400 (Bad Request)." The logs don't say much more: "at=info method=GET path="/" host=odyssey-db3a471a3d45.herokuapp.com request_id=4f1b44ca-f023-4e72-b1be-d03f9dbde384 fwd="104.32.1.116" dyno=web.1 connect=0ms service=162ms status=400 bytes=428 protocol=https." I've scoured the internet and tried many different solutions, but nothing has made a difference. Some examples: manually running collectstatic before pushing using the heroku terminal to run npm install and npm start on the client side assorted changes to my Procfile and settings.py manually copying the contents of the static directory into the staticfiles directory Can anyone help me? Thanks! -
Deploying Django project to fly.io
I'm trying to deploy my Django project to fly.io and get strange error Running nameless-paper-520 release_command: python hw10/manage.py migrate release_command 5683d609cd778e completed successfully This deployment will: * create 2 "app" machines No machines in group app, launching a new machine Error: error creating a new machine: failed to launch VM: To create more than 1 machine per app please add a payment method. I do not want to create two machines, but only one. Where should I write this in fly.toml or Dockerfile? -
Django Tastypie - Inserting parent and child objects in a single atomic transaction
I am trying to implement REST API using PostgreSQL, Tastypie and Django. I managed to implement [GET] API endpoint, but I'm having troubles with implementing [POST] API operation. The cause of my troubles is the fact that I have a table "parent" which can have many child objects defined in Django. The definition of models is below: ` class Parent(models.Model): title = models.CharField(max_length=200, null=False, blank=False, unique=True) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) is_private = models.BooleanField(null=False, blank=False, default=False) class Meta: db_table = 'test_parent' class Child(models.Model): title = models.CharField(max_length=200, null=False, blank=False) parent = models.ForeignKey(Parent, on_delete=models.CASCADE, null=False, blank=False, related_name='components') is_mandatory = models.BooleanField(null=False, blank=False, default=False) is_visible_in_table = models.BooleanField(null=False, blank=False, default=False) is_visible_in_form = models.BooleanField(null=False, blank=False, default=False) options = models.JSONField(null=True, blank=False) note = models.TextField(null=True, blank=True) class Meta: db_table = 'test_child' ` This is the definition of Tastypie resources: ` class ChildResource(ModelResource): parent = fields.ToOneField('app.api.resources.test.ParentResource', attribute='parent') class Meta: list_allowed_methods = ('get', 'post',) detail_allowed_methods = ('get', 'post', 'patch', 'delete',) authorization = AnonymousCanPostAuthorization() authentication = MultiAuthentication( ApiKeyAuthentication(), CookieBasicAuthentication(), Authentication(), ) resource_name = 'test/child' queryset = Child.objects.prefetch_related('component').filter(is_active=True) always_return_data = True filtering = { "id": ('exact',), "components": ALL_WITH_RELATIONS, } class ParentResource(ModelResource): owner = fields.ToOneField( UserResource, attribute='owner', full=True, null=True ) components = fields.ToManyField( ChildResource, attribute='components', full=True, null=True ) class Meta: resource_name = … -
Nginx with GZIP not compressing Django responses even when it is enabled
I have a Django project that runs via Nginx web server. I've enabled gzip settings on nginx.conf like this: gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; gzip_min_length 256; Now I have nginx upstream like this: upstream example { keepalive 500; server 127.0.0.1:8001; } server { listen 0.0.0.0:80 server_name example.com } location / { proxy_pass http://ikhlas; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } In Django, I have a method that returns JSON with 16MB of size when I enabled gzip it returned to me same JSON with 16MB of size while having Content-Encoding: gzip response header. Why it is not compressing Django responses even if gzip is enabled and returns Content-Encoding header? -
Annotating Many2Many link works but only on SQLite (testing) not MariaDB (Production)
I am trying to annotate a model that includes a many2many link: class Link(models.Model): products = models.ManyToManyField(Product, related_name = "%(class)s_name", related_query_name = "product_link_qs", blank = True) position = models.ForeignKey(Position, on_delete = models.CASCADE) class Position(models.Model): place_id = models.PositiveIntegerField(unique = True) store = models.ForeignKey(Store, on_delete = models.CASCADE) class Store(models.Model): name = models.CharField("name", max_length = 32) in my admin I used annotate() to couple the information: @admin.register(Link) class LinkAdmin(admin.ModelAdmin): list_display = ["product", "get_store"] list_filter = ["position__store"] ### extend by product_link_qs related name property to make field sortable in the admin def get_queryset(self, request): qs = super().get_queryset(request) return qs.annotate(storename = Product.objects.filter(product_link_qs = OuterRef("id")).values("store__name")) @admin.display(description = "store name", ordering = "storename") def get_store(self, obj): if obj.asset: return obj.device.store or None return obj.storename or None only one product is linked to a position: this works perfectly fine in SQLite on testing and MariaDB in production adding a second relation to a link: works on SQLite in testing, but gives: django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row') -
Krakend Multiple Authorization Methods
I have an application that exposes a few endpoints which, for backward compatibility purposes, support both JWT and Basic Authorization methods. Recently we have decided to use KrakenD as the API Gateway for this application, now I have an issue with the authorization of the mentioned endpoints. I use auth/validator plugin for JWT validation and it works fine. But I'm looking for a way to bypass it when it fails and proxy the request directly to the application to use Basic Auth on the application side. I had an idea about writing a plugin for KrakenD to decide whether the Authorization header is a Basic or Bearer and then decide what to do with the request, or else to see if the JWT validation has failed and then proxy the request to the backend. I wasn't able to do any of those, so I'm looking for new ideas or an already existing solution for this. -
connect css and js to html in Django
I can't connect css and java script files to my html. I try diffrent ways to give it addres but It does'nt work. when I run my server my html file just show. here is a picture that shows how I address in diffrent ways. -
Django three-step registration
Please tell me, I'm doing a 3-step registration, using 3 forms that inherit from ModelForm and view classes that inherit from FormView. The first two pages were ok. On the first, I write down the first name, last name, mail and number in the session. On the second, I confirm the mail using the code. But there is a problem with the third page. There should be two fields: Enter password Enter the password again. And here in the form I don’t know how to make the password validation be from Django (well, that is, checking for length, characters, similarity between the first and second input field, etc.). Tell me, please, how to do this? From what class to inherit in the form? FormView class registration_step3(FormView): form_class = RegistrationForm3 template_name = 'html/log_&_reg/registration_add_password.html' success_url = reverse_lazy('authorization') def dispatch(self, request, *args, **kwargs): if 'registration_data' not in self.request.session: return redirect(reverse_lazy('registration_step1')) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): print("Форма прошла валидацию успешно.") registration_data = self.request.session.get('registration_data') print(registration_data) if registration_data: user = CustomUser.objects.create( first_name=registration_data['first_name'], last_name=registration_data['last_name'], email=registration_data['email'], phone_number=registration_data['phone_number'], notification_access=registration_data['notification_access'], email_verified=True, password=form.cleaned_data['password2'], ) del self.request.session['registration_data'] self.request.session.save() return super().form_valid(form) else: # Handle the case when registration_data is not found in the session return self.form_invalid(form) def form_invalid(self, form): print("Форма не … -
Django how to change CSS according the app you are in
I am pretty new with Django, I am customizing my admin section and I'd like to change the CSS according to the app I am browsing. Is it possible? I noticed that the uploaded CSS is the one in the first static folder found by the system. Is there some trick to do this? I tried to make a static folder in every app but the selected CSS is always the first. Thank you all. -
IndexError: list assignment index out of range (filling an array in a for loop with count() of objects)
I want to fill the array 'v' with the number of doctors in each department, I got this error : v[i]=Doctor.objects.all().filter(idDept__deptName__contains=s.deptName).count() ~^^^ IndexError: list assignment index out of range views.py def accueilAdmin(request): if not request.user.is_staff: return redirect('loginAdmin') depts=Department.objects.all() v=[] i=1 for s in depts: v[i]=Doctor.objects.all().filter(idDept__deptName__contains=s.deptName).count() i+=1 models.py class Department(models.Model): deptName = models.CharField(max_length=50, null=False) ... return self.deptName class Doctor(models.Model): name= models.CharField(max_length=50) ... idDept = models.ForeignKey(Department, on_delete=models.CASCADE, null=True) def __str__(self): return self.name I don't know how to solve it, I would appreciate your help, thank you.