Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React+Django deploy to heroku not reading Static files
my website works fine on local host but when i upload it to heroku i get The resource from “https://websitename.herokuapp.com/Static/js/main.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). on all static files both css and javascript index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=Muli:300,400,500,600,700,800,900&display=swap" /> <link rel="stylesheet" href="./Static/css/slicknav.min.css" type="text/css" /> <link rel="stylesheet" href="./Static/css/style.css" type="text/css" /> <title>React App</title> </head> <body> <div id="root"></div> <script src="./Static/js/jquery.slicknav.js" type="text/javascript" ></script> <script src="./Static/js/main.js" type="text/javascript"></script> </body> </html> i had to remove some of them from my post so they could fit. -
Angular 11 Django Heroku Deployment
i trying to deploy my Angular + Django with Postgres project to Heroku, and i don't know how to start and what to do. Can someone help? -
unable to store utf8mb4 in mysql
I'm using django with mysql. I want to change my unicode utf8 to utf8mb4 for storing emojis. i did try and change some fields. here is the variables- mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%'; +--------------------------+--------------------+ | Variable_name | Value | +--------------------------+--------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | collation_connection | utf8mb4_general_ci | | collation_database | utf8mb4_unicode_ci | | collation_server | utf8_general_ci | +--------------------------+--------------------+ 10 rows in set (0.00 sec) Right now when i'm trying to add an emoji its prints ? question mark. I also change my databse and my.cnf file- DATABASES = { ’default’: { ’ENGINE’: ’django.db.backends.mysql’, ’NAME’: ’example’, ’USER’: ’example’, ’PASSWORD’: ’example’, ’HOST’: ’’, ’PORT’: ’’, ’OPTIONS’: {’charset’: ’utf8mb4’}, } } and my.cnf- [client] default-character-set = utf8mb4 [mysql] default-character-set = utf8mb4 [mysqld] character-set-client-handshake = FALSE character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci somehow the collation server is still shows the utf8 encode and collation connection shows utf8mb4_general_ci -
How to create video conference in flutter and django?
I want create a app thats need to have video conference for multiple users(50 maybe), How can i create this in python django and flutter or react native (for mobile app) ? -
I need to print my username from app named users to in another app named board..It throws error (Cannot import username from users
Here is my code: users/views: from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.models import User,auth global username def login (request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return redirect("/") else: messages.info(request,'INVALID CREDENTIALS') return redirect('login') else: return render(request,'loogin.html') print(username) I need my username which is logged in on my board/view,But am not able to import and if am able to import i cant print and shows an error named NameError (username is not defined) Board/views: from django.http import JsonResponse from django.shortcuts import render from board.models import userboard from.utils import get_plot import pandas as pd from sqlalchemy import create_engine from users.views import username print(username) def graphview(request): qs = userboard.objects.all() x=[x.Month for x in qs] y=[y.Bp_Values for y in qs] chart = get_plot(x,y) return render(request, 'piechart.html' ,{'chart':chart}) def panddf(request): engine=create_engine('postgresql+psycopg2://postgres:#24May@2002@localhost/bhavesh') df = pd.read_sql_query('SELECT * FROM public."board_userboard"',con=engine) print(df) return render(request, 'abc.html') -
Django don't save the image from the form with ajax
I have an model with a bunch of fields class Guide(models.Model): image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) user = models.ForeignKey( User, blank=True, null=True, default=None, on_delete=models.SET_NULL, help_text=_("User, author/owner of this trip"), related_name="guide", ) active = models.BooleanField( default=False, help_text=_("Display it in trips list / search results?") ) featured = models.BooleanField( default=False, help_text=_("Display it on main/index page?") ) ... Form like this class ChangeImageForm(ModelForm): class Meta: model = Guide fields = ['image'] def __init__(self, *args, **kwargs): super(ChangeImageForm, self).__init__(*args, **kwargs) self.fields['image'].widget = FileInput(attrs={ 'name':'image', 'class':'image', 'id':'upload_image', 'style':'display:none' }) view def change_photo(request): if request.user.is_authenticated and Guide.objects.filter(user = request.user).exists(): item = Guide.objects.get(user=request.user) if request.method == "POST": form = ChangeImageForm(request.POST or None, request.FILES or None, instance = item) if form.is_valid(): form.save(commit=False) form.save() return HttpResponseRedirect('/profile/') ajax $.ajax({ type: 'POST', url: imageForm.action, enctype: 'multipart/form-data', data: fd, success: function (response) { $modal.modal('hide'); $('#uploaded_image').attr('src', fd); }, error: function (error) { console.log('error', error) }, cache: false, contentType: false, processData: false, }) I am trying to do cropping photo with CropJs, and save it with ajax, and so my photos are not saving in database , but when i upload it in admin panel all good, i think it might be something with permisions, but i dont know what is it -
Django Abstract User - how to create/save a profile each time a user has been created/updated
I know I don't have the standard User model to rely on, I don't know how to refer to the instance below. Before changing to the Abstract User Model I would refer to (user=instance). With Abstract User model: UserProfile.objects.create(userprofile=instance) The error I'm getting is Exception Value:'UserProfile' object has no attribute 'userprofile' Exception Location: /workspace/Project-Saasy/profiles/models.py, line 48, in create_or_update_user_profile models.py from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.conf import settings from django.dispatch import receiver class UserProfile(AbstractUser): """ A user profile model for maintaining default delivery information and order history """ is_volunteer = models.BooleanField(default=False) is_organisation = models.BooleanField(default=False) default_phone_number = models.CharField(max_length=20, null=True, blank=True) default_street_address1 = models.CharField(max_length=80, null=True, blank=True) default_street_address2 = models.CharField(max_length=80, null=True, blank=True) default_town_or_city = models.CharField(max_length=40, null=True, blank=True) default_county = models.CharField(max_length=80, null=True, blank=True) default_postcode = models.CharField(max_length=20, null=True, blank=True) class Volunteer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username class Organisation(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=UserProfile) def create_or_update_user_profile(sender, instance, created, **kwargs): """ Create or update the user profile """ if created: UserProfile.objects.create(userprofile=instance) # Existing users: just save the profile instance.userprofile.save() ``` -
How can I connect my packages (to call functions from them) to the Django project?
I have a task-to develop a bot + make a web admin panel for it -> in the admin panel, I need to output data from the bot's database, and from the admin panel to call some functions from the bot's packages (for example, turn the bot on or off). A simple import sees PyCharm, but Django swears that it doesn't find it. The picture shows how I want to import the functions. enter image description here If I misunderstand the concept, please correct me, I will be very happy (third day studying Django ): ) -
Heroku celery worker crashed
I have written app for email automation using: Django==2.2.19, django-celery-beat==2.2.0, redis==3.5.3 The desired outcome is to set a specific cron schedule and according to it send email messages. Everything works fine when I have local redis server, local celery worker and local django app. In app I am creating PriodicTask object with a specific crontab and email task to run. Localy App works as well using Herokuredis. I did setup worker in my Procfile release: python3 manage.py migrate web: gunicorn auto_emails.wsgi --preload --log-file - worker: celery -A auto_emails worker --beat --scheduler django --loglevel=info -
How to AutoWrap Statements with Jinja tags inside html file
is there a way to select the statements and wrap it with jinja tags ({% %}) inside html files? For Example. Lets say we have long text to comment,what we usually do is select the entire text and hit CTRL + /, So im looking some what similar , If i have statement like, if a == b after selecting the statement hitting the shortcut i want it to be wrapped with {% if a == b %}, If its possible please let me know -
theblockcrypto's embedded iframe not loading
I am embedding a chart from theblockcrypto.com on my django website. It's a simple iframe tag within the html: <iframe width="100%" height="420" frameborder="0" src="https://embed.theblockcrypto.com/data/crypto-markets/futures/btc-annualized-basis-binance/embed" title="BTC Annualized Daily Basis (Binance)"></iframe> It works fine within my runserver at home, but as soon as I move the code to my VPS(using the same runserver command), the chart doesn't load. The iframe just shows a loading logo. I get the following error in the js console: TypeError: Cannot read property 'getRegistrations' of undefined at 643985e.js:1 at h (72e8ff3.js:1) at Generator._invoke (72e8ff3.js:1) at Generator.next (72e8ff3.js:1) at r (72e8ff3.js:1) at l (72e8ff3.js:1) at 72e8ff3.js:1 at new Promise (<anonymous>) at 72e8ff3.js:1 at 643985e.js:1 Any idea what's going on? -
Long login times with Django Allauth
I set up my project using cookiecutter Django (https://cookiecutter-django.readthedocs.io/en/latest/index.html) with async and docker option turned on. Registering on the website works fast, only the sing in takes around 30 seconds. My Allauth configuration is set like this: # django-allauth ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) ACCOUNT_AUTHENTICATION_METHOD = "username" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_ADAPTER = "tum_vr.users.adapters.AccountAdapter" SOCIALACCOUNT_ADAPTER = "tum_vr.users.adapters.SocialAccountAdapter" Apart from that I used the base configuration from cookiecutter Django. Does anyone have an idea where I need to look for errors to fix this problem? -
Django problem on book Антонио Меле - "Django 2 в примерах"
I'm all trying to get over Django. I open the book by Antonio Mele - "Django 2 in Examples" and do everything as in the book. But for some reason I get errors. So this time I got stuck on the chapter Creating a Model Manager. The book says: Edit the models.py file of the blog application to add your me- nejer: class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): # ... objects = models.Manager() # Менеджер по умолчанию. published = PublishedManager() # Наш новый менеджер. python manage.py runserver enter image description here And I create a post again to help me. I don't understand how you can do something in this Django? it gives errors all the time! it's harder than learning python -
Warning: Your slug size (386 MB) exceeds our soft limit (300 MB) which may affect boot time
What will be the expected delay in boot time? This is from heroku and I had deployed a Django site. -
Not allowed to load local resource: I got this error in chrome console
I am doing an Django application , while placing a Background picture i got this error in console Not allowed to load local resource: file:///C:/UsersThripura%20saiPycharmProjectspythonProjectecomuploadsproducts%E0%AB%8ER_Aspire_7.jpeg my html code <style> body{ margin:0; color:#6a6f8c; background:#c8c8c8; background-image: url('C:\Users\Thripura sai\PycharmProjects\pythonProjectecom\uploads\products\ACER_Aspire_7.jpeg'); background-attachment: fixed; background-size: 100% 100%; background-repeat: no-repeat; font:600 16px/18px 'Open Sans',sans-serif; } nav{ background-color: black; } .one-edge-shadow { box-shadow: 0 8px 2px -5px rgb(246, 245, 245); } .display-8{ font-weight: 200; font-size: 30px; } please help me to to resolve this error -
Django queryset get quantity for all products
I have a query running inside a view that returns two records: cart_items = cartItem.objects.filter(cart=cart, is_active=True) <QuerySet [<cartItem: cartItem object (304)>, <cartItem: cartItem object (305)>]> 1 1 I'm trying to set the quantity and the name based on the query, meaning quantity=2 and name=Test, Test2 However i get quantity only for 1 product, (below code is running inside the view). for cart_item in cart_items: quantity = cart_item.quantity print(quantity) name = cart_item.product.name How can i set quantity based on the query? What i'm doing wrong? Thank you -
How do I load static JavaScript files inside django framework
I know I'm doing something wrong, after consulting the docs and watching 3 YouTube videos that get it spun up in the first 7 min and copying them it still doesn't work I'm basically trying to get to hello world from clicking a button The Relevant lines in my HTML {% extends 'box2.html' %} {% load static %} {% block content %} <button class="btn btn-success mt-3" type="button" onclick="handle_do_thing_click()" type="">Add Planner</button> {% endblock %} {% block js_block %} <script type = "text/javascript/" src="{% static 'js/doThing.js' %}"></script> {% endblock %} my settings.py static settings INSTALLED_APPS = ['django.contrib.staticfiles'] STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] and my js file which exists in app/static/js/doThing.js is hello world function handle_do_thing_click() { console.log("hello world"); } -
Why do I get 403 forgidden when cookies are used, and success if POST request is without cookies?
I use Django as my server and Android app as client. OkHttp on client side. It uses CookieJar for cookie handling. CookieJar works because I have a page that is availble only if user is signed in (aka has cookie). I have http://../api/picture/create/ page. It accepts post requests. When I try to send post request from andorid app, I get Forbidden: /api/picture/create/ [15/May/2021 13:23:28] "POST /api/picture/create/ HTTP/1.1" 403 58 If I use the same json body in browser (new client or authorised client = with or without cookies), it works perfectly fine. As well as if I remove cookie jar from OkHtttp client fro android. So, to be clear. It works if: No cookies in POST request With cookies in POST request if I use chrome with UI that django provides (mean I logged in first and then send post request to create picture) I am sure that cookies are not recreated in android app. Ones I logged in, I have only 1 cookie for okHttp cliient. So I am not even sure if it is Django or CookieJar/OkHttpClient error. Any tips where should I look to understand what is wrong? CookieJar setup static CookieJar cookieJar = new CookieJar() { … -
How to display post created time according to users country like Twitter in Django?
I tried django-tz-detect but it's not working in production. I also tried django-easy-timezones module that's also not working for me. I just want to convert UTC timezone to users country's timezone like Twitter or other social media in Django. -
Loop in Field name
I am trying to define a class with its different fields please someone can help me loop on the index of the field so that it is clean ? class Tabletarif (models.Model): age_duree = models.CharField (max_length = 4) U_20 = models.FloatField (default = 0) U_19 = models.FloatField (default = 0) U_18 = models.FloatField (default = 0) U_17 = models.FloatField (default = 0) U_16 = models.FloatField (default = 0) U_15 = models.FloatField (default = 0) U_14 = models.FloatField (default = 0) U_13 = models.FloatField (default = 0) U_12 = models.FloatField (default = 0) U_11 = models.FloatField (default = 0) U_10 = models.FloatField (default = 0) U_9 = models.FloatField (default = 0) U_8 = models.FloatField (default = 0) U_7 = models.FloatField (default = 0) U_6 = models.FloatField (default = 0) U_5 = models.FloatField (default = 0) -
How to send data from ESP8266 to Django local server
I am new to Django and even newer to ESP8266. I'm trying to send information from ESP8266 to my Django server using the POST method. The information looks like this: Temperature=24.60&Humiditi=30.30&Soil=0.00&Water=0&Light=602.00 So my ESP8266 code looks like this: #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> #define POMPA1 D0 const char* ssid = "****"; const char* password = "*****"; String serverName = "http://127.0.0.1:8000/data/"; int POMP1 = HIGH; char output; String output_str; String payload; String server_output = "rain"; unsigned long lastTime = -20000; unsigned long currentTime = 0; unsigned long remeberedTime = 0; int timeDelay = 20000; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); pinMode(POMPA1, OUTPUT); WiFi.begin(ssid, password); Serial.println("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(2000); Serial.print("."); Serial.println(""); Serial.print("Connected to WiFi network with IP Adress: "); Serial.println(WiFi.localIP()); Serial.print("DNS IP: "); Serial.println(WiFi.dnsIP()); } while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } } void loop() { // run over and over if (Serial.available()) { output_str = Serial.readString(); Serial.println(output_str); if (WiFi.status() == WL_CONNECTED) { HTTPClient http; http.begin(serverName); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); int httpCode = http.POST(output_str); payload = http.getString(); Serial.println(httpCode); Serial.println(payload); http.end(); } else { Serial.println("Server Disconnected"); } } Serial.println(payload); if (payload=="pompa1"){ currentTime … -
I have a python django app that was working fine until Pylance was automatically installed. Now I get an error: Exception has occurred:
My code is: from django.shortcuts import render # Create your views here. from django.views.generic import ListView # <- new from .models import Post def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) And the error I receive is from .models import Post Exception has occurred: ImportError attempted relative import with no known parent package Post is defined in: from django.db import models # Create your model fields here. from django.utils import timezone # for the DateTimeZone field below from django.contrib.auth.models import User # the author field below needs this class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() # TextField has no length limitation date_posted = models.DateTimeField(default=timezone.now) # Use the django timezone author = models.ForeignKey(User, on_delete=models.CASCADE) # if the User is deleted, so will this model def __str__(self): return self.title Any help would be appreciated. -
TemplateDoesNotExist on Django 3.2.2
I am getting the below error when, I am trying to add new application: TemplateDoesNotExist at /listings/ listings/listings.html Request Method: GET Request URL: http://127.0.0.1:8000/listings/ Django Version: 3.2.2 Exception Type: TemplateDoesNotExist Exception Value: listings/listings.html Exception Location: /home/brup/Desktop/Python/Django/FullWebApplication/btre_project/venv/lib/python3.6/site-packages/django/template/loader.py, line 19, in get_template Python Executable: /home/brup/Desktop/Python/Django/FullWebApplication/btre_project/venv/bin/python Python Version: 3.6.9 Python Path: ['/home/brup/Desktop/Python/Django/FullWebApplication/btre_project', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/brup/Desktop/Python/Django/FullWebApplication/btre_project/venv/lib/python3.6/site-packages'] Note: I have gone through these links but its not helping me, I have checked these. I have added pages application and its working fine, but when I am trying to added listing application its not working. Solution1 Solution2 Solution3 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Inside Installed Apps, I have done the the following: INSTALLED_APPS = [ 'pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] In urls.py I have added the following: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('pages.urls')), path('listings/', include('listings.urls')), path('admin/', admin.site.urls), ] Listing Application: Configuring urls.py in listing from django.urls import path from . import views urlpatterns = [ path('', views.index, name='listings'), path('<int:listing_id>', views.listing, name='listing'), path('search', views.search, name='search'), ] configuring views from django.shortcuts import render def index(request): return … -
Django(djongo) can't connect to MondoDB Atlas after Heroku deployment
I managed to get it working locally (different cluster), but not after when deployed to Heroku. Heroku - automatically adds DATABASE_URL config var with a postgresql, and I cannot remove/edit it. MongoDB Atlas - I've set the MongoDB Atlas cluster to allow IPs from everywhere. And the password has no funny characters. django settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'DBProd', 'CLIENT': { 'host': "mongodb+srv://XXX:YYY@ZZZ.pc4rx.mongodb.net/DBProd?retryWrites=true&w=majority", } } } django_heroku.settings(locals()) I ran migrate straight after the deployment and it's all green OKs heroku run python manage.py migrate Everything works functional wise, just that the data are not stored in the MongoDB Atlas cluster. There are lots of posts from various sites on this, but they all have different instructions... Some of the posts I tried to follow: https://developer.mongodb.com/how-to/use-atlas-on-heroku/ Django + Heroku + MongoDB Atlas (Djongo) = DatabaseError with No Exception Connecting Heroku App to Atlas MongoDB Cloud service -- A very confused beginner -
sessionStorage.getitem returns null in react
I was making an API in django which sets a key to session of user key is then sent to email of user. I need to use this key stored in session in my react app. I used request.session.setitem method to set a temporary key in user session, but when using sessionStorage to fetch that key in react app it gives null