Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert list to multiple Q objects?
Taking an example from Django 3.2 documentation, I need to use an argument like this for .filter: Q(question__startswith='Who') | Q(question__startswith='What') In my case need to convert each of the user's selections, which I'm getting in views.py via request.META['QUERY_STRING'], into it's own Q() object. If I tried to create Q objects from that list of parameters, it would not work, because the | would be evaluated. This seems like it must be a solved a problem, but I haven't had luck yet finding the answer. Thanks for any advice. -
How to match any url contains a certain string (such as .jsp) in Django?
I'd like to soft reject any path that contains a string, such as .jsp in the Django 3. Here is my url.py: from django.urls import re_path from django.views.generic import TemplateView re_path( r"^.*\.jsp\??.*$", TemplateView.as_view(template_name="404.txt", content_type="text/plain"), ), The above path pattern can match an ordinary string like /whatever.jsp, but cannot match the following probing string. How to improve my re_path pattern to match this? Thanks! /content/..%3B/crx/packmgr/list.jsp%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0Aa.css?_dc=1615863080856&_charset_=utf-8&includeVersions=true -
React i18next fails to load translation.json as json
React i18next fails to load translation.json as json. everything is functioning well before I use the build folder I'm using React / Django. i18n.js : import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; // don't want to use this? // have a look at the Quick start guide // for passing in lng and translations on init const Languages = ['ar', 'en', 'fr'] i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) // passes i18n down to react-i18next .init({ lng: 'en', react: { useSuspense: true, }, // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) supported: ["en", "fr", "ar"], fallbackLng: "en", detection: { order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'], caches: ['cookie'], }, debug: true, whitelist: Languages, interpolation: { escapeValue: false, // not needed for react as it escapes by default }, nsSeperator: false, keySeperator: false, backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', }, }); export default i18n; index.js : import React, {Suspense} from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'bootstrap/dist/css/bootstrap.min.css'; import './index.css'; import './i18n'; ReactDOM.render( <React.StrictMode> <Suspense fallback={(<div className='index__loading'><h2>Loading...</h2></div>)}> <App /> </Suspense>, </React.StrictMode>, document.getElementById('root') ); here's where I switch … -
Django: unknown database name
I am trying to change the database in django from sqlite3 to mysql DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER':'myusername', 'PASSWORD':'mypassword', 'HOST':'127.0.0.1', 'PORT':'3306', } } and after trying to run my server i get this error System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 244, in ensure_connection self.connect() File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 244, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\__init__.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb.OperationalError: (1049, "Unknown database 'django'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 576, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() … -
How can I protect some endpoints from user accessing it directly in django?
There is a URL with an endpoint named as 'otp/', I don't want the user to access this endpoint directly, I want to have them as directed by my code (whenever needed) How can I do it? here is my code class OTPView(View): def get(self, request, *args, **kwargs): otp_form = OTP_Form() return render(request, 'otp.html', {'otp_form': otp_form}) def post(self, request, *args, **kwargs): try: otp = request.session.get('otp') first_name = request.session.get('first_name') last_name = request.session.get('last_name') password = request.session.get('password') phone = request.session.get('phone') otp_form = OTP_Form(request.POST) if otp_form.is_valid(): get_otp = otp_form.cleaned_data['otp'] if get_otp == otp: user = MyUser.objects.create_user( phone=phone, password=password, first_name=first_name, last_name=last_name) user.save() otp_entry = OTP.objects.create(user_id=user, otp=otp) otp_entry.save() delete_session(request) messages.success( request, 'Your account has been created') return redirect('login') else: messages.error(request, 'Incorrect OTP') return redirect('otp') else: messages.error(request, 'Please enter the OTP again') return redirect('otp') except: messages.error(request, 'Please try signing up again') return redirect('signup') urls.py path('otp/', OTPView.as_view(), name='otp'), I want this endpoint to be accessed by the user right after the user signup Please suggest me something -
Django Using ManyToMany instead of ForeignKey
In a specific Django app, I have a DB Model class A that is considered as the main class and many other models are connected to it weather through one to one relationship (like B) or one to many relationship (like C). So, the direct approach to implement such is: class A(Model): b = OneToOneField('B', on_delete=CASCADE) # other fields class B(Model): # some fields class C(Model): a = ForeignKey(A, on_delete=CASCADE) # other fields Now, when I want to create a new object of A, the sequence will be: create B object create A object and link the created B object to it create C object and link the created A object to it. This happens on a larger scale with a lot of models linked with model A. But I want to have all the relations seen in the A class so that when I want to create an object of A, I go to create all the related objects first after validating them regardless the relationship, then create new A object and link all those related objects to it. So, I did so: class A(Model): b = OneToOneField('B', on_delete=CASCADE) c = ManyToManyField('C') # as there is no OneToManyField class … -
Getting an error with app label 'admin' not installed
I am building a movie project with django, it is my first project so I am still new at this. When I run python manage.py makemigrations I get the following error: LookupError: No installed app with label 'admin'. I have included a few things to my settings.py, here's the additional stuff (not including the things already installed by requirement) #additional import django django.setup() from pathlib import Path #additional import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-b(tax)t-t&6uy$2=64s8=00^oj#&7o*oj7#x0eg10dsbf-=sqa' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] #additional MEDIA_URL = '/media/' #additional MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #additional from django.contrib import admin from django.urls import re_path # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #additional 'movie', ] ... Admin.py from django.contrib import admin from .models import Movie class MovieAdmin(admin.ModelAdmin): pass admin.site.register(Movie, MovieAdmin) Models.py: from django.db import models class Movie(models.Model): title = models.CharField('Title',max_length=255, unique=True) critics_consensus = models.TextField('Critics consensus', blank=True, null=True) average_grade = models.DecimalField('Average grade', max_digits=3, decimal_places=2, blank=True, null=True) poster = models.ImageField('Poster', blank=True, null=True) amount_reviews = models.PositiveIntegerField('Amount Reviews', blank=True, null=True) approval_percentage … -
How to create a Circular Counter Custom Field in Django?
I'm trying to solve this question as a hackerrank challenge but I'm stuck. Django: Circular Counter Custom Field In this challenge, your task is to implement a custom model field called CircularCounterField as a field to hold the provided CircularCounter class. A circular counter is an object that stores a value that is initially set to the given start value and can be incremented. After a given number of increments from the starting value (let's call this number cycle_len), the value is reset to the starting value. For example, if start=1 and cycle_len=2, then the initial value is 1. After the first increment, the value becomes 2. After the second increment, the value is reset to the start value, i.e. 1. Then, after the third increment, the value becomes 2, and after the fourth increment, it again becomes 1, and so on. CircularCounter class is a very simple class to store the state of a circular counter: class Circular Counter: def init(self, start, cycle_len, value=None): if not isinstance (start, int): raise ValueError("start must be int") if not isinstance (cycle_len, int) or cycle_len <= @: raise ValueError("cycle_len must be a positive integer") if value is not None: if not isinstance (value, … -
I am getting this error "HomeView.get() got multiple values for argument 'id'"
Hello I am creating an app, when I logged in, I want to open up the particular profile of that user (by using user.id), but I am getting this error, And I don't know the reason why? here is my code: class HomeView(LoginRequiredMixin, View): def get(request, id): login_url = 'login/' redirect_field_name = 'home/<int:id>' user = MyUser.objects.filter(id=id).first() return render(request, "home.html", {"first_name": user.first_name, "last_name": user.last_name}) class LoginView(View): def get(self, request, *args, **kwargs): loginform = UserLoginForm() return render(request, 'signin.html', {'loginform': loginform}) def post(self, request, *args, **kwargs): try: loginform = UserLoginForm(request.POST) if loginform.is_valid(): phone = loginform.cleaned_data['phone'] password = loginform.cleaned_data['password'] user = authenticate(phone=phone, password=password) if user is not None: login(request, user) return redirect('home', id=user.id) else: messages.error(request, "Invalid phone or password.") return redirect('login') else: messages.error(request, "Invalid phone or password.") return redirect('login') except: messages.error(request, "Please try again") return redirect('login') I am getting this error TypeError: HomeView.get() got multiple values for argument 'id' What is the problem with it -
Django, i18n, problems with translation after changing LANGUAGE_CODE
I have created a multilingual website, using Django i18n. But then I needed to change the default language (LANGUAGE_CODE) to one of those that were in the LANGUAGES. After that, when setting the language that was originally the default, the translation does not work correctly. The models are translated correctly, but the templates remain in the new default language. At the same time, one more language, which was originally in the LANGUAGES, but neither at the beginning nor now is the default language, there are no problems. -
Cannot connect to "@localhost". Access denied for user 'root'@'localhost' (using password: YES)
I try to connect mysql to django project Here my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': 3306, } } enter image description here -
No installed app with label scrapy-django
I have been following the documentation for scrapy-django, and have implemented all the steps required for the first part. I have got up to the django migrations for the file, and when I use: python manage.py makemigrations open_news I get the following error: No installed app with label 'open_news'. Here's my tree: . ├── example_project │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-310.pyc │ │ ├── settings.cpython-310.pyc │ │ └── urls.cpython-310.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── open_news │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── scraper │ │ ├── __init__.py │ │ ├── checkers.py │ │ ├── pipelines.py │ │ ├── settings.py │ │ └── spiders.py │ ├── tasks.py │ ├── tests.py │ └── views.py └── scrapy.cfg -
Is there any way to build a React App and leave env variables that can be dynamically populated?
I have a react app that is served via Django. I have multiple environments: staging and prod. These environments have different URLs that the API is exposed from. On building the React app I'm passing variable that tells the build which URL to use, but this gets to be a mess with the multiple environments and git. I end up having a git history filled with builds from other environemnts. These builds get passed to other branches when PRs are merged, then they create conflicts, etc. I want to have a single React build that will be able to tell which environment it is and update the API url accordingly: after being built! Is that possible? -
tempfile.tif: Cannot read TIFF header?
Here I am trying to convert a tiff image into jpg but I am getting this error tempfile.tif: Cannot read TIFF header. rgb_img = img.convert('RGB') File "..../PIL/Image.py", line 915, in convert self.load() File ".../PIL/TiffImagePlugin.py", line 1079, in load return self._load_libtiff() File ".../PIL/TiffImagePlugin.py", line 1171, in _load_libtiff raise IOError(err) IOError: -2 this is the function from PIL import Image def convert_to_jpg(tiff_image): img = Image.open(tiff_img) rgb_img = img.convert('RGB') rgb_img.save('jpg_file.jpg') return rgb_img -
Why Django doesn't see my json file at base dir?
My structure of files here I'm beginner at Django. And I read in "2 Scoops of Django", that store database password etc. at settings.py it's bad. So I decided, store password etc. at json file, then I expanded settings.py by this code: import json import os from django.core.exceptions import ImproperlyConfigured with open(os.path.join(BASE_DIR, 'secrets.json')) as secrets_file: secrets = json.load(secrets_file) def get_secret(setting, secrets=secrets): """Get secret setting or fail with ImproperlyConfigured""" try: return secrets[setting] except KeyError: raise ImproperlyConfigured("Set the {} setting".format(setting)) And I got the following code: from pathlib import Path import json import os from django.core.exceptions import ImproperlyConfigured BASE_DIR = Path(__file__).resolve().parent.parent with open(os.path.join(BASE_DIR, 'settings_for_db.json')) as secrets_file: secrets = json.load(secrets_file) def get_secret(setting, secrets=secrets): """Get secret setting or fail with ImproperlyConfigured""" try: return secrets[setting] except KeyError: raise ImproperlyConfigured("Set the {} setting".format(setting)) SECRET_KEY = get_secret("SECRET_KEY") ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', "NAME": get_secret("NAME"), "USER": get_secret("USER"), "PASSWORD": get_secret("PASSWORD"), "HOST": get_secret("HOST"), "PORT": get_secret("PORT") } } WHEN I entered the command from Django documentation: py manage.py check --database default I've got this error: Traceback (most recent call last): File "C:\Projects\Django-project\my_first_site\manage.py", line 22, in <module> main() File "C:\Projects\Django-project\my_first_site\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Projects\Django-project\venv\lib\site- packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Projects\Django-project\venv\lib\site- packages\django\core\management\__init__.py", line 386, in … -
How can I display both active and inactive investments on my dashboard using django?
My template only shows active investments, despite the fact that I wish to show both active and inactive investments. It does not appear on the template when I set is_active to false. Anyone know what I'm doing wrong? Attached is the screenshot of my dashboard where I intend to show both active and inactive investment. This image displays active investment when created. This no investment when I change is_active = False which is what I don't want. I want in_active=False investments to also display on the dashboard. Views def create_investment_view(request): if request.method == 'POST': basic_investment_form = BasicInvestmentForm(request.POST) if basic_investment_form.is_valid(): investment = basic_investment_form.save() investment.basic_interest = investment.basic_deposit_amount * 365 * 0.02/2 investment.basic_investment_return = investment.basic_deposit_amount + investment.basic_interest investment.basic_investment_return += investment.basic_deposit_amount investment.plan = "Basic - Daily 2% for 180 Days" investment.due_date = datetime.now() + timedelta(seconds=5) investment.is_active = True investment.save() print(investment.basic_interest) print(investment.basic_investment_return) print(investment.basic_deposit_amount) messages.success(request, 'your basic investment of {} is successfull '.format(investment.basic_deposit_amount)) else: messages.success(request, 'your investment is not successfull! Try again.') else: basic_investment_form = BasicInvestmentForm() context = {'basic_investment_form': basic_investment_form} return render(request, 'create-basic-investment.html', context) def list_investments(request): investments = Investment.objects.all() atleast_one_active=False atleast_one_inactive=False for investment in investments: if investment.is_active: atleast_one_active=True else: atleast_one_inactive=True context = { 'investments': investments, } return render(request, 'list-investments.html', context) Model class Investment(models.Model): PLAN_CHOICES = ( … -
Django cannot render model attributes by slug to the template
I have set a model including some attributes and can get the model by a slug in views.py. However, I can't render its attributes into the template. Did I miss something? Model.py class article(models.Model): title = models.CharField(max_length=200) content = RichTextUploadingField() slug = models.SlugField(unique=True, max_length=200) def __str__(self): return self.title Views.py def post_details(request, slug): details = get_object_or_404(article, slug=slug) context = { details: 'details' } return render(request, 'post_details.html', context) Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('<slug:slug>/', views.post_details, name='post_details') ] I have set a URL to get the article model's data by slug in index.html <h4 class="title"><a href="{% url 'post_details' article.slug %}">{{ article.title }}</a></h4> post_details.html <h2>{{ details.slug }}</h2> I can access this template by slug but can't get any attributes by using the 'details' tag -
Using Django-tables2 with class-based view and non-default database throws "NameError: name 'TypeError' is not defined"
I am trying to set up django-tables2 and followed the recommendations in their docs. However, if I call the view, it throws the error File "/home/ubuntu/mysite/mysite_venv/lib/python3.8/site-packages/asgiref/local.py", line 94, in __del__ NameError: name 'TypeError' is not defined Note: From what I could gather, this error message unfortunately also occurs in other contexts as the most upvoted thread deals with an Apache config problem. I would be glad to adjust the title for clarity once the issue has been grasped concisely. Django-tables2 should access (read-only) a legacy MySQL database which I added behind the default SQLite database in settings.py (see further down). My polls/models.py: from django.db import models import datetime from django.db import models from django.utils import timezone ... class Dashboard(models.Model): host = models.CharField(db_column='Host', max_length=255, blank=True, null=True) title = models.TextField(db_column='Title', blank=True, null=True) operation = models.CharField(db_column='Operation', max_length=255, blank=True, null=True) performedat = models.DateTimeField(db_column='PerformedAt', blank=True, null=True) class Meta: managed = False db_table = 'dashboard' In case it's necessary, the underlying table in MySQL looks like this: c.execute('''CREATE TABLE dashboard( id INT PRIMARY KEY AUTO_INCREMENT, Host VARCHAR(255), Title TEXT, Operation VARCHAR(255), PerformedAt DATETIME);''') My polls/views.py: from django.shortcuts import render from django.views.generic.list import ListView from .models import Dashboard from django.http import HttpResponse class DashboardListView(ListView): model = Dashboard … -
Unable to display multiple readonly fields in Django admin, only one will display
I'm trying to display two new rows (fields) in the "posts" section of django admin which are read-only fields that take data from two other database columns. My code works, but it will not create two new fields, it only displays one. I'm relatively new to Django and python, and I'm struggling to figure out how to do this. I spent too much time trying different things only to have no success. In the context of my test, I want to see two readonly fields called "New row 1" and "New row 2", which take the data from two database columns called "est_completion_time" and "downtime". I can only see "New row 2" on the output. This is my code in admin.py: @admin.register(Post) class PostAdmin(admin.ModelAdmin): form = JBForm exclude = ['est_completion_time'] # hide this database column exclude = ['downtime'] # hide this database column readonly_fields = ['placeholder_1'] # display this one readonly_fields = ['placeholder_2'] # display this one @admin.display(description="New row 1") def placeholder_1(self, obj): return obj.est_completion_time # a new readonly field which should display contents of 'est_completion_time' column @admin.display(description='New row 2') def placeholder_2(self, obj): return obj.downtime # a new readonly field which should display contents of 'downtime' column After reading through … -
Django Filter specific user's salary within giving date range
I have Two models : class MonthSalary(models.Model): month = models.DateField(null=True) def __str__(self): return str(self.month.year) + '/' + str(self.month.month) class SalaryPerMonth(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) salary_month = models.ForeignKey(MonthSalary, null=True, on_delete=models.CASCADE) main_salary_per_month = models.PositiveIntegerField(default=0, null=True) net_salary_per_month = models.PositiveIntegerField(default=0, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=["user", "salary_month"], name="all_keys_unique_together")] def __str__(self): return str(self.user.employeedetail.empcode) + ' ' + str(self.net_salary_per_month) + ' LYD ' + str( self.salary_month) In Views I can query all user salaries with : user = request.user salary_per_month = SalaryPerMonth.objects.filter(user=user) In MonthSalary model I added a bunch of months\years not in order Ex "2022-2,2022-4,2022-1,2021-4" when I filter user's salary by ordering the date "related salary_month field" like so : salary_per_month = SalaryPerMonth.objects.filter(user=user).order_by('salary_month') It's not in order. Q1 = How how filter by Year ? Q2 = How to order by month ? -
how to make subdomains in django?
I want to make a panel which has two main urls by the name user and admin and also each of the "user" and "admin" urls have other urls. for example -> " site.com/panel/user/id/profile " OR " site.com/panel/admin/id/addItem " . but idk how can I make this main urls and subdomain urls :) -> ecoverde/urls.py : from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), path('panel/', include('panel.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ecoverde/panel/urls.py ((this is where i want to add two main urls and other sub urls) : from .views import userPanel, Compare, saves from django.urls import path urlpatterns = [ #main urls that i want path('user dashboard/<str:pk>', userPanel, name='userPanel'), path('admin dashboard/<str:pk>', adminPanel, name='adminPanel'), #sub urls that i want path('compare', Compare, name='compare'), path('saves', saves, name='saves'), #... ] -
Django, unable to locate static files when using Dropbox
I'm new to Django and I'm trying to understand the static and media files. I'm following this practical example which uses AWS As I don't have AWS but Dropbox, I used django-storages but with Dropbox instead of AWS. It works fine while storing the files locally. However, when pointing to Dropbox, I'm able to upload them but when loading the django app it fails as it does not find the icons. Dropbox folder structure is as follows: Dropbox Aplicaciones ptstg bulma.min.css admin img icon1.jpg ... fonts ... css ... js ... The value of my variables in SETTINGS are: DROPBOX_ROOT_PATH = '/Aplicaciones/ptstg' DROPBOX_LOCATION = 'static' STATIC_FILES = 'staticfiles' STATIC_URL = f'{DROPBOX_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' I'm expecting to store and access the static and image files from the root folder /Aplicaciones/ptstg. And it does. However, it uploads all files into a folder called 'admin' with the icons inside img folder (same img folder name is used when locally, and it works). When I try to reload my site, it fails and it complain: Exception Value: ApiError('dea1242d617d4ef9a8b9afe5ab06fd97', GetTemporaryLinkError('path', LookupError('not_found', None))) And it points to the following file: Error during template rendering in template /usr/src/app/upload/templates/upload.html, error at line 8 1 … -
django admin error target lists can have at most 1664 entries
I want to use from django admin to add some data and check them in my project but i have a strange error please help me to understand what is this error and how can I solve it. my model: class Task(BaseModels.AbstractField): STATUS_CHOICES = ( ('شروع نشده', 'شروع نشده'), ('درحال انجام', 'درحال انجام'), ('خاتمه یافته', 'خاتمه یافته'), ('لغو', 'لغو'), ('ارجاع به آینده', 'ارجاع به آینده'), ('ارجاع به دیگری', 'ارجاع به دیگری'), ) PRIORITY_STATUS = ( ('معمولی', 'معمولی'), ('فوری', 'فوری'), ('آنی', 'آنی'), ) reference = models.ForeignKey('self', on_delete=models.PROTECT, related_name='children',verbose_name='تکلیف مرجع') project = models.ForeignKey('TaskManager.Project', on_delete=models.PROTECT, related_name='tasks', verbose_name='پروژه') category = models.ForeignKey('TaskManager.TaskCategory', on_delete=models.PROTECT, related_name='tasks', verbose_name='دسته بندی تکلیف') content = models.TextField(verbose_name='توضیحات') expert = models.ForeignKey('Identity.User', on_delete=models.PROTECT, related_name='expert_tasks', verbose_name='کارشناس') expert_head = models.ForeignKey('Identity.User', on_delete=models.PROTECT, related_name='expert_head_tasks', verbose_name='کارشناس مسئول') priority = models.CharField(max_length=10, choices=PRIORITY_STATUS, default='معمولی', verbose_name='اولویت') estimated_time = models.IntegerField(verbose_name='زمان مورد نیاز برای انجام(ساعت)') estimated_date = jmodels.jDateField(verbose_name='تاریخ تخمینی اتمام') deadline_date = jmodels.jDateField(default=None, verbose_name='مهلت تحویل') close_date = jmodels.jDateField(verbose_name='تاریخ اختتام') close_content = models.TextField(verbose_name='توضیحات اختتام') status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='شروع نشده', verbose_name='وضعیت') other_expert = models.ForeignKey('Identity.User', null=True, on_delete=models.PROTECT, related_name='other_expert_tasks', verbose_name='کارشناس ارجاع داده شده') meetings = models.ManyToManyField('TaskManager.Meeting', blank=True, through='TaskManager.Task2Meeting', verbose_name='جلسات') my admin: from django.contrib import admin from .models import Meeting, Task class TasksAdmin(admin.ModelAdmin): list_display = ('category', 'expert', 'content', 'priority', 'estimated_time', 'estimated_date', 'deadline_date', 'status') and my error: target lists … -
Form not being made despite having correct format
I am new to django and I am trying to load the 'form' variable into the html page here's the views.py function def show(request): showall = Products.objects.all() print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) below is the insert page where the form <body> <center> <h1>Edit details of Clothes</h1> </center> <center> <form method="POST"> {% csrf_token %} {{data}} <button class="btn btn-success"><a href="{% url 'polls:show' %}" style="color: red;">Go To Home</a></button> </form> </center> </body> the form itself isnt coming,what could the problem be? -
Django 4.0 pyinstaller 5.1 failed to run runserver command throws an error
Trying to package a django 4.0 project to exe using pyinstaller 5.1 and python 3.9 and it was successfully but i ran into a problem that when i run it in cmd with ./manage.exe runserver i get this error Am currently working in a virtual environment and am using windows 10 operating system The project is a basic test project were am using a single app, a few satic files and sqlite 3 as my default database PyInstaller\hooks\rthooks\pyi_rth_django.py", line 69, in _restart_with_reloader return _old_restart_with_reloader(*args) File "django\utils\autoreload.py", line 263, in restart_with_reloader args = get_child_arguments() File "django\utils\autoreload.py", line 250, in get_child_arguments raise RuntimeError('Script %s does not exist.' % py_script) RuntimeError: Script runserver does not exist. [7892] Failed to execute script 'manage' due to unhandled exception! This is my .spec file # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['manage.py'], pathex=[], binaries=[], datas=[], hiddenimports=[ 'webapp.urls', 'webapp.apps' ], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE( pyz, a.scripts, [], exclude_binaries=True, name='manage', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, ) coll = COLLECT( exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='manage', ) This is urls.py from django.contrib …