Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django default connections.cursor() not parsing JSONB into DICT despite using PSYCOPG3
I am switching an old codebase from Django ~2 to Django 4.2.1. Along side this switch, I upgraded psycopg2 to psycopg (also known as psycopg3), but this switch has caused my cursor to incorrectly fetch rows from my PostgreSQL database. I am receiving STR instead of DICT when selecting JSONB objects in my database Important: When I use psycopg.connect directly, all of the behavior returns to what I expected. It is only when I am using the default django connection. from django.db import connection Here I fetch some json objects and check the type. with connection.cursor() as cursor: cursor.execute("select json_file from json_file") # These are of type jsonb for row in cursor.fetchall(): type(row[1]) This usually returns dict but is now returning str Here is my DATABASES variable in settings: 'default': {'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, 'CONN_MAX_AGE': None, 'CONN_HEALTH_CHECKS': False, 'ENGINE': 'django.db.backends.postgresql', } Here is Django's Connection + Cursor > connections['default'].connection <psycopg.Connection [IDLE] (host=db database=postgres) at 0x...> > connections['default'].connection.cursor() <django.db.backends.postgresql.base.Cursor [no result] [IDLE] (host=db database=postgres) at 0x...> Here is psycopg's Connection + Xursor > psycopg.connect("...") <psycopg.Connection [IDLE] (host=db database=postgres) at 0x...> > psycopg.connect("...").cursor() <psycopg.Cursor [no result] [IDLE] (host=db database=postgres) at 0x...> -
The problem with arabic language in xhtml2pdf django
Im useing xthml2pdf for generate invoice with arabic language. I searched a lot to solve the problem and followed all the steps, but I don't know why it doesn't work. Utils code: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), dest=result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') View code: pdf = render_to_pdf('pdf/invoice.html'), context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "invoice-%s.pdf" % invoice_number content = "inline; filename= %s" % filename response['Content-Disposition'] = content return response And finally the HTML code: <!DOCTYPE html> <html lang="ar" dir="rtl"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta charset="UTF-8"> <style> @font-face{font-family:samim; src: url('/assets/fonts/Shabnam-FD.ttf') } body{ background: #fff; font-family: samim !important; direction: rtl !important; } </style> </head> <body> <div> <pdf:language name="arabic"/> <p>سلام</p> </div> </body> </html> But what is generate in the end -
The problem of not generic refresh and access token for users
I have a problem with the code written with Python and Django framework I wrote a custom model and used Abstrcatuser in it, and instead of the username field, I used the phone number field. Now, when I enter the login address in the api I wrote and want to get the access token and refresh token, it creates only these things for the superuser and tells the other users that the phone number or password is wrong if they are also correct. I also use jwt. I tried to make some changes in the code, but I didn't find anything important -
clickable label for radio in django
i want to have clickable labels for my radio buttons in django but i cant click and the values are not registered in the database , its like just text <div class="probprior"> <div class="radio-container"> <label for="id_is_observer"> {{register_user_form.is_observer}} Observer </label> <label for="id_is_technician"> {{register_user_form.is_technician}} Technician </label> <label for="id_is_self_service"> {{register_user_form.is_self_service}} Self Service </label> <label for="id_is_staff"> {{register_user_form.is_staff}} Staff </label> </div> </div> and im using this style too in css file .radio-container input[type="radio"] {display: none;} .radio-container input[type="radio"]:checked + label {background: #F7B1AB;border: 1px solid rgba(0,0,0,.1);} -
Show two distinct column count in annotate Django
I'm getting trouble with annotate in Django. I have two models in projects. (just structure) model A (field:name(char)) model B (field:A(A; related_name="b"), user(user), content(char; null=True)) The data of model B is just like... row1 -> A:1, user:2, content:"content1" row2 -> A:1, user:3, content:"content2" row3 -> A:1, user:2, content:None row4 -> A:2, user:1, content:None row5 -> A:1, user:3, content:None My intention is a unique value that combines user and content according to the pk of model A being searched. If I look up pk:1 of Model A and the answer I want is 2, and the reason is as follows. row1 -> A:1, user:2 row2 -> A:1, user:3 So the orginal code was... A.objects.annotate(count=Count(Concat("b__user", "b__a), distinct=True)).get(pk=pk) However, a value error occurs when looking up model A that is not referenced in model B. (count:1) What can should do? -
Django model foreignkey null=false, but null value on select list on form
I've got the following model field: category = models.ForeignKey("QuestionCategory", on_delete=models.CASCADE, null=False, blank=False ) Is it proper behaviour of django, that rendering it in html form, on the select list there are all options (all categories) as well as "empty option", represented by "-----------" ? (as on the image here): enter image description here Still, if selecting that empty option and trying to save, there is validation error, that I need to select one of the element from the list... -
Two foreign keys in one model
I am making my first Django app and I am having trouble exporting some values. I have a model let's call it Machines with some attributes (buyer, name, model, serial number etc). My other model is a visit category model that has 2 reasons for the visit (service, inspection) Finally I have my last model that has visitDetails (date of visit, notes, reason of visit (which is visit category model foreign key, and machine details (which is Machines model foreign key). How can I get for each visitDetails the reason of visit? I managed to get all machineDetails for each Machine with: machine = Machines.objects.get(id=id) visit_details = machine.details.all() - details is relate_name for machine_details which is an object inside visitDetails model with foreign key Machines. But I cannot figure out how to also get visit category for each visit. -
Django And Netbox Error: Invalid permission name: . Must be in the format <app_label>.<action>_<model>
I recently updated from 3.4.5 to 3.7.4. Everything worked great with my customizations except for logins. I have Nginx running as a remotebackend, which creates the users. So the users are able to login when I make them a superuser, but when I try to assign permissions other than superuser, I get the error of "Invalid permission name: . Must be in the format <app_label>._." Not really sure what's going on as if I use a superuser, everything works great, and that data can be uploaded just fine. Looking for some help as to what the issue could be, as it could be with my plugins, but I dont think it is. -
Django Hot Reload
I am running docker image of a Django application with an entrypoint like this: export PYTHONUNBUFFERED=1 python3 manage.py runserver 0.0.0.0:8080 In settings.py DEBUG=True. However StatReloader doesn't seem to boot up (no logs regarding it's existence) to watch for module/.py file changes. Also there is mount configured so that the docker is aware of host changes and I have double checked it using docker exec. -
Permission denied error while deleting the image from directory media/mobile_images
view.py: if 'del_img2' in request.POST: product.image2.delete() img_path = os.path.join(settings.MEDIA_ROOT, str(product.image2)) print(img_path) os.remove(img_path) product.image2.delete() models.py class Mobiles(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=50, blank=False, unique=True) actual_price=models.DecimalField(max_digits=10, decimal_places=2,blank=False) discount_price=models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)], default=0) selling_price=models.DecimalField(max_digits=10, decimal_places=2,default=0) review=models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(10)]) features=models.CharField(blank=False, max_length=5000) days=models.IntegerField(default=0) image1=models.ImageField(null=False, blank=False, upload_to='mobile_images/') image2=models.ImageField(null=True, upload_to='mobile_images/' , blank=True) While clicking on submit button Image is deleting from db and media/mobile_images but throwing an error : PermissionError at /admedit1/1 [WinError 5] Access is denied: 'D:\MyProjects\DjangoProjects\Elec&Gad\ElecAndGad\media\' Request Method: POST Request URL: http://127.0.0.1:8000/admedit1/1 Django Version: 4.2.5 Exception Type: PermissionError Exception Value: [WinError 5] Access is denied: 'D:\MyProjects\DjangoProjects\Elec&Gad\ElecAndGad\media\' Local vars D:\MyProjects\DjangoProjects\Elec&Gad\ElecAndGad\adminapp\views.py, line 105, in admedit1 os.remove(img_path) -
It is possible to set a title tab in django without to pass throught html?
Is it possible to set a page title in Django without going through the HTML file directly? I have data stored in my object, and I want to extract the name to set it as the title in my template. Essentially, I generate my views and URLs dynamically from the backend using HTTP requests. I'd like to know if there's a way to set the title dynamically without having to possess a .html file, as I generate my templates dynamically and don't have static .html files I except to set a title tab without passing through a .html file just from the .py files -
DJango rest-framework pagination without settings in REST_FRAMEWORK
I am following pagination help. It has para as You can also set the pagination class on an individual view by using the pagination_class attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis. I set pagination_class in my ViewSet, but until I set REST_FRAMEWORK setting, it wont effect. REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } When I set, it will set pagination for all view set, I have 10 views, but I want set pagination only on one view. Can I set pagination without setting in REST_FRAMEWORK parameter? -
how to access a django project when we are in the same network?
As you know, you can check django application by running this command: python3 manage.py runserver Let's say, there are 2 laptop which are sharing same internet network. When i run server for django app, i can access it on my browser from this address: http://127.0.0.1:8000/ But i would like to know if it is possible to access from another computer? I tried the same address but I could not access. My development stack is; Django version => 4.2.4 Python version => 3.11 How can i solve this issue? I tried to access from another laptop which sharing same network. i could not access. -
Heroku deploy with docker and poetry
I'm trying to deploy a django application on heroku. I use docker and poetry. I have a problem because in the dockerfile I install poetry and install dependencies using poetry. Locally it works fine, but when I want to deploy on heroku, the dependencies are not installed. Only putting code like: 'RUN pip install -r requirements.txt' installs the dependencies on heroku (I created the requirements.txt file using poetry export). Should I have two different Dockerfiles for dev and prod, where I will use poetry in one and pip install requirements in the other ? Or should I use multistaged Dockerfile or do you have any other suggestions ? My Dockerfile with potery: FROM python:3.11-alpine WORKDIR /code ENV PYTHONUNBUFFERED 1 ENV PATH "/root/.local/bin:$PATH" RUN apk add --no-cache curl \ && curl -sSL https://install.python-poetry.org | python3 - \ && apk add --no-cache postgresql-dev musl-dev COPY poetry.lock pyproject.toml /code/ RUN poetry install --no-root COPY . /code/ RUN poetry install heroku.yml: build: docker: web: backend/Dockerfile run: web: gunicorn core.wsgi:application --bind 0.0.0.0:$PORT -
How do I get out the doubles of the dropdown menu?
I have a dropdown in the index.html which shows duplicate values. These are displayed if I have e.g. 2 articles with the same ‘developer_id’ in index.html. I want that if several articles with the same value for the dropdown menu are get from the database, it is only displayed once in the dropdown menu. Can anyone help me with this? Thank you very much. view.py def index(request): return render(request, "auctions/index.html", { "auctions": Listing.objects.all() }) def sort_categories(request): if request.method == "POST": get_category = request.POST["developer_id"] dev = Games.objects.get(developer=get_category) sortobjects = Games.objects.values(developer_id=dev).distinct() #sortobjects = Games.objects.values("developer_id").distinct() #if dev == "": # messages.error(request, "Developer not in List") # return HttpResponseRedirect(reverse("article", args=(id, ))) get_article = Listing.objects.filter(developer_id=dev) all_dev = Listing.objects.all() #else: return render(request, "auctions/index.html", { "get_article": get_article, "all_dev": all_dev, "data": sortobjects }) models.py class Comment(models.Model): user_comment = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user_comment") listing = models.ForeignKey(Listing, on_delete=models.CASCADE, blank=True, null=True, related_name="listing_comment") comments = models.CharField(max_length=500) def __str__(self): return f"{self.user_comment} {self.listing} {self.comments}" index.html <form action="{% url 'sort_categories' %}" method="post"> {% csrf_token %} <label for="dev"></label> <!--<input type="text" name="dev" id="developer_id" placeholder="Developer">--> <select name="developer_id" id="developer_id"><br> {% for i in auctions %} <option value="{{ i.developer_id }}">{{ i.developer_id }}</option> {% endfor %} . . . -
slicing any filed of Django form
Is it possible to slice two field for adding hr HTML tag after fields? forms.py class FactureForm(forms.Form): Facture_No = forms.CharField(label='Facture Number', required=False) Beställare = forms.CharField(required=False) Actually I want to add hr tag between Facture_No and Beställare -
Use original image size and aspect ratio in the carousel component in Django CMS
I am using the carousel component for Django CMS from the front-end plugins. I have a problem with the image size and aspect ratio. I tried an approach to manage the CSS file according to this source: Maintain image aspect ratio in carousel However, this is not solving my problem. The image is still being cropped and downsampled, resulting in low resolution. I want to display the images in full view and in their original aspect ratio. However, the carousel component from the plugin only allows the use of fixed aspect ratios, which do not correspond to my image aspect ratio. I didn’t find the possibility to use or select the image’s original aspect ratio. Moreover, it seems that the carousel component loads a downsampled and cropped version of the image. If I understood correctly, the image loading response is from the thumbnail component: djangocms_frontend/contrib/carousel/templates/djangocms_frontend/bootstrap5/carousel/default/image.html {% load cms_tags easy_thumbnails_tags %} {% if instance.rel_image %} {% thumbnail instance.rel_image options.size crop=options.crop upscale=options.upscale subject_location=instance.rel_image.subject_location as thumbnail %} <img class="d-block w-100" src="{{ thumbnail.url }}" alt="{{ instance.rel_image.default_alt_text|default:'' }}" /> {% else %} <div class="d-block w-100" style="aspect-ratio: {{ aspect_ratio }}"> {% for plugin in instance.child_plugin_instances %} {% render_plugin plugin %} {% endfor %} </div> {% endif … -
Django and Celery old data persistency issue
I am having an issue with my django application using celery workers. I have a task that takes 2 input variables then passes them to an external function to perform a webscraping operation on them. The issue is that even though in the logs model I created it registers the correct new user_id and swimmer_id each time the task is executed it seems to get the swims information from the very first time the task was executed as opposed to the current execution. When the worker is restarted the issue resolves until you try to perform a second execution again. In my code below I can show you the setup I am using, @shared_task(bind=True) def process_swimcloud_merge(self, id, user): print(id) user = User.objects.get(id=user) print(user.first_name) swims = extract_recent_swims(user.id, id) #More swim processing code here, irrelevant to query return def extract_recent_swims(user_id, swimmer_id): meet = find_all_meets(swimmer_id)[0] a_tag = meet.find('a', class_='c-swimmer-meets__link-mask') link = a_tag.get('href') swims = extract_swims(link) swim = swims[-1] UserActionLogs.objects.create( user = User.objects.get(id=user_id), accessing = f'UID: {user_id}, SID {swimmer_id}, Swim: {swim.title}, {swim.time}') return The problem here is that in the UserActionLogs, it correctly logs whatever the user_id and swimmer_id are on each execution however it logs whatever the original swim was from the first … -
Static files not served while deploying Django application with Lighttpd and Gunicorn
I am working on my first Django project. I want to host the same using Lighttpd server rather than nginx or apache. The project works well in the developer mode. The 'runserver' serves all the files as intended. Since Lighttpd alone cannot host a Django project, I use Gunicorn to serve the dynamic aspects. Django version - 3.2 Gunicorn - 21.2 Python - 3.8 Lighttpd - 1.4.52 I have configured my Lighttpd in a separate conf file named myapp.conf without amending the default lighttpd.conf file. When I run the server, I see that Gunicorn loads index.html correctly but css files are not loaded by lighttpd. It gives the following error: GET https://ip-address/myapp/static/css/indexStyle.css net::ERR_ABORTED 404 (Not Found) Similarly Gunicorn gives an error when loading js file: GET https://ip-address/myapp/static/js/TM_PageFun.js net::ERR_ABORTED 404 (Not Found) Refused to execute script from 'https://ip-address/myapp/static/js/TM_PageFun.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I find a lot of information here on connecting Django with Nginx and Gunicorn. But I couldn't find much with Lighttpd. I am not sure where the error is. I have added the mime-types and double checked the path and permissions. CSS files are in /usr/web/myapp/static/css JS files … -
Django ForeignKey("x") field must be a "x" instance on update
Django version 4.2.9 I try to fix this : Cannot assign "('customer',)": "Project.customer" must be a "Customer" instance. I have 2 classes, Project and Customer. class Customer(models.Model): customer_name = models.CharField(max_length=50) string = models.CharField(max_length=50) def __str__(self): return f"{self.customer_name}" class Project(models.Model): project_name = models.TextField() project_code = models.CharField(max_length=50,null=True,blank=True) project_scope = models.CharField(max_length=200,blank=True,null=True) customer = models.ForeignKey("Customer", on_delete=models.DO_NOTHING) project_type = models.ForeignKey("ProjectType", on_delete=models.DO_NOTHING) is_rd = models.BooleanField(null=True,blank=True) #TARIHLER request_date = models.DateField(auto_now=False, auto_now_add=False) confirmation_date = models.DateField(auto_now=False, auto_now_add=False, null=True,blank=True) estimated_finish_date = models.DateField(auto_now=False, auto_now_add=False) project_finish_date = models.DateField(auto_now=False, auto_now_add=False, null=True,blank=True,default="01/01/1970") update_date = models.DateField(auto_now=False, auto_now_add=False,null=True, blank=True,default="01/01/1970") start_date = models.DateField(auto_now=False, auto_now_add=False,null=True, blank=True,default="01/01/1970") #TARIHLER update_count = models.IntegerField(null=True,blank=True) estimated_cost = models.IntegerField() actual_cost = models.IntegerField(null=True,blank=True) is_active = models.BooleanField(default=False) project_leader_id = models.ForeignKey("account.MamurUser", on_delete=models.DO_NOTHING) bill = models.BooleanField() patent = models.BooleanField(default=False,blank=True) market = models.BooleanField(default=False,blank=True) is_confirmed = models.BooleanField(default=False,blank=True) is_pmo_confirmed = models.BooleanField(default=False,blank=True) This is my views.py: def edit_project(request): context={ "projects" : Project.objects.filter(is_confirmed=False) } if request.method == "GET": return render(request,'pyka/project-edit.html',context) else: post = request.POST project_id = post['project_id'] project = Project.objects.get(id=project_id) update_count = project.update_count update_count += 1 valid = True # değişecek error = None now = datetime.date.today() project_name = post['project-name'] customer = Customer.objects.get(id=post['customer']) type = ProjectType.objects.get(id=post['type']) project_scope = post['project-scope'] project_budget = post['project-budget'] user_data = post['userData'] user_data = json.loads(user_data) start_date = post['start-date'] end_date = post['end-date'] patent = post.get('patent', False) market = post.get('market', False) # … -
Bt table filter extension:- how to filter dropdown value filter out?
How to filter dropdown value based on new data on first filter. Like only $0 needned in second dropdown value Simple table value filter then based on filtered result value dropdown value come to UI. Thanks I see the github code for bt table filter extension but i didn't identify any idea -
Mypy: properly typing a Django mixin class when accessing a method on super()
Django has a quirk where it doesn't validate models by default before writing to the database. A non-ideal situation that devs try to work around by creating a Mixin class for example: https://www.xormedia.com/django-model-validation-on-save/ The idea of that workaround is that you can inherit this mixin to your custom defined Django models whenever you want to add validation-on-save to it. That approach works, but I'm trying to upgrade those old examples to a properly typed example. Below is my current code: from typing import Any, TypeVar from django.db import models DjangoModel = TypeVar('DjangoModel', bound=models.Model) class ValidateModelMixin: """Use this mixing to make model.save() call model.full_clean() Django's model.save() doesn't call full_clean() by default. More info: * "Why doesn't django's model.save() call full clean?" http://stackoverflow.com/questions/4441539/ * "Model docs imply that ModelForm will call Model.full_clean(), but it won't." https://code.djangoproject.com/ticket/13100 """ def save( self: DjangoModel, force_insert:bool=False, force_update:bool=False, *args: bool | str | None, **kwargs: bool | str | None, ) -> None: """Override the save method to call full_clean before saving the model. Takes into account the force_insert and force_update flags, as they are passed to the save method when trying to skip the validation. Also passes on any positional and keyword arguments that were passed … -
prefill previous file field data in django form
i have two file fields in django form and i want set prefill data for fields. when form open again dont need fill again file field. this is my form field self.fields['total_trial_balance'].widget.attrs.update({'class': 'filestyle', 'id': 'total_trial_balance'}) self.fields['Certain_trial_balance'].widget.attrs.update({'class': 'filestyle', 'id': 'Certain_trial_balance'}) this is i try to do form = TaxReturnLegalUpdateForm(instance=tax_return, request=request) but i just got currently file name in my templateenter image description here -
Why Hosted Site showing blank page in azure-django hosting?
I am trying to deploy my django app using azure(app services) through vs code. It is Showing deployment successful but hosted site showing blank page. I used VS Code. Downloaded azure studio extension and deployed my django project. -
Is this the right way of creating Multi User Access for Django?
I actually confused right now on how to implement the Multi-User Access with Django v5.3. I am actually new in this backend and I would like to create a login where users can redirect to specific dashboards based on their accesslevel type (Providers,Admin,Validator,Students). Here is the app that I made so far... I have no views yet because I am not confident enough to my models.py but I hope this is good enough. from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_student = models.BooleanField(default=False) is_validator = models.BooleanField(default=False) is_provider = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.FileField address = models.CharField(max_length=50) gwa = models.FloatField(max_length=100) graduated_at = models.CharField(max_length=100) year = models.DateField() class Validators(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.FileField address = models.CharField(max_length=50) class Provider(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_address = models.CharField(max_length=100) phone_no = models.CharField(max_length=11) company_website = models.CharField(max_length=100) avatar = models.FileField class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.FileField(upload_to='avatars')