Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Whats wrong in dockerfile?
I am trying to run docker compose build then use the comand docker compose up and get next error: Attaching to django-postgresql-gunicorn-nginx-dockerized-master-db-1, django-postgresql-gunicorn-nginx-dockerized-master-web-1 Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "/usr/src/app/entrypoint.sh": permission denied: unknown Help me guys please to solve this error # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . # copy project COPY . . RUN chmod +x /usr/src/app/entrypoint.sh # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] -
Add field don't exist in model in fields at serializer
how can i add field in serializer... This field is not in model no more details thank you ça me renvoie une erreur "Got AttributeError when attempting to get a value for field etat_civil on serializer Serializer_Professeur_Assistant. The serializer field might be named incorrectly and not match any attribute or key on the DescPersonne_Prod instance. Original exception text was: 'DescPersonne_Prod' object has no attribute 'etat_civil'." -
Python telethon login telegram from my website
Hi friends I write template in Django.User enter phone number and my telethon code sending code after user enter code new input. I want to that user login in own telegram account. But this code not working. 1 STEP: phone_number = 'user number' client = TelegramClient('session_name', api_id, api_hash) phone_code_hash = client.send_code_request(phone_number).phone_code_hash client.connect() f not client.is_user_authorized(): client.send_code_request(phone_number) 2 STEP user = client.sign_in(phone_number,'89065') give error ConnectionError: Cannot send requests while disconnected User login with telethon in Django. But I cant -
Neo4J Django neomodel not showing nodes in the explorer
I'm new to Graph database and using Neo4j database with neomodel library in Django application. The settings are defined as NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL') NEOMODEL_SIGNALS = True NEOMODEL_FORCE_TIMEZONE = False NEOMODEL_ENCRYPTED_CONNECTION = True NEOMODEL_MAX_POOL_SIZE = 50 and the models.py file has the following model class Person(StructuredNode): SEXES = { 'm': 'Male', 'f': 'Female', } id = properties.UniqueIdProperty() first_name = properties.StringProperty(unique_index=True, required=True, max_length=100) gender = properties.StringProperty(choices=SEXES, required=True) In Django shell python manage.py shell, creating a node as >>> from family_tree.models import Person >>> person = Person(first_name='Anuj', gender='m') >>> person.save() <Person: {'id': '572d0b8ff3a8402ba58c4a03cace78ba', 'first_name': 'Anuj', 'middle_name': None, 'last_name': None, 'gender': 'm', 'date_of_birth': None, 'date_of_death': None, 'created': datetime.datetime(2023, 6, 24, 7, 44, 26, 223871, tzinfo=<UTC>)}> When the database explorer has no nodes in it. Also refreshing node gives DoesNotExist exception >>> person.refresh() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.9/site-packages/neomodel/core.py", line 616, in refresh raise self.__class__.DoesNotExist("Can't refresh non existent node") neomodel.core.PersonDoesNotExist: (PersonDoesNotExist(...), "Can't refresh non existent node") -
I can not run server
after python manage.py runserver using Pycharm that $ python manage.py runserver Python I reciver this message Exception ignored in thread started by: <function check_errors..wrapper at Traceback (most recent call last):Exception ignored in thread started by: <function check_errors..wrapper at Traceback (most recent call last): and in many files this proble, python manage.py runserver 8080 python manage.py runserver even on visual studio same error -
Django order by parent object with many to many relation with child object
I have two models class Course(models.Model): name = models.CharField(blank=True, null=True) class Account(models.Model): courses = models.ManyToManyField(Course, related_name=account_courses) I want to order by Course model by count of accounts I have tried by creating a property method @property def course_accounts(self): return self.account_courses.count() I am able to count the objects using this method but not able to order by objects using courses = Course.objects.all().order_by('course*accounts') It throws field error with: "Cannot resolve keyword 'course*account' into field" -
Post method in DetailView?
I wanna to use form in detail page,Then views access get and post ... from django.views.generic import DetailView from .forms import CommentForm Class ArticleDetailView(DetailView): model = Article def get_context_data(self,*args,**kwargs): context = super().get_context_data(*args,**kwargs) context['form'] = CommentForm return context def post(self): #do something here with request.POST But in django docs write this logic with mixins(FormMixin).. -
Opentelemetry auto-instrumentation error in python Django application in K8s
I'm running a simple Django 4 CRUD application in kubernetes. I'm trying to collect metrics and traces. I deployed the otel collector and auto-instrumentation and annotated using my django app. oc patch deployment.apps/django-crud -p '{"spec": {"template": {"metadata": {"annotations": {"instrumentation.opentelemetry.io/inject-python": "true"}}}}}' After annotated the below error occurs Create migrations No changes detected Exception while exporting metrics ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer')) Traceback (most recent call last): File "/otel-auto-instrumentation/urllib3/connectionpool.py", line 790, in urlopen response = self._make_request( File "/otel-auto-instrumentation/urllib3/connectionpool.py", line 536, in _make_request response = conn.getresponse() File "/otel-auto-instrumentation/urllib3/connection.py", line 454, in getresponse httplib_response = super().getresponse() File "/usr/local/lib/python3.10/http/client.py", line 1375, in getresponse response.begin() File "/usr/local/lib/python3.10/http/client.py", line 318, in begin version, status, reason = self._read_status() File "/usr/local/lib/python3.10/http/client.py", line 279, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "/usr/local/lib/python3.10/socket.py", line 705, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/otel-auto-instrumentation/requests/adapters.py", line 486, in send resp = conn.urlopen( File "/otel-auto-instrumentation/urllib3/connectionpool.py", line 844, in urlopen retries = retries.increment( File "/otel-auto-instrumentation/urllib3/util/retry.py", line 470, in increment raise reraise(type(error), error, _stacktrace) File "/otel-auto-instrumentation/urllib3/util/util.py", line 38, in reraise raise value.with_traceback(tb) File "/otel-auto-instrumentation/urllib3/connectionpool.py", line 790, in urlopen response = self._make_request( File "/otel-auto-instrumentation/urllib3/connectionpool.py", … -
Django - Code between Declaration and Render not executing
Got a funny issue that i've run into and I wondered if anyone can share some advice. I'm creating a simple web page with a form but the form content is not loading and after doing some digging i've discovered that any code between the function delaration request and the render is not being executed. @login_required(login_url='') def index(request): print('Hello World!') project = projectForm() return render(request, 'index.html', {'form': project}) so in the above example Hello World! and creation of the project form do not execute, but the page loads, albeit without any form content. Anyone come across this, can shed some light on what the problem may be? -
I need to change the colour of some cells in Full calendar, not the event, but the whole cell
I want to change the colour of the whole cells in Full Calendar, not the event but the whole cells, like the background of the current day. I don't know how to start `document.addEventListener('DOMContentLoaded', function () { var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { contentHeight: 'auto', timeZone: 'local', eventOrder: 'variable', stickyHeaderDates:true, events: [ {% for es in eventos %} { variable: {{ es.esTemprano }}, title: ' {{ es.icono }} {{ es.apellido }} {{ es.personas }}', start: '{{ es.dia |date:"Y-m-d"}}', end: '{{ es.dia |date:"Y-m-d"}}', url: '../evento/aviso/{{es.id}}', color: 'black', textColor:{% if es.llegar < '14:00' and es.llegar > '06:00' %} '#0F8706' {% else %} 'black' {% endif %}, backgroundColor: '#FCF7F3', }, {% endfor %} ], }); calendar.render(); calendar.setOption('locale', 'es'); }) ; ` -
MariaDB table got non-consecutive primary key after running a Django application
We have been running a Django application for years, and the operation accumulated multiple thousands of historical transactions. We recently sampled through the real data and realized that the transaction table contains non-consecutive values in its primary key id column. The jumping primary keys widely exist in the data, and typically, a sample query for id with an interval of 1000 will only yield three hundred records. By reviewing the application's source code, we have the following details, not sure if relevant, though. The DDL has AUTO_INCREMENT on the id column, so we believe the database will automatically increment on this column. In the Python source code, the model Transaction does not contain the primary key id column, so this column is added by the Django framework. In the function writing the transaction to database, there is no mention of the primary key id column either. However, the function has @transaction.atomic, and we are not sure whether the notation has any influence on the system behavior. The technical stack is: MariaDB v10.5, Python v3.7, Django v3.1.4. Our Question: Why does the database have non-consecutive primary keys on the table? Is it common for applications to have non-consecutive primary keys in … -
NoReverseMatch error when creating delete button
I was trying to create a button that deletes game in my website, however django displays NoReverseMatch error views.py def delete_game(request, pk): game = Game.objects.get(pk=pk) if request.method == 'POST': game.delete() return redirect('shop_page') context = { 'game': game } return render(request, 'store/product-details.html', context) urls.py path('delete/<int:pk>', delete_game, name='delete_game') product-details.html <form action="{% url 'delete_game' game.pk %}" enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="submit" value="Удалить игру"> </form> Please help me with that. -
Rename a file on upload Django
Good afternoon, I need to rename the files that users upload through a form with the nomenclature (DSR_"rut"-"name"-"label name (from form)"-0-"extension"). The parts of the rut, the name and the extension I could already generate, but I don't know how to do the name of the label. example: if the label says "image": (DSR_"rut"-"name"-image-0-"extension"). Please your help. To do this use the following: def upload_directory_name(instance, filename): ext = filename.split('.')[-1] filename = "DSR_%s_%s_0.%s" % (instance.rut, instance.name, ext) return os.path.join('uploads',filename) The file forms is as follows: class Candidato_form2(forms.ModelForm): class Meta: model = Candidato fields = [ 'certificado_antecedentes', 'hoja_de_vida_conductor', ] labels = { 'certificado_antecedentes': 'Certificado Antecedentes', 'hoja_de_vida_conductor': 'Hoja de vida del conductor', } widgets = { 'certificado_antecedentes': forms.ClearableFileInput(attrs={"multiple":True, 'class':'form-control'}), 'hoja_de_vida_conductor': forms.ClearableFileInput(attrs={"multiple":True, 'class':'form-control'}), } -
django csrf gives forbidden 403 error for POST
I'm trying to learning Django and as part of a tutorial, i was trying to pass some data through forms. It was good with GET, but POST gives me a forbidden 403. I googled and applied many of those tricks but nothing helped. Here is my code: view @csrf_protect def counter(request): template = loader.get_template("counter.html") ss = request.POST["cnt"] context = { "words" : len(ss.split(" ")) } return HttpResponse(template.render(context, request)) form <form method="post" action="counter"> {% csrf_token %} <textarea name="cnt" rows="10" cols="50"></textarea><br> <input type="submit"> </form> The 403 error at first was: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing. But after removing cookies (I read that it might be an issue with the cookie), it changed to: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.