Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can data stored in memory on a website be hacked? [closed]
I'm currently making a website in Django and I intend to eventually host it with Digital Ocean. Basically, what the website does is have a user upload a file that is hard to read, and then the website parses the content of the uploaded file and displays it in an easy to read format for the user. The file the user uploads may have some personal data in it. The way I have it set up is that all the data from the uploaded file is stored in memory. I don't upload the file's data to a database or locally on the website because I don't want any of the data, and I don't want the user's uploaded data to be seen anywhere but on the user's computer. So this means that when the user refreshes the page or goes to a different page and comes back, they have to upload their file again because the data from the user's uploaded file would have been deleted from memory when the page loads again. My question: The whole point of doing it this way is to keep the user's data safe (inaccessible) from everyone, including myself. Is this a good method … -
Django not updated inside the docker cookiecutters template
My Django project that is created based on Cookiecutters is not updated in local development environment after I changed the source code, I need to stop and start the docker again. I checked the volume and it seems ok but still no auto-update. The files and their contents are as follow: version: '3' volumes: one_sell_local_postgres_data: {} one_sell_local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: one_sell_local_django container_name: one_sell_local_django platform: linux/x86_64 depends_on: - postgres - redis volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: one_sell_production_postgres container_name: one_sell_local_postgres volumes: - one_sell_local_postgres_data:/var/lib/postgresql/data:Z - one_sell_local_postgres_data_backups:/backups:z env_file: - ./.envs/.local/.postgres redis: image: redis:6 container_name: one_sell_local_redis The Dockerfile for Django: ARG PYTHON_VERSION=3.9-slim-bullseye # define an alias for the specfic python version used in this file. FROM python:${PYTHON_VERSION} as python # Python build stage FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ && apt-get install gdal-bin -y \ # psycopg2 dependencies libpq-dev # Requirements are installed here to ensure they will be cached. COPY ./requirements . # Create Python Dependency and Sub-Dependency Wheels. RUN pip … -
More elegant one-liner way for urls.py to recognize path that include / as well as no / in Django
I am using Django v4. This is my urls.py from django.urls import path from .views import UserList, UserDetail urlpatterns = [ path("users", UserList.as_view()), ] http://127.0.0.1:8000/users works fine. However, http://127.0.0.1:8000/users/ with the slash at the end fails to work. To solve this problem, here's the new urls.py. from django.urls import path from .views import UserList, UserDetail urlpatterns = [ path("users", UserList.as_view()), path("users/", UserList.as_view()), ] It looks kind of repetitive and goes against DRY principle behind Django. Is there a more elegant one-liner to fix this problem? Answer need not be a one-liner as long as it doesn't look repetitive. -
django how to save data to multiple tables
I have PostgreSQL function that saves data in both items and items_transactionlog, I deleted some rows so its easier to read. INSERT INTO public.items (remarks,resolution,record_date,resolve) VALUES (f_remarks,f_resolution,now(),false); INSERT INTO public.items_transactionlog (trans_desc,trans_recorded) VALUES ('Add Clearance Item',now()); I want to use this function thru my models.py, How can I customize my models.py so whenever I save an item it also saves on transactionlog I use inspectdb and add the following models on my app class Items(models.Model): itemid = models.CharField(primary_key=True, max_length=20) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'items' class ItemsTransactionLog(models.Model): log_id = models.AutoField(primary_key=True) trans_desc = models.TextField(blank=True, null=True) trans_recorded = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'items_transactionlog' -
Django: to loop field while creating another instance
if i want to create another instance it doesnt pick the initial value. this is my model.py class Transaction(models.Model): student= models.ForeignKey(Student,blank=True,null=True, on_delete=models.CASCADE) schoollevy= models.ForeignKey(Schoollevy,blank=True,null=True, on_delete=models.CASCADE) inputt=models.IntegerField(blank=True,null=True) credit=models.IntegerField(blank=True,null=True) debit=models.IntegerField(blank=True,null=True) bal=models.IntegerField(blank=True,null=True) descrip=models.CharField(max_length=200, blank=True,null=True) date=models.DateField(auto_now_add=True, null=True, blank=True) def save(self): if self.schoollevy=="school fee": self.debit += self.inputt self.bal= self.credit-self.debit return super(Transaction, self).save() if i want to create a another instance it doesnt pick the first instance value -
Django TypeError: issubclass() arg 1 must be a class. Caused by from rest_framework.authtoken.views import ObtainAuthToken in views.py
I wrote the following view in Django to serialize the obtained token. However, I get error. I Could not get a similar issue on internet, most of the post were related to tests. from rest_framework import generics from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from user.serializers import UserSerializer from user.serializers import ( UserSerializer, AuthTokenSerializer, ) class CreateUserView(generics.CreateAPIView): """Create a new user in the system.""" serializer_class = UserSerializer class CreateTokenView(ObtainAuthToken): """Create a new auth token for user.""" serializer_class = AuthTokenSerializer renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES After running docker-compose I get following error: eMenue_1 | File "/app/eMenue/user/urls.py", line 5, in <module> eMenue_1 | from user import views eMenue_1 | File "/app/eMenue/user/views.py", line 5, in <module> eMenue_1 | from rest_framework.authtoken.views import ObtainAuthToken eMenue_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/authtoken/views.py", line 11, in <module> eMenue_1 | class ObtainAuthToken(APIView): eMenue_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/authtoken/views.py", line 18, in ObtainAuthToken eMenue_1 | if coreapi_schema.is_enabled(): eMenue_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/schemas/coreapi.py", line 612, in is_enabled eMenue_1 | return issubclass(api_settings.DEFAULT_SCHEMA_CLASS, AutoSchema) eMenue_1 | TypeError: issubclass() arg 1 must be a class Any idea what can cause that plese? -
I have installed django-form-designer-ai as an app in my site but am unable to add fields
I have installed django-form-designer-ai as an app and it shows in my Admin page and Add form does not allow me to define my own fields. I had installed the package with PIP in my venv if that makes a difference. -
Using Ajax to change a Boolean in a Django Model using a Button
I am trying to send a post in a Django project to switch a boolean from False to True. The button is working fine but I want to click it without refreshing the page so I am trying to use Ajax but I keep getting {"status": "error"} for a bad request and not sure why. Here is the views: def change_status(request, id): if request.is_ajax() and request.method == 'POST': startsession = Workout.objects.get(id=id) startsession.active = True if request.POST.get('active') == 'true' else False startsession.save() data = {'status': 'success', 'active': startsession.active} return JsonResponse(data, status=200) else: data = {'status': 'error'} return JsonResponse(data, status=400) Here is the template: <div> {% if object.active %} <button disabled type="button">Start the workout</button> {% else %} <a href="{% url 'my_gym:bla' object.id %}"> <button id="customSwitches" onclick="start();" type="button">Start the workout</button> </a> {% endif %} </div> Here is the ajax script <script> $(document).ready(function() $("#customSwitches").on('click', function () { $.ajax({ url: "{% url 'my_gym:bla' object.id %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", active: this.disabled }, type: "POST", dataType: 'json', }); .done(function(data) { console.log(data); }) .always(function() { console.log('[Done]'); }) }) }); </script> -
Unable to access Bitnami Django web app using run server of mod_wsgi
I am not sure what I am missing here to get Django running on Google Compute Engine and access it publicly. I am starting with Django packaged by Bitnami since it seems like it would be easy... I have been following this Getting Started Guide to get a running instance of Django running on Google Compute Engine. Django Packaged By Bitnami For Google Cloud Platform It successfully deploys and I see the Bitnami page. I am unable to get pass this point even with the simple example of hello world in their guide. I have used both ./manage.py runserver and serving through Apache Web server with the module mod_wsgi for my project. Test Your Django Project The Django project can be started by using this command from the /opt/bitnami/projects/PROJECT directory, and it will run on port 8000: cd /opt/bitnami/projects/PROJECT python manage.py runserver To access the application, browse to http://SERVER-IP:8000/. To end the application, terminate the running Django process. I have completed a Django Project that I can test and run locally. Getting something basic on Google Compute Engine, is another story. -
Error in django template if statements about end block
I'm getting the following error for the django template below. Line 63 is the {% else %} statement on the line after "Age: {{bottom_age | safe}} to {{top_age | safe}} ". Thoughts on what is wrong? To me, this just looks like subsequent if statements. When I removed the below block, it worked fine but I don't know what is wrong with the below block. I tried putting the two variables on different lines (bottom_age and top_age), but that didn't help. {$ if age %} <p>Age: {{bottom_age | safe}} to {{top_age | safe}} </p> {% else %} <p>No age supplied, so all ages used</p> {% endif %} django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 63: 'else', expected 'endblock'. Did you forget to register or load this tag? {% if score %} <p>You are in the <b>{{percentile | safe}}</b> percentile compared to other people who self identify as:</p> {% endif %} {$ if age %} <p>Age: {{bottom_age | safe}} to {{top_age | safe}} </p> {% else %} <p>No age supplied, so all ages used</p> {% endif %} {% if gender %} <p>Gender: {{gender | safe}}</p> {% else %} <p>No gender supplied, so all genders used</p> {% endif %} {% if ethnicity %} … -
Celery task is not started
I have 2 celery tasks with two workers (worker for each task) docker-compose.yml -- https://pastebin.com/Ln9WgxTd Problem - don't see logs and results of the periodic_check_urls I am calling periodic_check_urls via POST request, but don't see result of the function I just see nginx_1_ef8ec258f1c4 | 10.37.15.246 - - [05/Sep/2022:23:59:02 +0000] "POST /check_all_urls/ HTTP/1.1" 200 34 "-" "PostmanRuntime/7.26.8" "-" settings.py CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", "redis://redis:6379/0") CELERY_IMPORTS = ("core_app.celery",) CELERY_ROUTES = { 'parser_app.views.periodic_exctract_urls': {'queue': 'priority_queue'}, 'parser_app.views.periodic_check_all_urls': {'queue': 'normal_queue'}, } CELERY_BEAT_SCHEDULE = { 'fetch_yandex_urls': { 'task': 'parser_app.views.periodic_exctract_urls', 'schedule': crontab(minute='*/15'), 'options': {'queue': 'priority_queue'} }, } views.py @shared_task(name="parser_app.views.periodic_check_urls") def periodic_check_urls(parsing_result_ids: List[int]): ... print("Log", flush=True) # don't see this log @api_view(['POST']) def periodic_check_all_urls(request): ... periodic_check_urls.delay(parsing_results_ids) # parsing_results_ids is a list of ints -
datetime mismatch between plain Python console and a Django shell
I can open a plain Python console and run: >>> from datetime import datetime >>> datetime.now().strftime('%H:%M') '01:21' When I do the same in ./manage.py shell, however, I get different results: >>> from datetime import datetime >>> datetime.now().strftime('%H:%M') '23:21' Why is that? I though it might be related to the timezone, so I checked date time.now().tzinfo, which, however, is None in both cases. I also tried setting USE_TZ = False in settings.py but it doesn't make a difference (it was on True by default). -
How can I do so that they cannot create a post with more than 300 digits?
Picture of the post What I want to do is that when you have more than 300 digits you can't touch the "Bloob" button or something like that. What is on the left is a counter with javascript. The models is this class Post(models.Model): timestamp = models.DateTimeField(default=timezone.now) content = models.TextField(max_length=300) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') This is the PostForm class PostForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control w-100', 'id':'contentsBox', 'rows':'3', 'placeholder':'¿Qué está pasando?'})) -
Limit queryset to foreignkey in django rest framework
i searched a lot about a solution for this problem and i tried many solutions but no one solve it some of solutions i tried: limit choices to foreignkey and using CurrentUserDefault the problem is i'm trying to limit the provider choices depending on the current user as each user has his own providers i tried this code but gives me TypeError: Field 'id' expected a number but got CurrentUserDefault(), class RideSerializer(serializers.ModelSerializer): invoice = InvoiceSerializer(required=False) duration = serializers.ReadOnlyField() riding_duration = serializers.ReadOnlyField() heading_duration = serializers.ReadOnlyField() earning_per_km = serializers.ReadOnlyField() earning_per_minute = serializers.ReadOnlyField() provider = serializers.PrimaryKeyRelatedField( queryset=User.objects.select_related( 'driver_profile__team', 'company_profile__team').filter( Q(driver_profile__team__user=serializers.CurrentUserDefault()) | Q(Company_profile__team__user=serializers.CurrentUserDefault())), default=serializers.CurrentUserDefault()) class Meta: model = Ride exclude = ['shift', ] read_only_fields = ['id', 'start_time', ] -
how raise ImproperlyConfigured("settings.DATABASES is improperly configured. when deploying on railway
hey guys so i'm follwing this guide https://dev.to/mr_destructive/django-postgresql-deployment-on-railway-app-d54 on how to deploy my django project on railway i have everything set locally, it working but once i deploy, the app crashes returning this err File "/home/olaneat/Desktop/files/project/django/job/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/home/olaneat/Desktop/files/project/django/job/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/olaneat/Desktop/files/project/django/job/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/home/olaneat/Desktop/files/project/django/job/lib/python3.8/site-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. can someone pls help out -
Imports works in IDE and Idle but not in dokcer-compose and manage.py test
I have a strange problem with my Django project. The imports work fine in IDE and I can import when I import it in python CLI. However, when I run docker compose, I get error like: File "/app/eMenue/eMenueApp/admin.py", line 3, in <module> eMenue_1 | from eMenue.eMenueApp.models import models eMenue_1 | ModuleNotFoundError: No module named 'eMenue.eMenueApp' When I run python manage.py test I get similar output: ImportError: Failed to import test module: eMenue.eMenueApp Traceback (most recent call last): File "/usr/lib/python3.10/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'eMenue.eMenueApp' The structure of my code looks like this: ├── eMenue │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-310.pyc │ │ ├── settings.cpython-310.pyc │ │ └── urls.cpython-310.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── eMenueApp │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-310.pyc │ │ ├── apps.cpython-310.pyc │ │ ├── __init__.cpython-310.pyc │ │ └── models.cpython-310.pyc │ ├── tests │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ └── test_models.cpython-310-pytest-7.1.3.pyc │ │ └── test_models.py │ └── views.py ├── __init__.py ├── manage.py └── __pycache__ … -
Generating models from Database with FastAPI and SQLAlchemy
I have a Django project running on production with PostgreSQL. I want to spin a separate FastAPI microservice to do a specific task, and I want it to communicate directly with the database I have hooked up with Django. I do not want to rewrite all the models in FastAPI using pydantic, and at the same time I don't want to make a mistake. In Django, there is python manage.py inspectdb to automatically generate models using an existing database. Is there an equivalent in FastAPI, SQLAlchemy or Pydantic? -
django filter: datetime filed
Pease help me with next. I create NotesFilter based on django_filters.FilterSet. All filters is working except datetime. I trying everything, but something wrong and it doesn't working. List is empty when i enter any value in any format in field "Reminder contains:" filter.py: class NotesFilter(django_filters.FilterSet): SORT_BY_ = ( ('title+', 'Title(A-Z)'), ('title-', 'Title(Z-A)'), ('reminder_data_time+', 'Reminder (0-9)'), ('reminder_data_time-', 'Reminder (9-0)'), ) sort = django_filters.ChoiceFilter(label='Order by:', choices=SORT_BY_, method='filter_') class Meta: model = Notes fields = { 'notes_category': ['exact', ], 'title': ['icontains', ], 'reminder_data_time': ['icontains',] } def filter_(self, queryset, name, value): if value == 'title+': sort = 'title' elif value == 'title-': sort = '-title' elif value == 'reminder_data_time+': sort = 'reminder_data_time' elif value == 'reminder_data_time-': sort = '-reminder_data_time' return queryset.order_by(sort) models.py: class Notes(models.Model): title = models.CharField(max_length=25) text = models.TextField() data_time = models.DateTimeField(auto_now_add=True) reminder_data_time = models.DateTimeField(default=datetime.datetime.now()) notes_category = models.ForeignKey(NotesCategory, on_delete=models.CASCADE) class Meta: verbose_name_plural = "Notes" def __repr__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse('detail_note', args=[str(self.id)]) notes.html: [![<form method="get"> {% for choice in filter.form %} {% if choice.name == 'notes_category' %} <td>Category: {{ choice }}</td> {% elif choice.name == 'title__icontains' %} <td>Title contains: {{ choice }}</td> {% elif choice.name == 'reminder_data_time__icontains' %} <td>Reminder contains: {{ choice }}</td> {% elif choice.name == 'sort' … -
OperationalError at /accounts/login/ no such table: django_site
I wanted to ask a question, I am hosting my Django project on pythonanywhere, we are using the allauth package, I was having no problems until this happened.... OperationalError at /accounts/login/ no such table: django_site Request Method: GET Request URL: https://dariobackend2022.pythonanywhere.com/accounts/login/ Django Version: 4.1 Exception Type: OperationalError Exception Value: no such table: django_site Exception Location: /home/DarioBackEnd2022/.virtualenvs/lalcecCHACO- virtualenv/lib/python3.9/site- packages/django/db/backends/sqlite3/base.py, line 357, in execute Raised during: allauth.account.views.LoginView Python Executable: /usr/local/bin/uwsgi Python Version: 3.9.5 Python Path: ['/var/www', '.', '', '/var/www', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/DarioBackEnd2022/.virtualenvs/lalcecCHACO- virtualenv/lib/python3.9/site-packages', '/home/DarioBackEnd2022/Grupo2-ProyectoFinal'] Server time: Mon, 05 Sep 2022 17:36:20 -0300 the context is that we were changing the name of the urls in the href of our templates, the allauth one is {% url 'account_login' %} but we get that error.... these are my URLs.py from argparse import Namespace from django.contrib import admin from django.urls import path, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from pagina import views urlpatterns = [ path('foro/', views.listarPost.as_view(), name='lista_post'), path('post/<slug:url>/', views.DetallePost.as_view(), name='detalle_post'), path('accounts/', include('allauth.urls')), path('accounts/profile', views.profile), ] urlpatterns += staticfiles_urlpatterns() if you need more information ask me please -
TypeError: modelform_factory() got an unexpected keyword argument 'extra'
I'm trying to use the modelformset_factory to render multiple forms. However, when trying to run the server, this error occurs TypeError: modelform_factory() got an unexpected keyword argument 'extra' All the online sources say that I should be able to specify the extra argument in the modelform_factory but I can't seem to. forms.py class MapSeniorTeachForm(ModelForm): role = forms.CharField(max_length=32) def __init__(self, teach_id, *args, **kwargs): super(MapSeniorTeachForm, self).__init__(*args, **kwargs) self.teach_id = teach_id self.fields['senior'] = forms.ChoiceField(choices=[(1,1),(2,2),(3,3)]) class Meta: model = MapSeniorTeach fields = ['role', 'senior'] MapSeniorTeachFormset = modelform_factory(MapSeniorTeach, form=MapSeniorTeachForm, extra=1) Clipped Output Log File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\ethan\Documents\VSCodeProjects\bansheeApp\bansheeApp_project\banshee\training\urls.py", line 3, in <module> from .views import * File "C:\Users\ethan\Documents\VSCodeProjects\bansheeApp\bansheeApp_project\banshee\training\views.py", line 14, in <module> from .forms import LessonTeachForm, ActivityTeachForm, MapSeniorTeachFormset File "C:\Users\ethan\Documents\VSCodeProjects\bansheeApp\bansheeApp_project\banshee\training\forms.py", line 25, in <module> MapSeniorTeachFormset = modelform_factory(MapSeniorTeach, form=MapSeniorTeachForm, extra=1) One thing to note, if I remove the extra keyword, one instance of the form is successfully rendered. Here are some sources I was speaking about before: … -
DRF dynamic choices depend on current user
is there any way to make choices dynamically depend on current user something like that: class RideSerializer(serializers.ModelSerializer): provider_username = serializers.ChoiceField(choices=request.user.providers) -
Django fetch data as json from property and calculate it with jquery
Like the titile says, is it possible? I have like 100 numbers that are only updated but need to be calculated and and results should show in template, annotate allows me to calculate some fields but wont allow me to show it anywhere I need. And even if I got that as json I dont know jquery how would I calculate those numbers. my models in small class numbers(models.Model): number 1 = models.IntegerField(default=0) number 2 = models.IntegerField(default=0) number 3 = models.IntegerField(default=0) number 4 = models.IntegerField(default=0) number 5 = models.IntegerField(default=0) @property def sum of 1_2(self): return json.dumps(self.number 1 + self.number2) and so on -
django on cpanel ,, ImportError: No module named app_name.wsgi
I'm trying to deploy Django on Cpanel shared hosting .. after creating the app and everything was going okay following this guide, it never opens and it gives me this error : Traceback (most recent call last): File "/home/wateopjw/water_maps_dashboard/passenger_wsgi.py", line 1, in <module> from water_maps.wsgi import application ImportError: No module named water_maps.wsgi my passenger_wsgi.py from water_maps.wsgi import application my wsgi.py file """ WSGI config for water_maps. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'water_maps.settings') application = get_wsgi_application() Project Structure -
How to create a new field in django admin panel inside if condition in a method in the model
In the "save" method, I want to create a new field in the admin panel if the transaction type is transefere and vs code sees the new variable as a deadcode and says it's not accessed. ''''''''''''''''''''''''''''''''''''''''''''''' from django.db import models import uuid import random import math class Transaction (models.Model): customer=models.CharField(max_length=50) balance= models.DecimalField( max_digits=10,decimal_places=2 ,default=random.randint (0,30000)) class trans_options(models.TextChoices): CASH_IN= "cash in","cash in" CASH_OUT= "cash out" ,"cash out" TRANS= "transefere","transefere" INVALID="INVALID OPERATION", "INVALID OPERATION" Transaction_type=models.CharField( max_length=50,choices=trans_options.choices ,default=trans_options.INVALID) amount =models.DecimalField( max_digits=4,decimal_places=2) def save(self, *args, **kwargs): if self.Transaction_type == "cash in" : self.balance = self.balance + self.amount if self.Transaction_type == "cash out": self.balance=self.balance - self.amount if self.Transaction_type == "transefere" : self.balance=self.balance - self.amount customer2 = models.CharField(max_length=50) return super(Transaction, self).save(*args, **kwargs)' -
when I do python manage.py collectstatic I get the following error
I'm new to coding and djgango in general. I don't know what to do. I have checked my code time and again... and I'm lost. ``` STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] I Get the following error. I've checked my urls.py but aparently all is fine Traceback (most recent call last): File "/home/juanneg/ecommerce/manage.py", line 22, in <module> main() File "/home/juanneg/ecommerce/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/social_django/models.py", line 14, in <module> from .fields import JSONField File "/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/social_django/fields.py", line 7, in <module> from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/home/juanneg/ecommerce/envcom/lib/python3.10/site-packages/django/utils/encoding.py)