Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to send Django and Celery logs to CloudWatch
I use Django and Celery. I can send django logs to aws cloudwhatc. But I can't send Celery's logs. I'm waiting for your help. I use this for log. https://pypi.org/project/watchtower/ -
Configure NGINX with custom URL (server_ip/custom_name)
I'm trying to configure my nginx to access my site in this pattern IP_ADDRESS/folder_name Example 127.0.0.1/testapp. Currently i adjusted my nginx to this configuration location /test/* { proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8082; break; } proxy_connect_timeout 600; proxy_read_timeout 600; alias /var/www/html/test/; } but whenever i try to access my site 127.0.0.1/testapp. i always get 404 error. and upon checking my nginx error log. I get the following 2020/10/28 03:34:01 [error] 8711#8711: *5 open() "/usr/share/nginx/html/test" failed (2: No such file or directory), client: xxxxx, server: localhost, request: "GET /test Btw i'm configuring django site. Thanks! -
Unit testing for Django login page
I'm currently trying to write unit tests for the built-in django login page, and I keep getting this error. ERROR: test_login_success (User.tests.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\---------------\User\tests.py", line 74, in test_login_success self.assertTrue(response.data['authenticated']) AttributeError: 'TemplateResponse' object has no attribute 'data' Codes: no view function because I used the Django built-in login page test.py def test_login_success(self): testuser = User.objects.create_user(username = 'howdycowboy', password= 'Testing123' ) response=self.client.post(self.login_url,{'username':'howdycowboy', 'password': 'Testing123'},format='text/html') #self.assertEqual(response.status_code ,302) self.assertTrue(response.data['authenticated']) #HTML code {% extends 'User/base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} I've also tried self.assertEqual(response.status_code ,302) it redirects once it logs in, but for some reason the response.statuscode is 200. % (response.status_code, status_code) AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302) -
How to take data from model and display on the product page?
I am developing an ecommerce website with django, I can not show on the product page (product_detail.html) the dates from Product_details model, from other models I can display dates, for example, from the Product_image model and from Category model I already take dates and display without any problems. It seems that I did all steps right, but I can not display the dates. Please help me. urls.py: from django.urls import path from . import views from .views import ProductListView from django.conf.urls.static import static urlpatterns = [ # path('', views.home, name='amd-home'), path('', ProductListView.as_view(), name='amd-home'), # path('', views.home_page, name='amd-home'), # path('product/<int:pk>/', ProductDetailView.as_view(), name='product-detail'), path('product/<int:id>/', views.product_detail, name='product-detail'), path('about/', views.about, name='amd-about'), ] models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=200) parent_id = models.IntegerField(default=0) description = models.TextField() image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Brand(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=400) image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Product(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='uploads/', blank=True, null=True) sku = models.CharField(max_length=200) price = models.IntegerField(default=0) price_old = models.IntegerField(default=0) description = models.TextField() status = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return f'{self.title}, {self.description}' class … -
Django Admin Inline & TabularInline – Appending ordered text fields with a sql database structure
I have read and have tried some of the examples in https://docs.djangoproject.com/en/3.1/ref/contrib/admin/ in regard to appending additional objects. Essentially what I want is a Question to have multiple Answers and within the Admin Question area with the ability to get a [+] button to add additional questions. I want to get that working first; but down the road I also want to do the following: Ordered list of Answers: that is, ranked ordering to the questions. Ability to repeat Answers in the ordered list In models.py file from django.db import models class Question(models.Model): name = models.CharField(max_length=50) question = models.CharField(max_length=50) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) class Answer(models.Model): answer = models.CharField(max_length=50) In admin.py file: From .models import ( Question, Answer, ) class AnswerTabularinline(admin.TabularInline): model=Answer class QuestinAdmin(admin.ModelAdmin): inlines = [AnswerTabularinline] class Meta: model = Question admin.site.register(Question, QuestinAdmin) admin.site.register(Answer) This is a fairly standard implementation of tabular inline; however, I am linking it to a SQL database and I have added the following tables: CREATE TABLE "ModME_question" ( "id" INTEGER NOT NULL UNIQUE, "name" TEXT, "text" TEXT, "answer" INTEGER, FOREIGN KEY("answer") REFERENCES "ModMe_Answer"("id"), PRIMARY KEY("id" AUTOINCREMENT) ); CREATE TABLE "ModMe_Answer" ( "id" INTEGER NOT NULL UNIQUE, "text" TEXT, PRIMARY KEY("id" AUTOINCREMENT) ); -
How i can use a CreateView with the same model Post to create a Post(Parent) with comments Post(Children)?
Im trying to create a view to use it in two cases: Create a Post Create a Post with comment. Using the same model and view (Im open to use two views, but im looking for the Pythonic/Django way to do it). I dont know to do it with CBV -> CreateView Model: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=500) image = models.ImageField(upload_to="user/post", blank=True) video = models.URLField(blank=True) comment = models.ForeignKey("self", on_delete=models.CASCADE, default=None, blank=True, null=True, related_name='comments') date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) featured = models.BooleanField(default=False) View: class PostCreateView(LoginRequiredMixin, CreateView): form_class = PostForm template_name = "core/post_create.html" def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.date_created = timezone.now() obj.save() return redirect("feed") Source code on Github