Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load static file from JavaScript in Django?
Hello so I have been trying to play an audio element in my Django app and controlling it using JavaScript. I was trying to play the audio from localhost, but I got the following errors: And I guess it's because I made a mistake in loading the audio file in my JS code. import AudioPlayer from './AudioPlayer.js'; const audioPlayer = new AudioPlayer('.audioPlayer', [ {url: '../music/rainfall.mp3', name: 'Alleviating Rainfall'}, ]); I think I did wrong on the url: part so django does not load my mp3 file and serve it from the server. So my question is, how can I load static audio file in Django from JS? I know for HTML it's {% static "[filepath]" %} but what's for JS?? Since the JS itself is a static file.. Here's my file directory: -
Is the server running on host "postgres_db" (10.10.0.4) and acceptinG TCP/IP connections on port 5434?
This is docker compose for django environment: SECRET_KEY: "KEY" DEBUG: "True" NAME: "NAME" USER: "USER" PASSWORD: "PASSWORD" HOST: "HOST" PORT: "5434" depends_on: - postgres_db This is docker compose for postgres postgres_db: image: postgres environment: POSTGRES_HOST_AUTH_METHOD: trust POSTGRES_USER: ss POSTGRES_PASSWORD: ss PGDATA: /data/ss volumes: - postgres:/data/postgres ports: - "5434:5432" networks: main_network: ipv4_address: 10.10.0.4 restart: unless-stopped This is my database config data in django settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': "postgres_db", 'PORT': os.getenv('PORT') } } I can not find my mistake. I spent 4-5 hours but no success. still I get this error Is the server running on host "postgres_db" (10.10.0.4) and acceptinG TCP/IP connections on port 5434? when I write docker compose up -
Python deleting a repo from github with request module
I do not coding a this situation. I can create a repository in python using a request.post() but ı can not delete a this repository. Who want to help to me ? Code: def deleteRepository(self, repo, name): headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': 'token {}'.format(self.token)} response = requests.delete(self.api_url + '/repos/' + name + repo, headers = headers) return response.json() -
Django using modals for deleting a user
I want to delete users with modals in django. I have a deletion function which I don't know how I should return to template. views.py: @login_required(login_url='admin_signin') @admin_only def admin_profiles_deletion(request, username): context = {} account = Account.objects.get(username=username) account.delete() messages.success(request, "User deleted!") context['account'] = account return render(request, 'HOW SHOULD I REFER MODALS HERE?', context) And my urls.py looks: path('admin/profile/<str:username>/delete', views.admin_profiles_deletion, name='admin_profiles_deletion'), And finally my template is: <td class="text-center td-actions"> <a href="{% url 'admin_view_profiles' account.username %}"><i class="la la-eye view"></i></a> <a href="{% url 'admin_profiles_general_edition' account.username %}"><i class="la la-edit edit"></i></a> <a href="{% url 'admin_profiles_deletion' account.username %}" data-toggle="modal" data-target="#deleteaccount"> <i class="la la-close delete"></i> </a> <!-- Modal --> <div class="modal fade" id="deleteaccount" tabindex="-1" role="dialog" aria-labelledby="deleteaccountTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="deleteaccountTitle">Delete confirmation</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h5>Do you want to delete?</h5> </div> <div class="modal-footer"> <div class="col-6 text-left"> <div class="previous"> <form method="POST"> {% csrf_token %} <input class="btn btn-danger btn-sm btn-block" type="submit" name="submit" value="Yes"> </form> </div> </div> <div class="col-6 text-left"> <div class="next"> <a class="btn btn-info btn-sm btn-block" href="{% url 'accounts' %}">No</a> </div> </div> </div> </div> </div> </div> </td> In modal I want to hit YES and then delete specific account. but I don't know how to … -
How to generate a url that redirects to a specific view of another application
I'm working on a website, where I want to show all my django project. So, I have a main app, where i'm generating template for all my projects my home template when we access to the website: <!doctype html> {% load static %} <html lang="fr"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="{% static 'home/css/style.css' %}"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Nerko+One&family=Roboto&display=swap&family=Open+Sans&display=swap" rel="stylesheet"> <meta name="viewport" content="width=device-width"/> </head> <body> <header> <h1></h1> <span class="separator"></span> <h2></h2> <img src="{% static '/home/pictures/logo.png' %}" alt="logo" title="Ceci est mon logo" id="logo"> </header> <nav> <ul> <li><a href="" title="Aller à l'accueil">Accueil</a></li> <li><a href="#projects">Projets</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> <div class="contener"> <section> <h3>Projets</h3> <!-- conteneur --> <div id="projects"> {% for projet in projets %} <div class="project"> <a href="{% url 'projet-detail' projet.nom_lien %}"> <div class="picture"> <img src="{% static '' %}{{ projet.lien_image_presentation }}" alt="Présentation {{ projet.nom }}"> </div> <span>{{ projet.nom }}</span> <span class="date-project">{{ projet.date }}</span> </a> </div> {% endfor %} </div> </section> <section> <h3>Contact</h3> <div id="contact"> <p>Si vous désirez me contacter, n'hésitez pas à m'écrire à l'adresse <a href="mailto:aymerick.cotche@hotmail.fr"><b>aymerick.cotche@hotmail.fr</b></a></p> </div> </section> </div> <footer> <span>2020 © - Aymerick Cotche</span> </footer> </body> </html> template to see my project description : {% load static %} <html lang="fr"> <head> <meta charset="UTF-8"> <title>{{ projet.nom }} | {{ projet.auteur }}</title> … -
Purpose and use of Wagtail/Django template tags of the form {% block body_class %}template-homepage{% endblock %}
In the Wagtail docs (Your first Wagtail site) we are told to create a homepage.html template as follows: {% extends "base.html" %} {% load wagtailcore_tags %} {% block body_class %}template-homepage{% endblock %} {% block content %} {{ page.body|richtext }} {% endblock %} In the above code, what is that tag {% block body_class %}template-homepage{% endblock %} supposed to be doing? I can't find any mention of it in the text of the tutorial. The tutorial goes on to instruct us to create two more templates, blog_index_page and blog_page templates, both of which are to contain {% block body_class %} tags. Again, I can find no mention at all of those lines in the docs, let alone an explanation of how they might be used/modified. A search for "body_class" in the docs finds only the three code blocks just mentioned, and one other mention: in the version 1.2 release notes, under 'What's new — Minor features' the notation: "Simplified body_class in default homepage template." Any insight as to what I'm supposed to do with these tags? What special meaning, if any, does the tag-enclosed text have in the tutorial templates (for example, "template-homepage" in the code above)? -
Is there a page or an explanation of django testing functions?
I am looking at some tutorials on django testing from django.test import TestCase from .forms import ItemForm class TestItemForm(TestCase): def test_item_name_is_required(self): form = ItemForm({'name': ''}) self.assertFalse(form.is_valid()) self.assertIn('name', form.errors.keys()) self.assertEqual(form.errors['name'][0], 'This field is required.') I understand the importing and the class with it's parameters. I am struggling to understand the .assertXXX(). I tried looking in the documentation for django, for these functions and all I get are examples of them being used, not explanations of what they do. Then I went to GitHub to try and look under the tests folder for what the tests could potentially do and I do not fully understand their code. for example I understand that .assertEqual(<first>, <second>) compares the two parameters and checks if they are equal. I am looking for some site or some resource that can explain to me what they might potentially do, like a index or something that has similar documentation to JQuery. -
Multiple field text search in Django
I have an app "api", and a folder "models" in it. In that folder I have several ".py" files, such as "client.py", "therapist.py", "user.py" and etc. In "therapist.py" I have several classes, but I need just one class "TherapistProfile". In that class there are several fields, but I need just "name", "surname", "skills", "city" for searching. So the purpose is to search by writing a sentence. Example (of what user can write in the search bar): "Tommy davidson listening london" (and it has to be case insensitive). The words will be separated by space. Also it has to work if we miss any of the fields: "Tommy listening london" (we didn't write the surname) Also: "London listening tommy" (we are able to change the places of the words) Here is TherapistProfile class from models/therapist.py: class TherapistProfile(NonAdminProfile): user = models.OneToOneField(Therapist, on_delete=models.CASCADE, related_name='therapist_profile') skills = models.ManyToManyField(TherapistSkill, blank=True) city = models.ManyToManyField(TherapistCity, blank=True) ... PS The "name" and "surname" fields are in Therapist class (which inherits them from user.py). In TherapistProfile the field is written as "user". I kinda know the logic: I need to split the sentence into words by space and search each word in each field of each object (if you … -
Django how to limit template to only two posts
i would like to only show the last two posts added on the template (preferably the ones posted today only), i have seen this being done but not on class based views. from .forms import PostForm from .models import Post from django.views.generic import ListView from django.views import generic from django.urls import reverse_lazy class homeView(ListView): model = Post template_name = 'MAG-page.html' MAG-page.html {% for post in object_list %} <div class="col-lg-6 col-md-12"> <div> <!--Image--> <div class="view overlay rounded z-depth-1-half mb-3"> <img src="{{post.Thumbnail.url}}" class="img-fluid" > <a> <div class="mask rgba-white-slight"></div> </a> </div> <!--Excerpt--> <div class="news-data"> <a href="" class="light-blue-text"> <h6> <i class="fas fa-plane"></i> <strong> {{post.author}}</strong> </h6> </a> <p> <strong> <i class="far fa-clock"></i> {{post.Date}}</strong> </p> </div> <h3> <a> <strong>{{post.title|safe}}</strong> </a> </h3> <p> {{post.Text|safe}}</p> </div> {% endfor %} -
Store list of tuples django model in easy to access way
I'm creating django application for online Barber Shop booking. I came out with an algorithm that store avaliable hours. Here is exaple how it works. Let's say that barber_1 works form 8am to 4pm. We store this date in list with tuple {(8, 16)} if someone book an 1 hour apointment for 1pm it checks if it is between tuple and if it is, it creates 2 different tuples with updated hours {(8, 13), (14, 16)}, if another apointment is booked for let's say 10am, than it deletes first tuple and creates two new on it's place {(8, 10), (11, 13), (14, 16)} and so on and so on. I have a problem with "translating" my python code to the Django model. Can't find a way to store list of tuples in accesable way to be able to edit it. I read on different post that list of tuples can be stored in many to many relation but I dont think that it will be good in my case. -
Deploying Django DRF and Nuxt.js to Heroku (managing ports)
So I have deployed my Nuxt and Django to Heroku using the following buildpack. So I am running two servers in one app. So my frontend deployed successfully, however I can't setup the ports and hosts for my backend server. My frontends XHR requests are failing with 404, obviously my backend server should proxy to my frontend's "host" as /api/ route. I suppose it should be done using nginx - heroku module or somehow changing the procfiles with specifying the ports and hosts correctly. I would be more than glad if you could help me to clarify the setup structure. my Procfile.web django: gunicorn mydjango.wsgi:application --bind $HOST:$DJANGO_PORT node: cd frontend && yarn start -
The field admin.LogEntry.user was declared with a lazy reference to 'app2.user', but app 'app2' doesn't provide model 'user'
I am trying to build a custom-made User model in Django. My app name is app2. My models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_IndustryOwner = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) extraField = models.TextField(blank=True) I have already put AUTH_USER_MODEL = 'app2.User' in my settings.py and in admin.py: admin.site.register(User) admin.site.register(Employee) Now when I try to migrate I get the following error: Operations to perform: Apply all migrations: admin, app2, auth, contenttypes, sessions Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Python\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "G:\Python\lib\site-packages\django\core\management\commands\migrate.py", line 190, in handle pre_migrate_apps = pre_migrate_state.apps File "G:\Python\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "G:\Python\lib\site-packages\django\db\migrations\state.py", line 209, in apps return StateApps(self.real_apps, self.models) File "G:\Python\lib\site-packages\django\db\migrations\state.py", line 279, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'app2.user', but app 'app2' … -
django common context for views but for app only
app1/templates/test.html: {% load my_tags %} APP1: {% test_tag %} app2/templates/test.html: {% load my_tags %} APP2: {% test_tag %} app1/templatetags/my_tags.py: from django import template register = template.Library() @register.simple_tag def test_tag(): return 'Lord of the Rings' app2/templatetags/my_tags.py: from django import template register = template.Library() @register.simple_tag def test_tag(): return '3.14152925' And the result is of course wrong... it depends, which app is first in settings... APP1: 3.14152925 APP2: 3.14152925 how to rebuild this to get: APP1: Lord of the Rings APP2: 3.14152925 No changing names of tag, no changing name of templatetags file.... The best solution would be: {% load {% app_name %}/my_tags %} or {% load {% app_name %},my_tags %} - but of course it doesn't work.... (i have app_name template tag registered by processor if you want to use it) from django.urls import reverse def appname(request): return {'app_name': request.host.name, 'app_base' : '{}/base.html'.format(request.host.name) } -
How to return nested data according to user role in django rest framefork?
I have model which is connected to another model with foreign key, I have ApiView in django. Also, I have users with admin,moderator , and some roles. What I want is when Admin sends get request bring all nested data, when moderator sends get request return only one model's data. What can I do to implement it? I think to create several serializers classes to implement it. -
How can I find the Page Count of a Word Document with Python?
I have tried the approach of finding the page count in the docProps/app.xml file but this isn't very robust as the values can be easily manipulated. As I require this functionality for a website, I can't use win32com.client because it only works on Windows with Word installed. Is there a reliable way of finding the page count using Python? -
Display field (create with sql query) in fields= [ ] in Django admin?
I try create function create field dynamic. And i tried create function adding field with raw SQL query for django Ex : query_raw = "ALTER TABLE myapp ADD myField float(2);" and I had field with name "myField" in my database. But have i a trouble with edit it on Django admin. Because it's not showing on. Ex : First i have field in my db : MyName, MyYearOld, MySchool After i use query_raw i will have : MyName, MyYearOld, MySchool, myField in my database But in Django admin windowns, i just have field MyName, MyYearOld, MySchool. The "myField" cant display. -
Form validation in function views
Is there any difference between the 2 parts of code? def test(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() title = form.cleaned_data.get('title') #<<-- print(title) return redirect('blog-home') else: form = TestForm() return render(request, 'blog/test.html', {'form': form}) def test(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() title = request.POST.get('title') # <<-- print(title) return redirect('blog-home') else: form = TestForm() return render(request, 'blog/test.html', {'form': form}) Since both cases is part of form.is_valid() condition I believe it should be same right? -
django database won't show real time changes
my Django website connected to SQL server, when I make changes to the database on phpmyadmin page, for example, delete a field on a table, the data will remove, but my site shows it, if I rerun my app from pycharm, the changes show up, can you help me to have a real time database? Thanks -
UnboundLocalError at /: local variable 'query' referenced before assignment
This code worked yesterday but today when i open this i get unbounced local error!! I am trying to make a search using country name in an API and it should show me the context that i set up. Code: def index(request): url = 'https://api.covid19api.com/summary' result = requests.get(url).json() info = result['Countries'] if request.method == 'POST': query = request.POST['search'] for i in range(0,192): if query.lower() == info[i]['Country'].lower(): context = { 'country': info[i]['Country'], 'confirm': info[i]['NewConfirmed'], 'recover': info[i]['NewRecovered'], 'death': info[i]['NewDeaths'] } return render(request, 'corona/home.html', context) -
WIN10: Python env. variables suddenly changed themselves or sometihng?
This is the usual topic about with a twist , I think: For months I used Python+Django fine in a Win10 PC, running the bussines from the app folder like: python manage.py runserver Then one day sudenly with no change to the env vars that I recall, this happens: python manage.py runserver C:\Users\Admin\Desktop\Python\tjr>python manage.py runserver Can not find Python; etc etc... Also if I try jist py manage.py runserver BUT, typing only "py" starts the interpeter, so, yes, the python.exe is found by Windows, right? C:\Users\Admin\Desktop\Python\tjr>py Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> My env.vars.: enter image description here NOTE: I did not change the envvars or reinstalled Python or anyhing at all. This happened suddenly and I would like to know why. We do have thousands of posts about Python+Win+env.vars but this is more like, what happened? everything was fine and set up and now suddenly it errors our, same computer, same steps. Other posts advise to set the vars in the SysPath, not UserPath, ok, but, I had thse set in the user path all the time and worked fine, then … -
Add group to Proxy User
I'm using Django with Wagtail CMS and i created two proxy models from class User. I ant to add a group on user creation from the proxy classes. I tried to add signals but that apparently dose not work on proxy models. So on save i would like to add teachers to Teachers group and students to Students #models.py class User(AbstractUser): class Types(models.TextChoices): STUDENT = "STUDENT", "Student" TEACHER = "TEACHER", "Teacher" type = models.CharField(_('Type'), max_length=50, choices=Types.choices, default=Types.STUDENT) class Student(User): class Meta: proxy: True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.STUDENT return super().save(*args, **kwargs) class TeacherMore(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) models = models.CharField(max_length=255) class Teacher(User): class Meta: proxy: True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.TEACHER return super().save(*args, **kwargs) -
Django staticfiles not loading
I am using s3 to serve my static files. The files are present on the s3 bucket but when i run my website those files do not load up. I have installed django-storages and boto3 for this. This is what is see [Click Here to see the image] when i inspect the image i can see that the image url is pointing towards the s3 aws bucket but for some reason the css and images are not being shown on the website itself. here is my setting.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'accounts', 'blog', 'tinymce', 'storages', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'vedicmiracles.urls' 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', ], }, }, ] WSGI_APPLICATION = 'vedicmiracles.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Django Heroku Deployment No Module Found
I am trying to deploy a django project at https://testing-mike.herokuapp.com/ The deployment succeeded but it throws a no module found error. The same module with wsgi works on the local shell using this command : gunicorn --bind 0.0.0.0:8000 solvesto.wsgi:application but fails on heroku. -
Dictionaries in specific format
I need the below code in one specific formate ROOM_CATEGORIES={ ('Elt','Elite'), ('Lux','Luxury'), ('Sig','Signature') } Above code I want {'Sig':'Signature','Lux':'Luxury','Elt':'Elite'}<---Like This -
How to set up gunicorn
My django project in /root/code/mysite, django apps: main, homepage. What should I write in gunicorn.service? (Debian 9, user root)