Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In my Django-project how can I dynamically append a script which is located in the static folder to the head-section?
In my Django-project I would like to dynamically append a script-tag to the head-section. The script I want to append is located in static-folder. The problem is that I don't know how to reference the static-folder in javascript, or if that is even pssible. This is (a part of) my Javascript: jQuery( window ).on( "load", () => { const script = document.createElement("script"); script.src = "{% static 'js/myScript.js' %}"; document.head.appendChild(script); }); myScript.js could look like this: console.log("This is myScript") Of course this does not work. In the console I get: GET http://127.0.0.1:8000/%7B%%20static%20'js/myScript.js'%20%%7D net::ERR_ABORTED 404 (Not Found). Is there a way to reference the static-folder inside a javascript? -
Python doesn't see packages in virtual environment
I try to deploy my first django project on heroku and for that i need to import whitenoise. I have it installed in site-packages, but have an ImportError when import it. And python doesn't see packages in there apart from django and default ones. I'm quite a novice and don't understand what it means and what to do. Tried to add PYTHONPATH to activate, add a new path in SystemPropertyAdvanced, didn't help -
datetime-local time format does not conform to the required format
I hope this question is not a duplicate - I was at least not able to fix the issue by looking at other similar Q&As. I'm making a web application using Django 2.2, Postgresql 9.5 and Django template language with bootstrap for front end. In settings.py I have the following time settings: TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True In some of my forms I have datetime-local fields: date = forms.CharField(required=False, widget=forms.DateTimeInput( attrs={ 'type':'datetime-local', 'class':'form-control', } )) In my Django template I render the date field as shown below: <input type="datetime-local" id="id_date" class="form-control" value="{{ basic_form.date.value|date:"c"}}"> I'm getting the following error when loading a page with date field having a date value retrieved from database. And I'm not able to display the date in the form date field: The specified value "2020-10-28T09:28:00+00:00" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS". I have also tried to 'render' the date field in the template directly from the form variable received by views.py: {{ basic_form.date }} ...and then I get a same warning, however the date value does not contain the T 'separator': The specified value "2020-10-28 09:28:00+00:00" does not … -
Connecting to Mongodb from Django application hosted on heroku
I am trying to connect my djnago application hosted on heroku. I have also changed the DATABASE_URL on heroku settings as: mongodb+srv://<name>:<password>@cluster0.wtnph.mongodb.net/test I am using python 3.9 and django 3.0.5 But when deploying to heroku, I am getting the error. > -----> Python app detected -----> No change in requirements detected, installing from cache -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_91bba5c0/kibo_skill_matrix_api/settings.py", line 176, in <module> django_heroku.settings(locals()) File "/app/.heroku/python/lib/python3.6/site-packages/django_heroku/core.py", line 69, in settings … -
Filter child related object and return empty list if none is found
Is there a way to filter child objects and return an empty list if no related object matching the query is found? At the moment I'm doing it in this way: Person.object.filter(item__is_active=True) If no active item is found, None is returned. I want to still get the Person object but with the items attribute as an empty list. -
Upload csv file and return back information in Django
views.py from django.shortcuts import render import pandas as pd import csv # Create your views here. def home(request): return render(request,'hello/home.html') def output(request): csvfile = request.FILES['csv_file'] data = pd.read_csv(csvfile.name) data_html = data.to_html() context = {'loaded_data': data_html} return render(request, "hello/home.html", context) Here I am trying to get the uploaded file and convert the file to table format. While doing this,I am getting No such file or directory: 'file.csv' Please help in solving this -
Nginx + uwsgi + Django
Django web application deployed with nginx + uwsgi. If we daemonize the application, the api request using fetch is leading to a 504 Gateway Time-out. I have tried to fix it by using proxy timeout and gateway timeout but no luck. Also after restarting the server I am able to see the output but this doesnt happen when we run uwsgi in normal mode (not daemonized) -
OSError: [Errno 24] Too many open files , [ django , python , PyCharm ]
I faced this problem when i tried to upload about 7000 images via django. I want all of them open to pass them to Yolo-core, who can help me? During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Asus\Anaconda3\lib\wsgiref\handlers.py", line 137, in run File "C:\Users\Asus\Anaconda3\lib\site-packages\django\contrib\staticfiles\handlers.py", line 66, in __call__ File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\wsgi.py", line 146, in __call__ File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 81, in get_response File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 37, in inner File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 87, in response_for_exception File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 122, in handle_uncaught_exception File "C:\Users\Asus\Anaconda3\lib\site-packages\django\views\debug.py", line 94, in technical_500_response File "C:\Users\Asus\Anaconda3\lib\site-packages\django\views\debug.py", line 331, in get_traceback_html File "C:\Users\Asus\Anaconda3\lib\pathlib.py", line 1176, in open File "C:\Users\Asus\Anaconda3\lib\pathlib.py", line 1030, in _opener OSError: [Errno 24] Too many open files: 'C:\\Users\\Asus\\Anaconda3\\lib\\site-packages\\django\\views\\templates\\technical_500.html' [28/Oct/2020 10:44:30] "POST /train HTTP/1.1" 500 59 Exception ignored in: <function TemporaryFile.__del__ at 0x000001F16A1EE488> Traceback (most recent call last): File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\files\temp.py", line 61, in __del__ File "C:\Users\Asus\Anaconda3\lib\site-packages\django\core\files\temp.py", line 49, in close AttributeError: 'TemporaryFile' object has no attribute 'close_called' -
i got pylint error how to fix this anyone please help i am working with django development server
enter image description here I got this pylint error please tell me how to fix this? -
Query the n-th most recent entries for each unique type, for all types in Django
I have researched this issue and answers are about getting the most recent for each type, e.g. this topic. The difference is I would like to get the n most recent items for each type, for ALL types. At the moment I get all items, then in python find the n-th most recent entries, which is very slow. e.g. class CakeType(models.Model): name = models.CharField() class CakeEntry(models.Model): cake_type = models.ForeignKey(CakeType, on_delete=models.CASCADE) created = models.DateTimeField() How would one get say the 5 most recent CakeEntry's for all the distinct/unique CakeType's? I migrated DB from MySQL to PostgreSQL (a lot of work) so I can use Postgres's DISTINCT ON. -
Events auto delete in Django / Python
I have an event calendar in Django / Python and I am trying to get it to automatically not show events that have already passed based on the current date. The code I am working with looks like this: {% for event in view.events %} <div class="py-2"> {% if event.date < Today %} <ul> <li class="font-bold text-gray-900">{{ event.date }}</li> <li class="font-medium text-gray-800">{{ event.name }}</li> <li class="font-medium text-gray-800">{{ event.description }}</li> <strong><p>Location:</p></strong> <li class="font-medium text-gray-800">{{ event.location }}</li> {% if event.website_url %} <a class="font-medium text-gray-800 hover:font-bold hover:text-blue-600" href="{{ event.website_url }}" target="blank">Information </a> {% endif %} {% endif %} </ul> </div> In the top of the code I have the line: {% if event.date > Today %} What can I replace Today with to make this work? Any ideas? -
The best way to make a matrix-like form in Django?
I'm making a booking site on Django with sqlite database. I want a model which has entries for data of day, and a form which has boolean fields for each booking slot. What is the best way to realize this? Do I need to use ForeignKey relationships between day, room and slot models? If yes, how do I do that? -
how to give custom validation in django and djangorestframework on creating an API?
Here is my question I am creating address model, in that city, district I am accepting null values, Because for some API View I will accept Null values, but another API I will call this same models that time I want to validate that field is required, How Its is possible Here is my below code example. models.py class Address(models.Model): address_line1 = models.CharField(max_length=250) address_line2 = models.CharField(max_length=250, blank=True, null=True) city = models.ForeignKey('Cities', on_delete=models.DO_NOTHING, blank=True, null=True) district = models.ForeignKey('Districts', on_delete=models.DO_NOTHING, blank=True, null=True) class Assignaddress(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE) owner_name = models.CharField(max_length=255) class dont`Assignaddress(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE) owner_name = models.CharField(max_length=255) Now in serializer.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ('address_line1','address_line2','city','district') class AssignaddressSerializer(serializers.ModelSerializer): class Meta: model = Assignaddress fields = ('address ','owner_name ') class dont`AssignaddressSerializer(serializers.ModelSerializer): class Meta: model = dont`Assignaddress fields = ('address ','owner_name ') now How can I validate Assignaddress you have to pass city and district is required and don`tAssignaddress its not neccessary Sorry for not writting views.py -
Error when trying to decode json: simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I'm receiving this error when trying to decode json: simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Any help will be appreciated. views.py: from django.shortcuts import render import requests def home(request): response = requests.get('https://dev-api.prime.com/api/v1/hub/login') data = response.json() return render (request, 'home.html', { 'email': data['email'], 'password': data['password'] }) urls.py: path ('home/', views.home, name="home"), home.html {% extends 'main.html' %} {% block content %} <h2>API</h2> <p>Your email is <strong>{{ email }}</strong>, and password <strong>{{ password }}</strong></p> {% endblock %} -
How to reload html src of an image in django
My Django app import an image from the media_url and then it goes to the next page and shows the image and goes back to first page then a new image imported and the old image is removed. The problem is that at the first loop everything is good, in the second loop, it appears that html shows the old image not the new one. how can I apply a reloading in html. here is part of the code: settings.py: MEDIA_ROOT = 'media//' # I test the MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media//' views.py: def scraping(request): .... template_name = "scraping.html" response2 = {'media_root': Config.MEDIA_ROOT, 'media_url': Config.MEDIA_URL} return render(request, template_name, response2) scraping.html <img src='{{media_url}}/pic.jpg//'> # I also tried {{media_url}}pic.jpg {{media_url}}/pic.jpg/ {{media_url}}//pic.jpg// -
Django using loaddata from subfolder setup
Here's the INSTALLED_APPS setup INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... #imported old dependencies 'lamusoftware.blog', ] trying to loaddata to blog like so (kpsga) sam@sam:~/code/kpsga$ python manage.py loaddata blog < new_blog.json CommandError: No fixture named 'blog' found. or (kpsga) sam@sam:~/code/kpsga$ python manage.py loaddata lamusoftware.blog < new_blog.json CommandError: Problem installing fixture 'lamusoftware': blog is not a known serialization format. without restructuring the folder setup is there a way to make it work? -
Django not discovering models when moved into folder
My previous layout: project: app: models.py Right now it is like this: project: app: models: __init__.py model_name.py Because I have many more models now so I had to separate them. Inside project/app/models/__init__.py I have imported the model, hence I can import from app.models instead of app.models.model_name, but I'm getting ImproperlyConfigured. django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed settings.py: APPS = [ 'comments', 'forums', 'notifications', 'posts', 'privatemessages', 'profiles', 'subforums', 'summaryreports', 'users', ] Users app layout: users.models.init.py: from users.models.user_backends import UserBackend from users.models.users import User users.apps.py: from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' Why??? EDIT: In settings.py, also tried: APPS = [ 'comments.apps.CommentsConfig', 'forums.apps.ForumsConfig', 'notifications.apps.NotificationsConfig', 'posts.apps.PostsConfig', 'privatemessages.apps.PrivateMessagesConfig', 'profiles.apps.ProfilesConfig', 'subforums.apps.SubforumsConfig', 'summaryreports.apps.SummaryreportsConfig', 'users.apps.UsersConfig', ] Django version is 3.1. Python 3.8.5. WSGI and ASGI are properly pointing to settings.py. -
Converting Model object to Json in graphene
I am fetching models data using graphene resolver. Below is the models. class Movie(models.Model): name = models.CharField(max_length=100) genere = models.CharField(max_length=50) budget = models.FloatField() releaseYear = models.IntegerField() files = models.FileField(upload_to='', default="") Below is the resolver def resolve_all_movies(self, info, search=None): record_count=12 filtered_count=8 return session.query(Movie).all() Now I also wants to get the record count( in above it is hard coded). How to send all movie data and record_count and filtered_count. else how to convert movie objects to json so I can convert all the three data to json and return. -
Django NOT displaying SOME images on webpage
I am creating an app which is having categories of workers. So I hv created model for getting worker data and using that data I am displaying it on webpage. but when I want to display worker data of specific category Django showing some images on page, NOT ALL. here is my models.py: settings.py: urls.py: views.py : In views.py I have created to funtions (display()-It is used for displaying all worker data and its displaying all images also. display.html: for showing all worker data on a page Here is the one data along with image (output of display.html) Now coming to point as I said above that django is not displaying some images on page for specific category(checkout views.py in which category is Painter()) here is Painter.html: Here is the output of Painter.html: Notice that on this page the card which is not showing Image works fine on DISPLAY.HTML but not on PAINTER.HTML NOTE : I used ({{i.myfile}}) in painter.html because of that it is showing some images and not showing other image. In display.html I have used {{dest.myfile.url}} which works fine there and shows all images. But when i used {{i.myfile.url}} in painter.html. Its not showing any image at … -
I want to display just the years and not the dates and months using ajax in django
I want to display just the years and not the dates and months using ajax in django. Example: My code output1 displays in the format of a calendar. But I want to display as output2 containing just the years. output1: outpu2: My code are as follows: click.js $(document).ready(function(){ console.log("READY"); $("#datepicker").datepicker({ format: " YYYY", viewMode: "years", minViewMode: "years" }); }); layoutstyle.html <script src="{% static ' https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' %}"></script> <script src="{% static 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js' %}"></script> <link href="{% static 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css' %}" rel="stylesheet"/> <script src="{% static 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js' %}"></script> <link href="{% static 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' %}" rel="stylesheet"/> <script src="{% static 'websitejs/click.js' %}"></script> <input type="text" id="datepicker" /> -
How to Seed add data in database in Django
I'm been trying to save data in database using seeder in Django. I want to add some data of my table usertypes and I think seeder is the only way to add it. The problem is how can I execute my seed.py file and save bunch of data into usertype table in database. Is there any trick or idea about this? seed.py from django_seed import Seed seeder = Seed.seeder() from .models import usertypes_tbl types = ["Super User", "Admin", "Customer"] descriptions = ["Super User", "Admin", "Customer"] status1 = ["Super User", "Admin", "Customer"] seeder.add_entity(user_type, types) seeder.add_entity(description, descriptions) seeder.add_entity(status, status1) inserted_pks = seeder.execute() python manage.py seed app/seed.py -
Django problem : How to extract data from a web
if i have a website: https://geodata.gov.hk/gs/api/v1.0.0/locationSearch?q=St.+Clare%27s+Primary+School which will show [{"addressZH":"","nameZH":"聖嘉勒小學","x":832498,"y":816065,"nameEN":"St. Clare's Primary School","addressEN":""}] How can I extract the text from the website using Django? i.e. given https://geodata.gov.hk/gs/api/v1.0.0/locationSearch?q=St.+Clare%27s+Primary+School Then,i need to get x=832498, y=816065 and use them in my program -
Internal Server Error:/admin/login/ DoesNotExist at /admin/login Site matching query does not exist`
Below are my setting files. I have them split into base.py (used for development and production), production (used for just production) and development (used for just development). After completing Coreys Blog series and a Udemy Ecommerce series, I have tried to merge the two together. On https://www.rossecommerce.com/, I am getting the error Internal Server Error:/admin/login/ DoesNotExist at /admin/login Site matching query does not exist. I have tried disabling 'django.contrib.sites' and changing SITE_ID to 2 (it was 1). I tried to look at the information in django_site, but could not figure out how to do it. Note - secret keys and email addresses have been modified, to prevent confidential info being leaked init.py from .base import * # from .local2 import * from .production import * base.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = "6a28569690e44af0de19f3eb6b3cb36cb448b7d31f881cde" DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', # third party 'storages', 'crispy_forms', 'mptt', #our apps 'blog.apps.BlogConfig', 'accounts', 'addresses', 'analytics', 'billing', 'carts', 'categorytree', 'discounts', 'marketing', 'orders', 'products', 'search', 'tags', 'properties', 'floppyforms', 'photologue', 'sortedm2m', 'photologue_custom', 'taggit', ] SITE_ID = 2 #SITE_ID = 'http://localhost:8000/' AUTH_USER_MODEL = 'accounts.User' #changes the built-in user model to ours FORCE_SESSION_TO_ONE = False FORCE_INACTIVE_USER_ENDSESSION= False … -
Django allauth, how to fetch email from all auth user model
I had been doing a lot of research of how to fetch email field in django allauth user model but I don't have any answer so i am turning to you please help me out i am stuck. In views.py i tried to fetch email from django allauth as per my understanding but don't know how to do it...!!! # Settings.py ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 300 # Models.py class OrderItem(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE # Views.py order = Order.objects.get(user=self.request.user, ordered=False) cust_mail = order.user.email As you can see in the image that email is registered and entred in database I am stuck at a point where i dont know how to fetch it back, I really hope you guys can help me out!!!enter code here -
How do I change a field value in Django form based on input?
Let's say I have a form with 3 fields - Book, Title, Author. The user could manually enter the title and the author, but he can also choose a book from the Book field. When a book 'some_title(some_author)' is chosen, I want the Title and Author fields to automatically update to 'some_title' and 'some_author'. Can I do this with only Django/HTML or do I need something else like Javascript? How? I don't know anything about JS, sorry if this is basic stuff.