Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if file has extension pdf
I have a method of uploading files. But now I want to check if the uploaded file is a pdf file. So I try it like this: def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) file_extension = os.path.splitext(uploadfile[1]) if file_extension in {'pdf'}: print('Is pdf') uploadfile.save() with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r') as f: content = f.read() print(content) return render(request, "main/create_profile.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/create_profile.html", { "form": submitted_form, }) But then I get this error: TypeError at / 'UploadFile' object is not subscriptable Question: what I have to change? Thank you -
Unable to store object in Django cache because the model uses a dynamic attribute
I am using the django-stdimage package to auto-resize my images. However, it seems that this particular plugin creates problems when I want to cache certain results. Models: class Page(models.Model): name = models.CharField(max_length=255) image = StdImageField(upload_to="images", variations={"thumbnail": (800, 600), delete_orphans=True) View: page = Page.objects.get(pk=1) cache.set("page", page, None) Result: AttributeError: 'StdImageFieldFile' object has no attribute 'thumbnail' From here: that is because the attribute is being set dynamically and is not properly serialised. So my question is: is there a way to record this object in the cache, even though this specific attribute is being set dynamically? Note that I don't need that specific field to be cached - if there is a way to cache the entire object WITHOUT the image field, I am happy with that too. -
How to make Django create an id but in different sequence
what I mean here is to make my id like that id : 2022001,2022002 not 1,2,3 or something like this random id hdvdfhbf124 and my second question is how to use auto-generated id the default one in my view.py if I didn't defined in models class FAQ(models.Model): questionTitle = models.CharField(max_length=50) questionAnswer = models.TextField(max_length= 300) class Meta: verbose_name_plural = "FAQ" because I can't refere to it in viwes.py like faq.id or something like that even if I import models not working -
I tried installing pip3 using the command prompt in windows but I got these error messages
Hi everyone I am new to Python programming, I tried installing pip3 on my windows computer, I typed (pip3 install pipenv) on the command prompt but I got these error messages (Error message 1: ”could not find a version that satisfies the requirement pipenv (from versions: none”) (Error message 2: no matching distribution found for pipenv) Thank you. -
How I upload image with schema to my dio flutter app
I had this endpoint in my django api django endpoint I need to upload a image with the post details to create one in my app ,i spend days without any sol please help me if you can :( -
Dropdown dynamic in django ajax
I am using django for dynamic dropdown. There are two dropdown when the first dropdown was click and there is a subcategory for it, the second dropdown will show options. I want to disable the second dropdown if there is no subcategory for it. How can I do that? $("#id_general-collision_type").change(function () { const url = $("#form_incidentgeneral").attr("data-acc-url"); // get the url of the `load_cities` view const collisionId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= /persons/ajax/load-cities/ ) data: { 'collision_type_id': collisionId // add the country id to the GET parameters }, success: function (data) { //console.log(data) // `data` is the return of the `load_cities` view function $("#id_general-collision_subcategory").html(data); // replace the contents of the city input with the data that came from the server let html_data = '<option value="">---------</option>'; data.forEach(function (collision_subcategory) { html_data += `<option value="${collision_subcategory.id}">${collision_subcategory.sub_category}</option>` }); console.log(html_data); $("#id_general-collision_subcategory").html(html_data); } }); }); -
My Django App only works on heroku when server is running locally
I have built an app using react and django. After deploying the app on heroku, when I open it the frontend works fine. However when i try to do any action that sends requests to the backend I get errors. The only time the requests work fine is when the django backend is running locally. I hsve been looking allover for solutions and have not been able to find any solutions. In my settings.py The heroku domain name is added to the allowed hosts ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'barkbnb-demo.herokuapp.com'] If anyone can point me in the right direction on where to begin looking for solving the issue that would be greatly appreciated. Thanks! -
Add n number of fields in django model
I want to add unlimited fields in the Django model. Actually, I want my model to look like this, Is it Possible ? -
Pytho Django Html - Need a function to make a filter of the choices of a models.py
Cree una App Blog python django. El usuario, al crear un nuevo articulo, puede seleccionar el tipo de categoria del articulo y se guarda en una base de datos. Necesito crear varias funciones (o una sola) en el view.py que filtre por categoria que viene del models.py. Para poder mostrarlas por html (front) y mostrar asi solamente los articulos (por ej: "Accion") Esto es lo que he intentado hasta el momento: view.py def sports(request): category = Post.objects.all() if category == sports: print(list(Post.category)) return render(request, "sports.html", {"category":category}) Models.py from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField STATUS_CHOICES = [ ('Action', 'Action'),('Adventure', 'Adventure'), ('Science Fiction', 'Science Fiction'), ('Sports', 'Sports'), ('Thriller', 'Thriller'), ('Shounen', 'Shounen'),('Fantasy', 'Fantasy') ] class Post(models.Model): anime_name = models.CharField(max_length=80, verbose_name='Título') sub_name = models.CharField(max_length=100, verbose_name='Subtitulo') content = RichTextField(max_length=5000, verbose_name='Contenido') created_at = models.DateTimeField(auto_now_add=True) published_at = models.DateField(null=True, blank=True, verbose_name='Fecha de publicación') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Autor') photo = models.ImageField(upload_to='/media/images/',default='/images/no_image.jpg', null=True, verbose_name='Foto') category = models.CharField(max_length=20, choices=STATUS_CHOICES) def __str__(self): return f'Autor: {self.user.username} -- Titulo: {self.anime_name} -- Contenido: {self.content[:(42 - (len(self.anime_name) - 4))]} -- Fecha de publicacion: {self.published_at}' class Meta: db_table = 'posts' verbose_name = 'post' verbose_name_plural = 'posts' ordering = ['-published_at'] forms.py from django import forms from .models import Post, Comment class … -
hot to set tinymce.init in django-tinymce package
I can't use CDN of tinymce in my project. So I wanna use django-tinymce package. But don't know how to set tinymce.init to set my personal configuration. -
HTTP to HTTPS on NGINX Django server
I'm setting up a server on AWS from a Django project and my Nginx gives an error when trying to switch from HTTP to HTTPS. See my file: host = fantasy name server { listen 80; server_name host; return 301 https://host$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ {alias /home/ubuntu/Filmes/staticfiles/;} location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Indeed when using the old domain over HTTP I am redirected to HTTPS but I get CONNECTION DENIED TO THIS DNS. -
Any idea why contexts are not showing in template?
So, I have this two function in my views.py class TheirDetailView(DetailView): model = List def listcomments(request): modell = Review.objects.all() return render(request, 'app/list_comment.html', {'model' : modell}) And have these two paths set in my apps urls path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'), path('comment/',views.listcomments, name='ListComments'), So I have two templates list_detail.html & list_comment.html Here in list_detail.html I have included list_comment.html (just the comment section is there in list_comment.html) In my list_detail.html .. ... .... <div class="commentss" id="comments-id"> <div class = "commentscarrier"> <div class="comment-contentsas comment-head"><p>Comments(3)</p></div> <hr> {% include "app/list_comment.html" %} ... .. In my list_comment.html {% load static %} {% for i in model %} <div class="comment-contentsas"><p class="commentor-name">{{i.user.username}} </p></div> <div class="comment-contentsas"><p>{{i.comment}}</p></div> </div> {% endfor %} In my models.py class Review(models.Model): user = models.ForeignKey(User, models.CASCADE) List = models.ForeignKey(List, models.CASCADE) comment = models.TextField(max_length=250) rate = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.comment) class List(models.Model): title = models.CharField(max_length=65) genre = models.ManyToManyField('Genre') creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) posted = models.DateTimeField(auto_now_add=True) content = RichTextField(null=True,default=' ') type = models.CharField(max_length=10,default="Movie") slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) I have created 5 objects of Review model manually in admin. So that should show in my template. But its not showing anything. I am guessing I must have been messed up in my urls. But … -
CookieCutter Django websocket disconnecting (using Docker)
I am trying to build a chat application. I am using Cookiecutter django as the project initiator. And using a docker environment, and celery as i need to use redis for websocket intercommunication. But websocket is constantly disconnecting even if i am accepting the connection is consumers using self.accept(). i have also included the CHANNEL_LAYERS in the config/settings/base.py file. Here is my local env file. # General # ------------------------------------------------------------------------------ USE_DOCKER=yes IPYTHONDIR=/app/.ipython # Redis # ------------------------------------------------------------------------------ REDIS_URL=redis://redis:6379/0 REDIS_HOST=redis REDIS_PORT=6379 # Celery # ------------------------------------------------------------------------------ # Flower CELERY_FLOWER_USER=xxxxx CELERY_FLOWER_PASSWORD=xxxx Here is my consumers.py file from channels.generic.websocket import JsonWebsocketConsumer class ChatConsumer(JsonWebsocketConsumer): """ This consumer is used to show user's online status, and send notifications. """ def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_name = None def connect(self): print("Connected!") self.room_name = "home" self.accept() self.send_json( { "type": "welcome_message", "message": "Hey there! You've successfully connected!", } ) def disconnect(self, code): print("Disconnected!") return super().disconnect(code) def receive_json(self, content, **kwargs): print(content) return super().receive_json(content, **kwargs) Heres my routing.py file from django.urls import path from chat_dj.chats import consumers websocket_urlpatterns = [ path('', consumers.ChatConsumer.as_asgi()), ] Heres my asgi.py file """ ASGI config It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/asgi/ """ import os … -
Code to display Django (Reverse) related table throws error
I'm quite new to Django and practicing Models section of Django by following its official tutorial. I also created a project of my own and try to apply similar concepts. This is my models.py; from django.db import models class Experience(models. Model): o01_position = models.CharField( max_length = 50 ) o02_year_in = models.DateField( null = True) o03_year_out = models.DateField( null = True) o04_project = models.CharField( max_length = 100 ) o05_company = models.CharField( max_length = 50 ) o06_location = models.CharField( max_length = 50 ) def __str__(self): return self.o01_position class Prjdesc(models.Model): o00_key = models.ForeignKey( Experience, on_delete = models.CASCADE) o07_p_desc = models.CharField( max_length = 250 ) def __str__(self): return self.o07_p_desc class Jobdesc(models.Model): o00_key = models.ForeignKey( Experience, on_delete = models.CASCADE) o08_job_desc = models.CharField( max_length = 250 ) def __str__(self): return self.o08_job_desc Now when I run below command in python / Django shell it runs as expected with the related data. >>> x = Experience.objects.get( pk = 2 ) >>> x <Experience: Head Office Technical Office Manager> Below two also work as expected; >>> y = Prjdesc.objects.get( pk = 11 ) >>> y <Prjdesc: Description 1> >>> x.prjdesc_set.all() <QuerySet [<Prjdesc: Description 1>, <Prjdesc: Description 2>]> However this expression does not return anything although it should return its … -
Django server running on a GCE instance cannot connect to postgres cloud SQL
I have a docker-compose that has django and an nginx as a reverse proxy docker-compose.yml: version: "3" services: app: restart: always command: ./startup.sh image: region-docker.pkg.dev/project_id/repo/image:tag container_name: backend expose: - "8000" volumes: - static_volume:/code/static hostname: app nginx: restart: always image: region-docker.pkg.dev/project_id/repo/image:tag volumes: - static_volume:/code/static ports: - "80:80" depends_on: - app volumes: static_volume: the database connection variables configuration in the settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'Instance': 'project_id:region:instance_name', 'NAME': 'database_name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'database_internal_IP', 'PORT': '5432', } } whenever I run docker-compose up in the VMs CLI the nginx runs perfectly but the django servers comes with this error django.db.utils.OperationalError: could not connect to server: Connection timed out backend | Is the server running on host "instance-private-IP" and accepting backend | TCP/IP connections on port 5432? Note: when I run psql -h instance-private-IP -U username the connection is successfully established Note: when I run the exact same container on my local pc with the same configurations with only the public IP instead of the private IP the container runs just fine Note: the service account attached to the VM has access to the cloud SQL enabled -
Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name
I'm trying to use my custom template for password change. So I created its template (registration/password_change_done.html) and wrote the urls as below: from django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView app_name = "accounts" urlpatterns = [ path( "accounts/password_change/", PasswordChangeView.as_view( success_url=reverse_lazy("accounts:password_change_done") ), name="password_change" ), path( "accounts/password_change/done/", PasswordChangeDoneView.as_view( template_name="registration/password_change_done.html" ), name="password_change_done" ), ] Password change works fine but when its form is submitted, I get this error: NoReverseMatch at /accounts/password_change/ Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. I searched about it and it seems like it should work when I set PasswordChangeView's success_url. But it didn't make any difference. -
Apache/mod_wsgi/Django AJAX : 500 Internal Server Error: ModuleNotFoundError: No module named 'corsheaders'
Our issue is stemming from a Django project finding the corsheaders module running via Apache/WSGI. The code runs fine using the Django's local runserver but throws a 500 Internal Server Error when acccessed throught Apache (v.2.4.41). If we comment out the application and middleware in settings.py, the site and other code works fine (execpt the API functionality that needs corsheaders). We have exhausted the online resources we can find, so thank you in advance for the advice to uninstall and reinstall django-cors-headers in a variety of ways using pip. We do use several other modules that have been installed via this gateway with no issue. The best we can tell, the issue stems from the django wsgi not seeing the module. I included the relevant logs and settings below. I also noted the install locations for the corsheader module. Relevant Versions django-cors-headers==3.13.0 (installed at: /home/geekfest/.local/lib/python3.8/site-packages) django-cors-middleware==1.5.0 python==3.8.10 Django==4.1.2 Ubuntu==20.04.1 pythonpath: ['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/geekfest/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] **settings.py** INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'corsheaders', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'stats', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.CommonMiddleware', 'stats.middleware.EventData', ] ROOT_URLCONF = 'geekstats.urls' CORS_ORIGIN_ALLOW_ALL = True error.log [Fri Oct 07 11:01:49.957188 2022] [wsgi:error] [pid 11860] … -
Django user two-factor authentication
I want to make user two-factor authentication (especially qrcode). I tried to use django-otp, but faced with problems. I add two-factor for admin, but don't understand how to do this for casual users. What can i use for this? -
Custom HTTP error pages in Django not working as intended
I want to make custom error pages for 404, 403, etc, but when I do anything mentioned in the documentation or any other forums/stackoverflow posts, it ignores the custom functions. I tried this already: How do I redirect errors like 404 or 500 or 403 to a custom error page in apache httpd? and many others. Am I doing something wrong? engine(custom app) \ views.py def permission_denied(request, exception): context = {'e':exception} return render(request, '403.html', context, status=403) core (main project) \ urls.py handler403 = 'engine.views.permission_denied' urlpatterns = [ path('admin/', admin.site.urls), [...] ...and it just shows the built-in error pages. Changing debug mode on or off doesn't change it. P.E.: when I pasted the views.py function, it threw an error saying it takes 2 arguments, one for request and one for the exception, so it knows that the function is there, but when I added it to the arguments, it still got ignored. Any advice appreciated! -
Django cached_property is NOT being cached
I have the following in my models: class Tag(models.Model): name = models.CharField(max_length=255) type = models.CharField(max_length=1) person = models.ForeignKey(People, on_delete=models.CASCADE) class People(models.Model): name = models.CharField(max_length=255) @cached_property def tags(self): return Tag.objects.filter(person=self, type="A") I would expect that when I do this: person = People.objects.get(pk=1) tags = person.tags That this would result in 1 db query - only getting the person from the database. However, it continuously results in 2 queries - the tags table is being consistently queried even though this is supposedly cached. What can cause this? Am I not using the cached_property right? The models are simplified to illustrate this case. -
Where do I install Apache2 in my existing Django Project
I have an existing Django project running on uWSGI, and I want to install apache2 to act as the web server. I found instructions online on how to do the installation - see link below. https://studygyaan.com/django/how-to-setup-django-applications-with-apache-and-mod-wsgi-on-ubuntu One thing the instructions does not mention is where do I run the installation. Do I run the installation in /root? Or somewhere else. Also, any feedback on the online instructions would be greatly appreciated. Thanks in advance -
Django Link to form with condition
On my base.html I have 2 links which lead to the same post_form.html and use the same forms.py. Link: <a class="list-group-item list-group-item-light" href="{% url 'post-create' %}">Submit</a> Problem is, I would like to hide/show part of the page depending on which link did user select. How can I do that? Below is script I use to hide a field, but I don't know which link did they use. (currently the links are the same, don't know what to add to make a change on the page 'post_form.html) <script type="text/javascript"> function on_load_1(){ document.getElementById('div_id_type').style.display = 'none';} on_load_1(); </script> -
Django, keep initial url path unchanged
I have a Django project with 5 apps. Basically, in the homepage there are 3 links. I'm still not in deployment so the base url is localhost:8000 (the homepage app is called homepage). After the user clicks in one of the 3 links I want the url to stay with that number, even after using different apps. Example of what I'm looking for: User clicks on link 1 and then -> localhost:8000/1. User clicks on link that directs to another app (called ros) -> localhost:8000/1/ros. And keep that one at the start of the url and only change if another of the 3 links in homepage is selected. Example of what I'm getting so far: User clicks on link 1 and then -> localhost:8000/ros/1 or localhost:8000/ros/2 or localhost:8000/ros/3 depending on the link clicked. The question is, how can I modify the homepage URL's and the app ROS url's so that the ROS url receive the link parameter (either a 1,2 or 3) + ROS.urls. HTML homepage code <li><a href="/" class="nav-link scrollto"><i class="bx bx-home"></i> <span>Inicio</span></a></li> <li><a href="1/ros/1" class="nav-link scrollto"><i class="bx bx-file-blank"></i> <span>ROS 1</span></a></li> <li><a href="2/ros/2" class="nav-link scrollto"><i class="bx bx-file-blank"></i> <span>ROS 2</span></a></li> <li><a href="3/ros/3" class="nav-link scrollto"><i class="bx bx-file-blank"></i> <span>ROS 3</span></a></li> Homepage URL … -
Scattermapbox code works as Dash app but is blank with DjangoDash
I want to display a map in Django using django_plotly_dash and map box. It is based on the "Basic example" from https://plotly.com/python/scattermapbox/. It works FINE AS STAND ALONE Dash app: import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from dash import Dash external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = Dash('Location', external_stylesheets=external_stylesheets) mapbox_access_token = open("./finished_apps/mapbox_token.rtf").read() fig = go.Figure(go.Scattermapbox( lat=['45.5017'], lon=['-73.5673'], mode='markers', marker=go.scattermapbox.Marker( size=14 ), text=['Montreal'], )) fig.update_layout( hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=go.layout.mapbox.Center( lat=45, lon=-73 ), pitch=0, zoom=5 ) ) app.layout = html.Div([ dcc.Graph(id='maplocation', figure=fig) ]) if __name__ == '__main__': app.run_server(debug=True) But is does not work in Django. Remark: Other Dash Plotly diagrams work in Django in this portal. The code differs only in three lines (marked with ###) between map box stand alone and Django version. import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from django_plotly_dash import DjangoDash ### external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = DjangoDash('Location', external_stylesheets=external_stylesheets) ### mapbox_access_token = open("./mapbox_token.rtf").read()### fig = go.Figure(go.Scattermapbox( lat=['45.5017'], lon=['-73.5673'], mode='markers', marker=go.scattermapbox.Marker( size=14 ), text=['Montreal'], )) fig.update_layout( hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=go.layout.mapbox.Center( lat=45, lon=-73 ), pitch=0, zoom=5 ) ) app.layout = html.Div([ dcc.Graph(id='maplocation', figure=fig) ]) It finds the map box token (Reason for the third change is the different levels … -
{% block content %} {% endblock %} showing in html while making chatbot
so I was following one chatbot tutorial using Django I came across this error my frontpage.html https://i.stack.imgur.com/TET9w.png my base.html https://i.stack.imgur.com/1eVg1.png my output https://i.stack.imgur.com/r4R0K.png so {% block title %} {% end block %} is not working kindly help.