Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to insert new string to DB by button Django
How to insert new string to DB by button Django and take id new record <a href="{% url "main:create_bd_line" %}"><button type="button" class="btn btn-secondary">Начать</button></a> def create_bd_line(request): user_group = request.user.groups.values_list() university = user_group[0][1] -
How to automatically add '/static/' in every url that loading files
I want to use static without {% load static %}, just a raw html. How can I automatically add 'static' in every url, that loading any file. For example, site requesting file in "/js/script.js", but I want to get "/static/js/script.js" url. How can I do this?Shall I use middleware or it would be some easiest way? Thanks! -
display commas instead of periods
in my sql table I have decimal data with dot as a separator but the display in my page is done with commas I would like to display them with dot in my settings i have this LANGUAGE_CODE = "fr-fr" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True my models class VilleStation(models.Model): nomVille = models.CharField(max_length=255) adresse = models.CharField(max_length=255) cp = models.CharField(max_length=5) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) in the templates i have this {% for c in object_list %} {{c.nomVille}} {{c.adresse}} {{c.cp}} {{c.latitude}} {{c.longitude}} {% endfor %} thank -
Django fullstack developer
What do I need to learn in order to connect the frontend to a ready-made backend on a django? I tried googling, but after a few inaccurate answers I decided to ask the question here -
Performing Boolean Logic in views and template
am having two set of challenges. First, I have a model with field submit as Boolean field. I use model form and render it in template. There are two options as Boolean select i.e. 'Yes' and 'No' option for user to select whether he want to save the form or not. I want if this user select 'Yes', the form should be save. else if he select 'No', the form should not be save. I have exhausted all the logics that i thought could work but cannot achieve this. Below is the views views.py def submit(request): if request.method =='POST': form = submitForm(request.POST) form.instance.user = request.user sub = form.save() if sub.sumit ==True: if sub: messages.info(request, 'You have submitted you form successfully') return redirect('home') messages.info(request, 'Continue editing your data') return render(request, 'portal/home/submit.html') form =submitForm() context = { 'form':form, # 'sub':sub } return render(request, 'portal/home/submit.html', context) my second question is in this view. since I could not achieve what i wanted in the above form, i just query it in this user_info so that if user save the submit as 'Yes' or 'No' some certain buttons in template should or should not show. below is how i try but not exactly what i … -
ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, environment variable DJANGO_SETTINGS_MODULE
I'am getting this error: I cannot see the Filters botton in Filter back ends with URL query parameters. raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This my api_views.py file: from rest_framework.generics import ListAPIView from django_filters.rest_framework import DjangoFilterBackend from store.serializers import ProductSerializer from store.models import Product class ProductList(ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('id',) Here is my wsgi.py file: import os import sys from django.core.wsgi import get_wsgi_application path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if path not in sys.path: sys.path.append(path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'store', ] REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } and the manage.py code: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Can anyone seem to understand the … -
How can I redirect the user to another template after a search?
I have a search form where the models an user searches are displayed bellow the search form but I want it to be shown in another page. I tried looking for a way to redirect the user to another url when the search is done and display the filtered data there but I wasn't able to do that. model: class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) date_posted = models.DateTimeField(default=timezone.now) ... view: def FilterView(request): qs = Product.objects.all() title_contains_query = request.GET.get('title_contains') title_or_author_query = request.GET.get('title_or_author') ... if is_valid_queryparam(title_contains_query): qs = qs.filter(title__icontains=title_contains_query) elif is_valid_queryparam(title_or_author_query): qs = qs.filter(Q(title__icontains=title_or_author_query) | Q(author__username__icontains=title_or_author_query)).distinct() ... context = { 'queryset': qs, ... } return render(request, 'main/form.html', context) template: <form method="GET"> <div> <input type="search" name="title_contains" placeholder="Title contains"> <span><div><i class="fa fa-search"></i></div></span> </div> <div> <input type="search" name="title_or_author" placeholder="Title or author"> <span> <div><i class="fa fa-search"></i></div> </span> </div> ... <button type="submit">Search</button> </form> <div> <ul> {% for product in queryset %} <li> {{ product.title }} <span>Author: {{ product.author.name }}</span> </li> <hr /> {% endfor %} </ul> </div> -
Django Conditional to remove css class if not on main url
Im wondering if someone could help me figure this out; Working on a web app using the django framework and for my navbar, I have a css class that makes it transparent on the main page. This of course worked on a static website, but does not in django. How can i write an if statement to only apply this class on a specific url - the home page? {% load static %} <header id="home"> <!-- Navbar --> <nav id="navbar" class="main-page"> <a href="{% url 'home' %}"><img src="{% static 'images/farmec-logo-2.png' %}" alt="" id="logo"></a> <ul> <li><a href="{% url 'home' %}" class="current">Home</a></li> <li><a href="{% url 'teams' %}">About</a></li> <li><a href="blog.html">Blog</a></li> <li><a href="suppliers.html">Suppliers</a></li> <li><a href="parts.html">Spare Parts</a></li> </ul> </nav> </header> #navbar { display: flex; justify-content: space-between; padding-top: 1rem; position: absolute; background: transparent; width: 100vw; z-index: 1; background: var(--dark-color); transition: 0.5s ease-in; } #navbar.main-page { background: transparent; } -
Celery (worker) getting tasks with producer (Django) shutdown
I am using Celery as a worker for Django API calls. My current stack is: Producer: Django app Message Broker: Redis server Consumer: Celery app The issue is: If my Django app is shutdown, and I have the redis-server running, and start the worker with: python3 -m celery -A b3 worker -l info It starts getting tasks, which doesn't make much sense since my producer isn't producing any tasks. Celery getting tasks My tasks.py: @shared_task() def fetch_stock_task(company_code: str): ... -
djangocms Currently installed Django version 3.2.15 differs from the declared 3.1
I am running an AWS Bitnami Django instance. Django 3.2.15 installed by default. Django documentation recommends version django 3.2 so all is good there. Once installed I am having a hard time getting djangocms to create a new project. I keep getting dependency errors when I issue the command djangocms -f -p . projectname I received the following: Currently installed Django version 3.2.15 differs from the declared 3.1. Please check the given `--django-version` installer argument, your virtualenv configuration and any package forcing a different Django version -
In django email autosave Doesn't work(all files in git)
i have created an study project, the aim of it to create website where you can recover your password, but after registration password doesn't save. https://github.com/ErikArabyan/Authentication I've try to find mistakes, but i couldn't, help me please. -
Django-filters do not work. Data do not changes
Can you help me ? Request is sending, but data returning the same. My url after hitting submit button changes to get request, but my list do not changes. logs.html - https://prnt.sc/kuIjkitL_PF7 https://prnt.sc/SLurDBigzwkQ views.py - https://prnt.sc/uxyvsAQrQb7C https://prnt.sc/UneurdsO-gsU filters.py - https://prnt.sc/D-zMk5MV3MQq -
in Django sql table with dots as a decimal separator but in the admin are displayed with commas
I have this error in Django error during template rendering .... argument must be int or float I wonder if it's because in my sql table I have columns with coordinates that have dots as a separator but when I look at the display in the admin these coordinates are displayed with commas my models : class VilleStation(models.Model): nomVille = models.CharField(max_length=255) adresse = models.CharField(max_length=255) cp = models.CharField(max_length=5) latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.nomVille in my settings LANGUAGE_CODE = "fr-fr" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True DECIMAL_SEPARATOR = True thank -
TypeError: '>' not supported between instances of 'CombinedExpression' and 'int'
I got this product model: class Product(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2, default=0) price = models.DecimalField(max_digits=10, decimal_places=2, default=0) @property def value(self): return F('quantity') * F('price') when I call .value on product instance I got in return: product.value // returns 14 but when I check condition: for product in Product.objects.all(): while (product.value > 0): ... I got this error: TypeError: '>' not supported between instances of 'CombinedExpression' and 'int' I have not found an existing question about this problem. How to solve it? -
ImportError: Couldn't import Django. in my vscode terminal it's strange
(myenv) baeg-ingeol@baeg-ingeol-ui-MacBookAir mysite % python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (myenv) baeg-ingeol@baeg-ingeol-ui-MacBookAir mysite % pip list when i run my manage.py, compiler say error but i already pip django,, and i tryed check my django version in terminal and install django. It comes out in the code below. please help... (myenv) baeg-ingeol@baeg-ingeol-ui-MacBookAir practice % python -m django --version /usr/local/bin/python: No module named django (myenv) baeg-ingeol@baeg-ingeol-ui-MacBookAir practice % pip install django Requirement already satisfied: django in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (4.1.3) Requirement already satisfied: asgiref<4,>=3.5.2 in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (from django) (0.4.3) run manage.py, solve this problem -
Why my app is not find (ModuleNotFoundError: No module named '<app_name>')?
I'm trying to create an API for my blog with django rest framwork and when I execute the following command : python manage.py makemigrations posts This Error appears : Traceback (most recent call last): File "/Users/xxx/dev/api/blog/blog/../manage.py", line 22, in <module> main() File "/Users/xxx/dev/api/blog/blog/../manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/xxx/dev/api/blog/env/lib/python3.9/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'posts' settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "posts.apps.PostsConfig", ] . ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-39.pyc │ ├── settings.cpython-39.pyc │ └── urls.cpython-39.pyc ├── asgi.py ├── posts │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── … -
I get 502 Bad Gateway nginx/1.22.0 (Ubuntu) when deploying django app to linode with gunicorn and nginx
I'm deploying a django app to linode with gunicorn and nginx. I have followed a few different tutorials, but for the setting up of gunicorn and nginx I followed this, which took me to the end with no errors, but at the end I got 502 Bad Gateway error from nginx when trying to open the url directly on my browser. The error.log I get when refreshing the page is the following: tail -f /var/log/nginx/error.log 2022/11/20 11:24:33 [crit] 4949#4949: *5 connect() to unix:/home/djangouser/djangoproject/djangoproject.sock failed (13: Permission denied) while connecting to upstream, client: 181.43.95.34, server: 555.555.55.555, request: "GET / HTTP/1.1", upstream: "http://unix:/home/djangouser/djangoproject/djangoproject.sock:/", host: "555.555.55.555" (The IP, user and project names have been changed, not sure if this is unsafe, but just in case) The relevant settings are as follows: ufw status on server: To Action From -- ------ ---- 22/tcp ALLOW Anywhere Nginx Full ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) Nginx Full (v6) ALLOW Anywhere (v6) /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=djangouser Group=www-data WorkingDirectory=/home/djangouser/djangoproject ExecStart=/home/djangouser/djangoproject/.venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/djangouser/djangoproject/djangoproject.sock polman_project.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/djangoproject server { listen 80; server_name 555.555.55.555; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangouser/djangoproject; } location / { … -
How Should i import the Model Class on django to other py file to use it?
I wanted to insert model instance to database from a file. i wrote a python program to do so by importing models. but every time i get this error; ModuleNotFoundError: No module named 'exams' i have tried putting the file in the same folder; then i got "Relative import error" the expected result was to save model instance in the database. -
Django data frame automatically Add column
I'm creating a new data frame from my query. inputs =Test.objects.filter(created_at__date=datetime.today().date() - timedelta(days=1)).values('id','input') for i in inputs: name = name.objects.get(id=i['input']) name_label = name.label df = pd.DataFrame() df["Date"] = [datetime.today()] df["User"] = [user] df[name_label] = ['value']` Let say the query have 10 inputs(Name1,Name2,Name3,....), But my code not created a new columns depends on the query. Instead I got the only last record `{ "Name": { "Inputs": { "Date" : 2022-01-01, "User" : Admin, "Name10": "value" } } } ` I expecting output like this. The column to be added it's depend on the query output. `{ "Name": { "Inputs": { "Date" : 2022-01-01, "User" : Admin, "Name1": "value", "Name2": "value", "Name3": "value", "Name4": "value", "Name5": "value", and so on. } } }` -
how to us the prefix if there are two forms and one submit button?
I try to upload two forms with one submit button. A user can select a pdf file and a excel file. And then uploading both files. And then the contents of both are returned. So I try to upload both files with one submit button. But the two selected file options are not visible for uploading the files. So I have the template like this: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{form1.as__p}} <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> <div class="d-grid gap-3"> <div class="form-group"> {{form2.as__p}} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{conten_excel}}</textarea> </div> </div> </div> </form> </div> </span> </div> </body> </html> {% endblock content %} and the views.py: class ReadingFile(View): def get(self, *args, **kwargs): form = [UploadFileForm(), ExcelForm()] return … -
DJango Signals with Custom Arguments
I am trying to learn how to work with Django signal and maybe what I want to make work is impossible. I have two models User and Client. I want to create a Client and then use that Client ID to create a User. How do I pass user details to my signal? signals.py def client_created_handler(*args, **kwargs): print(args, kwargs) views.py client_query = Client.objects.create(client_name=request.POST.get('client_name'), address=request.POST.get('address'), email=request.POST.get('client_email'), phone='12345', website=request.POST.get('web'), created_by=request.user) custom_signal_kwargs = { "email": request.POST.get('contact_email'), "first_name": request.POST.get('first_name'), "last_name": request.POST.get('last_name'), "client": client_query, "user_role": 'Super User'} post_save.connect(client_created_handler,Client,**custom_signal_kwargs) The error I am getting is : TypeError: ModelSignal.connect() got an unexpected keyword argument 'email'. What am I doing wrong? -
Nginx setup with Django can’t access page
I have setup Django, Gunicorn and nginx. But my site is not loading? Gunicorn is running. In the logs I see that static files aren’t found. Here is my settings, am I doing something wrong with collectstatic? python manage.py collectstatic created a dir ‘collect_static’ automatically?! Before this command I had only a ‘static’ folder. Here is my Django settings, nginx settings and tree of django files: https://dpaste.org/NtoQ4 Thnx in advanced. -
Updating values inside a python list
ItemList = [ {'name': 'item', 'item_code': '473', 'price': 0}, {'name': 'item', 'item_code': '510', 'price': 0}, {'name': 'item', 'item_code': '384', 'price': 0}, ] data_1 = '510' data_2 = 200 def update_item(data_1, data_2): for a in ItemList: if a['item_code'] == data_1: update_price = append(a['price'].data_2) return True I want to update the price by using the function update_item. It fails at update_price = append(a['price'].data_2) -
Having "make_aware expects a naive datetime" while migrate
I have developed an application with Django. This is working fine in my PC with sqlite backend. But when I am trying to go live with linux server and mysql backend then I am getting bellow error while first time migration. (env-bulkmailer) [root@localhost bulkmailer]# python3 manage.py migrate Traceback (most recent call last): File "/var/www/bulkmailer-folder/bulkmailer/manage.py", line 22, in <module> main() File "/var/www/bulkmailer-folder/bulkmailer/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/commands/migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/migrations/recorder.py", line 82, in applied_migrations return { File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/models/query.py", line 394, in __iter__ self._fetch_all() File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/models/query.py", line 1866, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/models/query.py", line 117, in __iter__ for row in compiler.results_iter(results): File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/models/sql/compiler.py", line 1336, in apply_converters value = converter(value, expression, connection) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/backends/mysql/operations.py", line 331, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/utils/timezone.py", … -
Why Django 4.0 can access static files only with STATICFILES_DIRS, not STATIC_ROOT
When I use STATIC_ROOT: STATIC_ROOT = BASE_DIR / 'static' Django cannot access static files and always return 404 error for them. But when I use STATICFILES_DIRS: STATICFILES_DIRS = [ BASE_DIR / "static", ] Everything works well. What's the issue? I don't understand why Django works in this way, I always thought that STATIC_ROOT is correct way of creating route.