Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve an InconsistentMigrationHistory in Django?
In our django project we had over 900 migrations and they were slowing down our tests. Due to complex interdependencies between apps, we decided that squashing wasn't a real option, so we wanted to reset them. However we have a couple of 3rd party apps as well (celery etc.) with their own migrations. After running python manage.py shell -c "from django.db import connection; cursor = connection.cursor(); cursor.execute(\"DELETE FROM django_migrations WHERE app IN ('api', 'user');\")" and makemigrations we are now trying to apply the migrations with --fake-initial. We are now getting the error django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency user.0001_initial on database 'default'. which makes sense as the database currently "thinks" that it has celery, admin etc. installed, but not user (even though it has). How could we work around this issue? Also we can't loose any data, otherwise I would just delete the migrations for this as well or reset the entire database. -
request.user returns AnonymousUser in Django
I'm trying to write a basic POST request that uses request.user but it sends an AnonymousUser, even though the request requires a token authentication to pass. views.py: @api_view(['POST', 'DELETE']) def like(request, id, *args, **kwargs): """ CRUD for a like """ # Called when a user swipes right if request.method == 'POST': print(request.user) payload = { 'source': request.user.id, 'target': id, } serializer = LikeSerializer(data=payload) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When I run print(request.user), I get in the output: AnonymousUser -
AttributeError: 'IntegerField' object has no attribute 'is_hidden'
I am trying to constraint the input for salary in the forms from taking negative values, that's why I am avoiding to use Numberinput(), but using IntegerField() is giving me the following error AttributeError: 'IntegerField' object has no attribute 'is_hidden' Sharing Forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee exclude = ['created_at', 'updated_at'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['salary'].validators.append(MinValueValidator(0)) widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'gender' : forms.Select(choices=GENDER_CHOICES, attrs={'class': 'form-control'}), 'dob': CustomDateInput(attrs={'class': 'form-control'}, min_date='1964-01-31', max_date='2002-12-31'), 'doj': CustomDateInput(attrs={'class': 'form-control'}, min_date='1990-01-01', max_date = datetime.now().date().strftime('%Y-%m-%d')), 'address': forms.TextInput(attrs={'class': 'form-control'}), 'city': forms.Select(choices=CITY_CHOICES, attrs={'class': 'form-control'}), 'state': forms.Select(choices=STATE_CHOICES, attrs={'class': 'form-control'}), 'team': forms.TextInput(attrs={'class': 'form-control'}), 'salary': forms.IntegerField(), } I want Salary in the forms to only take integer values -
django 2nd html page not visible
I am resently develop an website as a beginer and got the error like. expected page is not loading instred of 404(page not found) error is showing. we expect another contact.html page to be visible here. that page defined in another specific html file. -
Django error : the format for date objects may not contain time-related format specifiers (found 'H')
I'm trying to display the date of birth in a French format, everything works fine on my PC, but when copying the same project on another computer and running it, I had this error under the date of birth (even if I changed nothing in the code) : Django error : the format for date objects may not contain time-related format specifiers (found 'H') Here is my code : settings.py: # Format : day month year DATETIME_FORMAT = ('d F Y') template.html: <body> {% load i18n %} {% language 'fr' %} .... <td>{{ i.birthday|date:"DATETIME_FORMAT"|title }}</td> ... {% endlanguage %} </body> Is the problem with the browser ? or should I install some library ? -
Django model with properties that come from an external API
I want to have properties on a model that come from an external API. I also want to leave those properties blank when the ORM loads an instance of the model so that queries within the ORM aren't making API requests unless explicitly asked. It'd be nice if I could call a function on the model to retrieve those external properties, maybe something like .with_external(). How could I achieve this? Here's what I'm starting with: class Project(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=True, blank=True) @property def external_id(self): external_id = requests.get({API_URL}) return external_id -
Docker Nginx Django [emerg] host not found in upstream /etc/nginx/conf.d/nginx.conf
I'm new to web applications landscape and just trying to deploy a basic Django application with Gunicorn, Nginx and podman (version 4.4.1) on Red Hat Linux Enterprise 8.7. Dockerfile for Nginx is the official image from Docker Hub v 1.25.1. There's no docker-compose/podman-compose available on the server. I'm starting the build by creating a dedicated network: podman network create testapp-net The next component is Django application: podman build -t testapp-django -f src/testapp-django/compose/django/Dockerfile . Dockerfile for the app is based on Ubuntu base image and I'm exposing port 8000: FROM ubuntu:22.04 ... RUN addgroup --system django \ && adduser --system --ingroup django django ... WORKDIR /app ... RUN chmod +x /app ... EXPOSE 8000 ... COPY src/testapp-django/compose/django/entrypoint /entrypoint RUN sed -i -e 's/^M$//' /entrypoint RUN chmod +x /entrypoint RUN chown django /entrypoint COPY src/testapp-django/compose/django/start /start RUN sed -i -e 's/^M$//' /start RUN chmod +x /start RUN chown django /start RUN chown -R django:django /app USER django ENTRYPOINT ["/entrypoint"] /entrypoint: set -o errexit set -o pipefail set -o nounset exec "$@" /start: set -o errexit set -o pipefail set -o nounset python3 /app/manage.py migrate gunicorn testapp.wsgi:application --bind 0.0.0.0:8000 --chdir=/app Starting the Django app is successful: podman run -d -p 8010:8000 --name testapp-django … -
Which frame work to use to build a web app [closed]
I have a desktop application that used to work with the tkinter package. But I need to turn it into a web application, so I have to rewrite it. I don't know which framework to choose between Django, Turbogears, Web2py and Cubicweb, as I'm not familiar with any of them. My application has 4 pages, the home page and 3 other pages accessible via buttons on the home page. These tabs contain large graphs in the form of a network and a map with numerous filters, everthing is built using data loaded when the application is launched (the data are loaded using an url link). The application also features images, help buttons that open a help pdf, and buttons to return to the home page. I have no idea which framework would be best suited to my problem and at the same time the easiest to use. From what I've read, I'd go for Django, even if it's a bit complex, especially as there are lots of tutorials on youtube. Thanks ! -
Django and react router shows blank page without content
I am using react inside django. I use npx create-react-app and npm run build to create react . The structure looks like this frontend main mysite In react I have two components. Form and App. App is the one that renders all other components. In settings I have configured frontend/build to be the templates. main/views.py def createUser(request): return render(request, 'index.html') main/urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('register/', views.createUser), ] frontend/src/App.js import Form from './Form'; import { BrowserRouter as Router, Routes, Route} from 'react-router-dom'; <Router> <Routes> <Route exact path='/register' element={<Form/>} /> </Routes> </Router> When I go to /register I get a blank page with the css that I wrote for form.js but nothing else shows. -
I don't understand why the code is not working
here is the error: >>> from blog.models import Post >>> user = User.objects.get(username='admin') Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'User' is not defined >>> here is the model: from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) author = models.ForeignKey( User, on_delete=models.CASCADE,related_name='blog_posts' ) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2,choices=Status.choices,default=Status.DRAFT) class Meta: ordering = ['-publish'] indexes = [models.Index(fields=['-publish']),] def __str__(self): return self.title I tried to change this part of the code ' 'to this 'from django.contrib.auth.models import User' but it did not help -
Django React Heroku
I have this problem {status: 'PARSING_ERROR', originalStatus: 200, data: '<!doctype html><html lang="en"><head><meta charset…pp.</noscript><div id="root"></div></body></html>', error: SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON} data : "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"/><link rel=\"icon\" href=\"favicon.ico\"/><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/><meta name=\"theme-color\" content=\"#000000\"/><meta name=\"description\" content=\"Chisfis | Online Booking – a responsive React template theme with Online booking, Real Estate, and booking system for accommodation, tours, travel experiences, cruises, car rentals, real estate, and travel agencies\"/><link rel=\"apple-touch-icon\" href=\"./logo192.png\"/><link rel=\"manifest\" href=\"./manifest.json\"/><title>Chisfis || Hotel booking Template</title><script defer=\"defer\" src=\"/static/js/main.6b24de68.js\"></script><link href=\"/static/css/main.c71aaa5c.css\" rel=\"stylesheet\"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id=\"root\"></div></body></html>" error : "SyntaxError: Unexpected token '<', \"<!doctype \"... is not valid JSON" originalStatus : 200 status : "PARSING_ERROR" [[Prototype]] : Object How do solve this problem? -
ckeditor don't appear in django form
I designed a web with Django . I use CKEditor for content of a model but after I connected my site to bucket storage, box CKA editor disappeared and won't upload so I can upload text, what's the problem? enter image description here what do I do? -
List view for user specific data?
I am a beginner in django . I am trying to get build a notesapp, but when a user logged in they are able to see all the all notes that are present in the admin panel. when I tried the below view function im just getting a blank page.How to write a view function such that a particular user can see the notes only they made . I have the following views.py @login_required(login_url='login') def Viewall(request): notes = NotesModel.objects.filter(user=request.user).all() return render(request, "Viewall.html", {'notes':notes}) models.py class NotesModel(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,null=True) title=models.CharField(max_length=255,unique=True) note=models.TextField() time=models.DateTimeField(auto_now_add=True) viewall.html {% for data in notes %} <div class="col"> <div class="card note_card"> <h5 class="card-header">{{ data.title }}</h5> <div class="card-body"> <h5 class="card-title"></h5> <p class="card-text">{{ data.note|truncatechars:50}}</p> </div> </div> </div> {% endfor %} -
How to set download directory?
def download_video(url, save_path): loader = instaloader.Instaloader() try: post = instaloader.Post.from_shortcode(loader.context, url.split("/")[-2]) video_url = post.video_url response = requests.get(video_url, stream=True) if response.status_code == 200: with open(save_path, 'wb') as file: response.raw.decode_content = True shutil.copyfileobj(response.raw, file) print("Video downloaded successfully!") else: print("Failed to download the video.") except Exception as e: print("Failed to download the video:", str(e)) I created this function to download instagram video from it's url, i add this on my website. Problem: Its was working fine when i wasn't using on my website, i want it available for everyone online, Error : Failed to download the video: [Errno 13] Permission denied, How can i fix it, so that it can download in users downloads folder and on mobile. Thanks help me to solve the error. -
ImproperlyConfigured: settings.DATABASES error in Django project
I made simple reservation website in django. And It works just fine in dedicated server but it returns this error when i try to migrate it in local machine. django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I haven'touched anything in DATABASES. So it looks like this DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } Is there any possible solution for this problem? I've tried some solutions that i found online such as adding from .database import * But it didn't work at all for me. -
converting HTML to PDF using wkhtmltopdf Python
I am converting HTML to PDF. PDF downloaded success but it return blank pdf pages not showing any converted content. in my HTML file have Shopify CSS links. if convert minimum content HTML file then it converted correctly from django.shortcuts import render from django.http import HttpResponse import pdfkit from django.conf import settings def convert_html_to_pdf(request): if request.method == 'POST': rendered_template = render(request, 'newundergrace.html') HTML file options = { 'enable-local-file-access': '', 'orientation': 'landscape', 'page-size': 'Letter', 'page-size': 'A4', 'margin-top': '0', 'margin-right': '0', 'margin-bottom': '0', 'margin-left': '0', 'dpi': 96, } rendered_content = rendered_template.content.decode('utf-8') pdf = pdfkit.from_string(rendered_content, False, options=options) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=output.pdf' response.write(pdf) return response return render(request, 'index1.html') -
Docker, Django(gunicorn) + Nginx | django's admin CSRF 403 error
I confused this situations. :( I want to run Docker compose Django + Nginx at AWS EC2/ALB the docker compose and nginx.conf, AWS setup is below, django is gunicorn example_mvp.wsgi -b 0.0.0.0:8000 then, nginx listen 80 to proxy_pass http://example_mvp:8000 nginx.conf http { server { listen 80; include /etc/nginx/mime.types; client_max_body_size 16M; location /favicon.ico { return 204; access_log off; log_not_found off; } location /static/ { alias /staticfiles/; } location / { proxy_pass http://example_mvp:8000; proxy_redirect off; proxy_set_header Host $http_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; } } } AWS EC2, security group inbound 80,443 port open. and AWS ALB setup, (generate domain SSL via AWS Certificate Manager) 1. https:443 -> http:80 2. http:80 -> redirect:443 so, my domain connect ALB. problems I access the admin page, but CSRF 403 error. my product's settings attach the CSRF_TRUSTED_ORIGINS settings.py DEBUG = False CSRF_TRUSTED_ORIGINS = ["https://mydomins.com"] but access admin page or POST forms, always return 403 error. I check the ALB setup, 2. http:80 -> http:80, and access admin page ok. (not 403 error) I don't know what's the problems -
How to Subcribe to an update of database django
When using Django model, I have an table name "AppConfig". What I want is that whenever there is an update on AppConfig table (inluding create,modify,delete) the result will log into a file. Is there an convenient way to do it. I can do this by adding log function to every point that I update the Config table in code. But it is quite messy and there is potential of mistake. -
"connection timeout expired" in PostgreSQL15
requirement: try to connect pgAdmin4 to Server, and it need to insert password, and I'm sure the password what i insert (I have reinstalled it again and again but i can't work) processing: so first when i installed postgre15 and pgAdmin4, that's all no block, and it let me customize password and i made it. when it come to finish for pgAdmin and postgreSQL, I select the pgAdmin4 to create database, the error is comming, below is troubleshoot. shotimage I want to connect to Server in pgAdmin4 first. -
Fallback or Error Handling for Secondary Django Database
I have a second database in my Django application. However, I need a VPN to connect to it. If my VPN is not enabled psycop2 will throw an operational error back at me. However, I would like the ability for that database to fail silently and fallback to the default database in case the connection is refused. Is there a way to do this? I cant seem to find a default way and it seems like a very basic functionality to have. I have tried to implement something through routers suggested in stackoverflow before, but at startup my application will simply say OperationalError: Connection Refused and then crash the rest of the startup procedure. class OVIRouter: """ A router that takes all of the reads, writes and changes to the OVIDevice model (also known as "ovidevice" once the model is translated to SQL), and sends them to the OVI database (The database configured in settings.py through the "ovi_db" entry in the DATABASES constant). """ db_name = 'ovi_db' def db_for_read(self, model: Model, **hints: Any) -> Optional[str]: """ Attempts to read the OVIDevice model go to the OVI device database. If the connection to the OVI device database fails, the default database … -
Unable to add an image in Django Admin page hosted on EC2 with Apache2 server
I am learning Django deployment on EC2 with Apache server. I am able to serve static files. But when I try to add an image via Admin page, I am getting below error. The permissions for media_root is as below I am able to add image with Django server inside the instance, but with Apache server I am getting error. Apache2 is configured as below Alias /static/ /home/ubuntu/testing/dummy/static_root/ Alias /media/ /home/ubuntu/testing/dummy/media_root/ <Directory /home/ubuntu/testing/dummy/static_root> Require all granted </Directory> <Directory /home/ubuntu/testing/dummy/media_root> Require all granted </Directory> WSGIScriptAlias / /home/ubuntu/testing/dummy/dummywebsite/wsgi.py <Directory /home/ubuntu/testing/dummy/dummywebsite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess loserprocess python-home=/home/ubuntu/testing/testingenv python-path=/home/ubuntu/testing/dummy:/home/ubuntu/testing/testingenv/lib/python3.10/site-packages/ WSGIProcessGroup loserprocess WSGIApplicationGroup %{GLOBAL} I have given the permission as mentioned here, but still I am facing issue. Can you please let me know what I am missing here. Thanks -
POST 403 Forbidden Django Vue Js
I am using Vue JS and Django Rest Framework and I am trying to add a feature to add a blog post. I am not sure why I am getting a 403 forbidden error in the console. I am getting the following error: Forbidden (Origin checking failed - http://localhost:8080 does not match any trusted origins.) Any direction would be appreciated I am not sure if this is a CORS related error but I have CORS_ALLOWED_ORIGINS = ['http://localhost:8080'] in my settings.py. I have also enabled the middleware. I have a login page that works and assigns the user a token when logged in (I am using djoser). I have made sure that the user has permissions to add a blog entry. here is my code for submitform if relevant: submitForm() { const postData = { title: this.title, author: this.author, body: this.body, }; const token = localStorage.getItem('token'); // Retrieve the authentication token from local storage axios.post('/api/v1/posts/add-post/', postData, { headers: { Authorization: `Token ${token}`, // Include the token in the request headers }, }) .then(response => { console.log(response.data); // Handle success, e.g., show a success message or navigate to another page }) .catch(error => { console.log(error); // Handle error, e.g., show an error … -
Error on testcase after update from django 2 to 4
I'm updating my entire project from Django 2.2 to Django 4.2.3. I have already read the entire deprecation timeline and done regression tests, and everything is working. But, using the TestCase, I found a difference: tear_down isn't flushing the database after each test, and when it runs, models that are created in migrations are removed as well. Does anyone know what has changed between those versions that can affect tests, teardown, and flush? I tried debbug testcase source code while running my tests, and read changelogs and deprecation list from django docs but without any tip. -
Real Estate Project - Error in Pagination Code
I am a web developer student and I am currently working on a real estate project. I have created a pagination system that allows users to view a list of properties in pages of 10. However, I am getting an error when I try to load the second page of properties. The following is the code that I am using for the pagination: def get_properties(page_number): if page_number is None: page_number = 1 start_index = (page_number - 1) * 10 end_index = start_index + 10 properties = Property.objects.all().order_by('-list_date')[start_index:end_index] return properties The error that I am getting is: Page Not Found (404) The requested page could not be found. I have tried debugging the code, but I cannot seem to find the source of the error. I am hoping that someone can help me troubleshoot this issue. -
Nginx + Gunicorn + Django: displays Nginx default page every 3 times
I have a Django app on Gunicorn 20.1.0 (:8000), served with Nginx 1.18.0 as the main server (link to the website) on Debian 11.2: Nginx <-:8000-> Gunicorn <-> Django The server displays the Nginx default template every three times (1st request, 4, 7, 10, so on). Here is a snippet of the Nginx access log (notice the pattern in the bytes sent): 89.xx.xxx.xx - - [05/Jul/2023:11:37:23 -0400] "GET / HTTP/1.1" 200 396 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:51 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:52 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:53 -0400] "GET / HTTP/1.1" 200 396 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:54 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:54 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" ... There's no error in Nginx or Gunicorn error.log files (both server and site specific logs are blank. previously I had some errors so I'm assured that the logging is …