Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tiny MCE Text editor gives html in front-end [closed]
I am using Django in the backend and react.js in the frontend. The Tiny MCE Text editor gave me HMTl in the frontend. the blog is written tiny Mce text editor is correct but it gives in HTML instead of text in frontend -
IndexError on Django/MySQL after ordery_by an union queryset
I am using Django on ubuntu ec2 and MySQL on RDS. I try to obtain 3 random objects satisfying condition 1 (is_shoes=True, is_bag = False) and 2 random objects from the same model with different condition (is_shoes=True, is_bag = True) and union it in a random order. I tried using operator |, but it was now allowed in MySQL. Here is my source code and Error Message. Is there any solution? queryset = Store.objects.filter(is_shoes=True, is_bag = False).order_by('?') queryset_sample1 = queryset[:3] queryset2 = Store.objects.filter(is_shoes=True, is_bag = True).order_by('?') queryset_sample2 = queryset2[:2] queryset_sample = queryset_sample1.union(queryset_sample2, all=True) store_serializer = StoreSerializer(queryset_sample, many=True) response = Response({ 'store_list' : store_serializer.data }) return response Internal Server Error: /api/req/ Traceback (most recent call last): File "/home/ubuntu/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/ubuntu/myvenv/lib/python3.8/site-packages/rest_framework/generics.py", line 242, in post return self.create(request, *args, **kwargs) File … -
how to update all the record at once in Djnago
I want to display all the created department in one view using a for loop and update all the record at once. the problem is it is taking only the first record and updating all the record with the value entered at the first field I tried using .getlist() but still taking only the first record. how to update each record with reference to its id and if the field is empty keep that record untouched. Views.py def department(request): departments = Department.objects.all() value1 = request.POST.getlist('BUID') value2 = request.POST.getlist('GBUID') print(value1) print(value2) Department.objects.update( BUID=request.POST.get('BUID'), GBUID=request.POST.get('GBUID'), ) context = {'departments': departments} return render(request, 'employee/department.html', context) models.py class Department(models.Model): DepartmentID = models.IntegerField() <------will be Entered by the admin Name = models.CharField(max_length=200) <------will be Entered by the admin BUID = models.CharField(max_length=200, blank=True) <------to be updated in the view GBUID = models.CharField(max_length=200, blank=True) <------to be updated in the view templates <form action="" method="POST"> {% csrf_token %} <h3>Manage Departments</h3> <input class="btn btn-primary" type="submit" value="Submit"> {% for department in departments %} <div class="col-sm-6"> <label>Department ID: {{department.DepartmentID}}</label> </div> <div class="col-sm-6"> <label>Department Name: {{department.Name}}</label> </div> <label>BU/Department Manager Id:</label> <div class="col-sm-3"> <input name="BUID" class="form-control"> </div> <label>GBU/Group Department Manager Id:</label> <div class="col-sm-3"> <input name="GBUID" class="form-control"> </div> </form> {% endfor %} -
type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' (Exception is being thrown while fetching data)
Not sure on reason why I am getting error " Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' ". Everything seems to be done correctly but still getting error class Product { int? id; String? title; String? price; String? description; Category? category; bool? favorites; Product( { this.id, this.title, this.price, this.description, this.category, this.favorites}); Product.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; price = json['price']; description = json['description']; category = json['category']; favorites = json['favorites']; category = json['category'] != null ? new Category.fromJson(json['category']) : null; favorites = json['favorites']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['title'] = this.title; data['price'] = this.price; data['description'] = this.description; if (this.category != null) { data['category'] = this.category!.toJson(); } data['favorites'] = this.favorites; return data; } } class Category { int? id; String? categoryName; String? createDate; Category({this.id, this.categoryName, this.createDate}); Category.fromJson(Map<String, dynamic> json) { id = json['id']; categoryName = json['category_name']; createDate = json['create_date']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['category_name'] = this.categoryName; data['create_date'] = this.createDate; return data; } } Flutter is giving the unhandeled exception while fetching the data This … -
Is partial form a good practice in Django?
I'm new in Django and I try to find out if saving partial forms is a good practice or not. For example, I have Poll App and Candidate model with four fields: name, surname, targets andbiography. And I have a form where I have to fill all these fields. But if user only finished fill name, surname and targets, but even din't start filling biography field, how can I save his draft to user can finish it later and don't make any security mess? I will be happy to see all ideas. -
How to save model in Django with unique but null fields
How can I save a model that should be unique but also allowed to be null in Django. For instance I have the following model... class PetOwner(models.Model): """Model representing a pet owner.""" user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, help_text="Enter owner's first name") last_name = models.CharField(max_length=50, help_text="Enter owner's last name") email = models.EmailField( max_length=50, blank=True, unique=True, help_text="Enter owner's email" ) phone_number = models.CharField( max_length=15, blank=True, unique=True, help_text="Enter owner's phone number" ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, null=True, blank=True ) I want my app to work the following way. A PetOwner can sign up but when they do they initially only sign up with a username, password, a confirmation password, and first_name, and last_name. I want my to have a profile page which will allow for updating the PetOwner to include their phone_number but I do not necessarily want to make this a requirement. I decided that I'd make phone_number field null=True and blank=True but as soon as I register a second user I get a django.db.utils.IntegrityError: UNIQUE constraint failed: app_petowner.phone_number error. I believe it is because when I register a user for some reason instead of phone_number being None even when I did not actually add a phone number at … -
how to upload multiple images properly
I have a simple model which has four different fileFields for uploading different files and images. this is my models: class DocumentInfo(models.Model): id = models.AutoField(primary_key=True) certificate = models.FileField(upload_to="documents", null=True) id_card = models.FileField(upload_to="documents", null=True) service_certificate = models.FileField(upload_to="documents", null=True) educational_certificate = models.FileField(upload_to="documents", null=True) users need to simply upload some images in four individual fields so, I created a simple form and passed it to views like this: class DocumentForm(forms.ModelForm): class Meta: model = DocumentInfo fields = ['certificate','id_card','service_certificate','educational_certificate'] views.py: def document_info(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('document') if 'delete' in request.GET: return delete_item(DocumentInfo, request.GET['id']) else: form = DocumentForm() documents = DocumentInfo.objects.filter(user=request.user) context = { 'form': form, 'documents': documents, } return render(request, 'reg/documents.html', context) it works just fine at first but I cant reupload anything! the uploaded image neither gets saved the second time around nor deleted. what am I doing wrong? -
docker-compose Error... [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started
docker-compose.yml version: "3.7" services: db: platform: linux/x86_64 image: mysql:5.7 volumes: - ./db_data1:/var/lib/mysql environment: MYSQL_ROOT_PASSWORD: "${DB_ROOT_PASSWORD}" MYSQL_DATABASE: "${DB_DATABASE}" MYSQL_USER: "${DB_USER}" MYSQL_PASSWORD: "${DB_ROOT_PASSWORD}" ports: - 3306:3306 command: - --character-set-server=utf8mb4 - --collation-server=utf8mb4_unicode_ci web: build: dockerfile: ./Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 volumes: - ./web_data1:/app ports: - 8000:8000 environment: DJANGO_DB_HOST: db:3306 DJANGO_DB_NAME: "${DB_DATABASE}" DJANGO_DB_USER: "${DB_USER}" DJANGO_DB_PASSWORD: "${DB_ROOT_PASSWORD}" my_setting.py DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'PASSWORD': "${DB_ROOT_PASSWORD}", 'HOST': 'db', 'PORT': '3306', } } SECRET = 'django-insecure-#kb%p45em8hdhja^+2jal#(*mzw1c3jk5gvsx(_cn@q^u@u&b0' ALGORITHM = 'HS256' Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["gunicorn", "--bind", "0.0.0.0:8000", "docker_train.wsgi:application"] .env DB_ROOT_PASSWORD=password DB_DATABASE=test DB_USER=root I run docker-compose up but got this error. How can I approach it to solve the problem? error docker-training11-db-1 | 2021-11-09 05:14:47+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.36-1debian10 started. docker-training11-web-1 | Watching for file changes with StatReloader docker-training11-web-1 | Performing system checks... -
How to properly design django related model
I'm designing models base on a csv file: PATIENT ID,PATIENT NAME,EVENT TYPE,EVENT VALUE,EVENT UNIT,EVENT TIME 1,Jane,HR,82,beats/minute,2021-07-07T02:27:00Z 1,Jane,RR,5,breaths/minute,2021-07-07T02:27:00Z 2,John,HR,83,beats/minute,2021-07-07T02:27:00Z 2,John,RR,14,breaths/minute,2021-07-07T02:27:00Z 1,Jane,HR,88,beats/minute,2021-07-07T02:28:00Z 1,Jane,RR,20,breaths/minute,2021-07-07T02:28:00Z 2,John,HR,115,beats/minute,2021-07-07T02:28:00Z 2,John,RR,5,breaths/minute,2021-07-07T02:28:00Z 1,Jane,HR,66,beats/minute,2021-07-07T02:29:00Z 1,Jane,RR,15,breaths/minute,2021-07-07T02:29:00Z 2,John,HR,107,beats/minute,2021-07-07T02:29:00Z There are only 2 patients in this data, but the details of their HR and RR update every minute. This how I designed the model: from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser class Event_type(models.Model): """ Event_type is like a category model for patient, datebase relationship is one to many """ name = models.CharField(max_length=40) class Meta: verbose_name = "event_type" verbose_name_plural = verbose_name def __str__(self): return self.name class Patient(models.Model): patient_id = models.AutoField(unique=True, primary_key=True) # patient identification patient_name = models.CharField(max_length=30, blank=True, null=True, verbose_name='patient_name') event_type = models.ForeignKey(Event_type, on_delete=models.CASCADE, blank=True, verbose_name='event type') event_value = models.PositiveIntegerField(default=0, verbose_name='even value', blank=True) event_unit = models.CharField(max_length=100, blank=True, verbose_name='event unit') event_time = models.DateTimeField(auto_now=True, verbose_name='event time') class Meta: verbose_name = 'Patient' verbose_name_plural = verbose_name ordering = ['-patient_id'] def __str__(self): return self.patient_name However I guess while loading the data into database I may have the ununique error. Any better design ? Any friend can help? -
Django Session Form (save form temporarily)
I have created a page for review form. All users can fill out the form, but only logged in users can submit the form. If users is not logged in, they will be redirected to the login page. After they login, they will be redirected to the profile page. So the flow will be like this : User fills out the form > click the submit > redirected to login page > user login and redirected to profile page (at the same time, the form they have filled in is automatically saved) I want the form they have filled in automatically saved after they login. How to do that? My idea is to create a session that saves the form temporarily, then save to database after they login. But I'm confused how to write the code Can anyone explain a bit what a django session is like? and how to write code to handle this problem? -
Digital Ocean PWA Manifest Icons failing to fetch
I have my django pwa on digital ocean. I used django-pwa to convert to a pwa. My icons are failing to load. The path the manifest.json is my absolute path. But I have all my images and icons in a space on digital ocean, and for some reason, manifest is not trying to request the icons from that location. Can someone help me? -
Run idle using pen drive python
Is there a way to import libraries from one devices to another or any way to run python idle from pen drive to any other device -
Apache Airflow 2 does not execute the task after upgrading from 1.1
I upgraded to Airflow 2.0 today (docker) and since then, I am not able to execute any tasks (they fail successfully, but get stuck at the green with the below error). airflow_worker | airflow_worker | airflow_worker | airflow command error: argument GROUP_OR_COMMAND: celery subcommand works only with CeleryExecutor, your current executor: SequentialExecutor, see help above. airflow_worker | usage: airflow [-h] GROUP_OR_COMMAND ... airflow_worker | shows all the options here airflow_worker | -h, --help show this help message and exit airflow_worker exited with code 2 I used the standard docker-compose and made minor changes to suit my need. This is my docker-compose.yml version: '3' x-airflow-common: &airflow-common # In order to add custom dependencies or upgrade provider packages you can use your extended image. # Comment the image line, place your Dockerfile in the directory where you placed the docker-compose.yaml # and uncomment the "build" line below, Then run `docker-compose build` to build the images. image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.2.1} # build: . environment: &airflow-common-env AIRFLOW__CORE__EXECUTOR: CeleryExecutor AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://xxx:xxx@db/xxx AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://xxx:xxx@db/xxx AIRFLOW__CELERY__BROKER_URL: redis://:redispass@redis:6379/1 AIRFLOW__CORE__FERNET_KEY: '' AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true' AIRFLOW__CORE__LOAD_EXAMPLES: 'false' AIRFLOW__API__AUTH_BACKEND: 'airflow.api.auth.backend.basic_auth' _AIRFLOW_WWW_USER_USERNAME: airflow _AIRFLOW_WWW_USER_PASSWORD: airflow _PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:-} volumes: - ./airflow/dags:/opt/airflow/dags - ./airflow/logs:/opt/airflow/logs - ./airflow/plugins:/opt/airflow/plugins user: "${AIRFLOW_UID:-1000}:0" depends_on: &airflow-common-depends-on redis: condition: service_healthy db: condition: service_healthy services: … -
DJANGO error. Reverse for 'receipt' with arguments '('',)' not found. 1 pattern(s) tried: ['receipt/(?P<pk>[^/]+)/$'] trying to use ID:PK
Lots going on here, the last row in inventory.Html is suppose to link to a product page using the id from PRODUCTS in views.py. I am trying to create a page for each product using the ID but the path isn't working. inventory.html code {% for i in items %} <tr> <td>{{i.Name_of_the_Material_per_specification}}</td> <td>{{i.Site_Material_Code }}</td> <td><a class="btn btn-sm btn-info" href="{% url 'receipt' products.id %}">View</a></td> </tr> {% endfor %} RECIEPT.HTML <div class="col-md"> <div class="card card-body"> {% csrf_token %} {% for i in products %} <p>Name: {{products.Name_of_the_Material_per_specification}}</p> {% endfor %} </div> </div> URLS.PY from django.contrib import admin from django.urls import path, include from inventory import views urlpatterns = [ path('main', views.inventory, name='inventory'), path('receipt/<str:pk>/', views.products, name="receipt") views.py from django.shortcuts import render, HttpResponse from django.template import loader from django.shortcuts import redirect from .models import * from .forms import * # Create your views here. def inventory(request): items = materialForm.objects.all() return render(request, 'website/inventory.html', {'items': items}) def products(request, pk): products = materialForm.objects.get(id=pk) context = {'products':products } return render(request, 'website/receipt.html', context ) -
Testing custom action on a viewset in Django Rest Framework
I have defined the following custome action for my ViewSet Agenda: class AgendaViewSet(viewsets.ModelViewSet): """ A simple viewset to retrieve all the Agendas """ queryset = Agenda.objects.all() serializer_class = AgendaSerializer @action(detail=False, methods=['GET']) def get_user_agenda(self, request, pk=None): print('here1') id = request.GET.get("id_user") if not id: return Response("No id in the request.", status=400) id = int(id) user = User.objects.filter(pk=id) if not user: return Response("No existant user with the given id.", status=400) response = self.queryset.filter(UserRef__in=user) if not response: return Response("No existant Agenda.", status=400) serializer = AgendaSerializer(response, many=True) return Response(serializer.data) Here, I'd like to unit-test my custom action named "get_user_agenda". However, when I'm testing, the debug output("here1") doesn't show up, and it always returns 200 as a status_code. Here's my test: def test_GetUserAgenda(self): request_url = f'Agenda/get_user_agenda/' view = AgendaViewSet.as_view(actions={'get': 'retrieve'}) request = self.factory.get(request_url, {'id_user': 15}) response = view(request) self.assertEqual(response.status_code, 400) Note that: self.factory = APIRequestFactory() Am I missing something? Sincerely, -
Django Allauth TypeError at /accounts/confirm-email/
I'm using django-allauth for my django authentication and while confirming the email i get TypeError at /accounts/confirm-email/MQ:1mk57U:HtWDA8B5NClWhK2L6nDxJgwlNRGItW_4FyhDqcbcfow/ argument of type 'bool' is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/accounts/confirm-email/MQ:1mk57U:HtWDA8B5NClWhK2L6nDxJgwlNRGItW_4FyhDqcbcfow/ Django Version: 3.2.9 Exception Type: TypeError Exception Value: argument of type 'bool' is not iterable Exception Location: /home/ali/.local/lib/python3.9/site-packages/django/shortcuts.py, line 136, in resolve_url Python Executable: /usr/bin/python Python Version: 3.9.7 Python Path: ['/home/ali/Projects/Jobs', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/ali/.local/lib/python3.9/site-packages', '/usr/lib/python3.9/site-packages'] Server time: Mon, 08 Nov 2021 13:56:20 +0000 as I searched answers were in the cause of using django-rest-allauth and here I'm not using any rest api and facing this issue. some configs in my settings.py file INSTALLED_APPS = [ ... # allauth "django.contrib.sites", "allauth", "allauth.account", "allauth.socialaccount", "allauth.socialaccount.providers.google", "allauth.socialaccount.providers.facebook", "allauth.socialaccount.providers.twitter", "allauth.socialaccount.providers.telegram", "allauth.socialaccount.providers.instagram", "django_extensions", ... ] ... # all auth config AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", ] SITE_ID = 1 # required to hand over an e-mail address when signing up ACCOUNT_EMAIL_REQUIRED = True # "optional" or "None" unverified email login allow ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_LOGIN_ON_PASSWORD_RESET = True SOCIALACCOUNT_PROVIDERS = { ... } -
HOW RO CODIFY IN VIEWS USING DJANGO CODE, AS I WANT TO PREVENT THE FURTHER UPDATE ALL ROW FIELDS OF POSTGRESQL TABLE BASED , IF ONE FIELD IS UPDATED
HERE IS MY MODELS CODE ''' `class defectrecord(models.Model): # id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date=models.DateTimeField() natureofwork=models.CharField(max_length=100, null= True, blank=True) element=models.CharField(max_length=100, null= True, blank=True) defectobserved=models.CharField(max_length=500) repemployee=models.CharField(max_length=100) appemployee=models.CharField(max_length=100, blank=True) defappempremark=models.CharField(max_length=500, blank=True) defallocemp=models.CharField(max_length=100, blank=True) rectdetail=models.CharField(max_length=500, blank=True) rectdate=models.DateTimeField(null=True,blank=True) permit=models.BigIntegerField(null=True,blank=True) workcarried=models.CharField(max_length=500, blank=True) rectemployee=models.CharField(max_length=100, blank=True) rectappemployee=models.CharField(max_length=100, blank=True) rectappempremark=models.CharField(max_length=500, blank=True) image=models.ImageField(max_length=100, null= True, blank=True) class Meta: get_latest_by='id' ''' IF LAST 'OBJECT FIELD 'rectappempremark' IS UPDATED THEN SOME CODE IN VIEWS.PY TO PREVENT FURTHER UPDATE OF ALL MODELS FIELDS OF THAT PARTICULAR ROW (IDENTIFIED BY id). Above model contains save function and update functions based on permission code in views.py -
use for loop with JavaScript template literal function
I have a web app, frontend using normal HTML5, backend using Django. In the frontend page, I have a JavaScript template literal function. Which is supposed to render all the individual value into a selection box of a queryset passed from backend to a bootstrap table. view.py: def view_material(request): query_results_publisher = Publisher.objects.all() return render(request, 'material/index.html', context={'Publisher':query_results_publisher}) index.html(bootstrap table + javascript template literal function): ... <th class ='publisher' data-field="book.publisher" data-formatter="renderPublisher">Publisher</th>... <script> var Publisher = "{{ Publisher }}"; var publisher = ''; function renderPublisher(value) { return `select style="width: 7em" name="" id=""> for (publisher in ${Publisher}) { <option value="eText" ${(value === 'eText') ? 'selected="selected"' : ""}> publisher</option>}</select>}` </script> But my for loop in javascript template literal function is not working, seems like I have some problem with the template literal usage in for loop. How to correct my function? -
How to get each order id contain multiple order products price calculate with quantity in django restframework?
def generate_order_id(): return uuid.uuid4().hex class Order(models.Model): STATUS = [ ('success', _('SUCCESS')), ('pending', _('PENDING')), ('failed', _('FAILED')), ] DELIVERY_STATUS = [ ('ordered', _('ORDERED')), ('pick_up', _('PICKED UP')), ('in_transit', _('IN TRANSIT')), ('out_for_delivery', _('OUT FOR DELIVERY')), ('delivered', _('DELIVERED')), ('returned', 'RETURNED') ] id = models.CharField(verbose_name='ORDER ID', max_length=64, default=generate_order_id, editable=False, primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='order_user', editable=False) product = models.ManyToManyField(Product, related_name='order_product') address = models.ForeignKey(DeliveryAddress, on_delete=models.CASCADE, related_name='order_address') amount = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(1000000)]) datetimestamp = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=STATUS) delivery_status = models.CharField(max_length=10) class OrderDetails(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_details') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Meta: db_table = 'tbl_order_detail' class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) MRP = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(100000)]) price = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(100000)]) quantity = models.IntegerField() description = models.TextField() datetimestamp = models.DateTimeField(auto_now_add=True) class DeliveryStatus(models.Model): """ Delivery status of all orders """ user = models.ForeignKey(User, on_delete=models.CASCADE) order = models.OneToOneField(Order, on_delete=models.CASCADE) delivery_status = models.CharField(max_length=20, choices=DELIVERY_STATUS) timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True) class DeliveryCompletes(models.Model): """ here in this delivery completed only ordered product details and photo of product and price will automatically adding depend on delivery status order model and order details. """ PAYMENT = [ ('COD', 'CASH ON DELIVERY'), ('PREPAID', 'PREPAID'), ] STATUS = [ ('FULL', 'FULLY COMPLETED'), ('PARTIAL', 'PARTIAL COMPLETED') ] order = models.OneToOneField(DeliveryStatus, on_delete=models.CASCADE) payment_type … -
Django cannot find project app - cannot import x_app
I am working on moving a django project from a Windows environment to a Ubuntu environment. The project was stored in git and cloned into the Ubuntu environment. I am using virtualenv for a clean slate (same as on windows environment). Whether I run django-admin check or anything using python manage.py I get the below error: Traceback (most recent call last): File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/apps/config.py", line 244, in create app_module = import_module(app_name) File "/opt/bitnami/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'akita_app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/bitnami/djangoenv/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/bitnami/djangoenv/lib/python3.8/site-packages/django/apps/config.py", line 246, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'akita_app'. Check that 'akitaapp.apps.AkitaAppConfig.name' is correct. The akita_app or akitaapp (same thing) that is missing is the the akitaapp folder. The project works perfectly in the Windows environment so I am guessing … -
Can I use ABC and Django Abstract classes together in Python?
I have a django abstract class: class AbstractModel(models.Model): date_added = models.DateField(auto_now_add=True) class Meta: abstract = True I want my concrete classes (Django Models) to subclass this abstract class, but I also want to make sure that all my concrete classes always implement very specific methods using abc. I tried doing this: class AbstractBaseClass(AbstractModel, metaclass=abc.ABCMeta): @abstractmethod def important_method(self): pass class MyDjangoModel(AbstractBaseClass): ... And I tried: class AbstractBaseClass(ABC): @abstractmethod def important_method(self): pass class MyDjangoModel(AbstractModel, AbstractBaseClass): Neither worked. They both say: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Is there a way to do this, or is this impossible? -
Django App Deploy on elastic beanstalk WSGI path issue
I am deploying the app then it gets severed health and 502 gateaway returns on browser. I checked out the logs lines I found these. Nov 9 01:15:38 web: ModuleNotFoundError: No module ImportError: Failed to find application, did you mean 'ecc/wsgi:application'? In .ebextensions folder django.config file look like below. option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ecc/wsgi.py I also tried to give ecc/ecc/wsgi.py because of the folder structure --ecc |--accounts |--ecc --|__init__.py --|settings.py --|wsgi.py But it didn't worked either. What is the correct way to fix this issue. What I am missing here? -
Password Lock after Multiple Login Attempts for Django + simplejwt
I'm building Django app and implemented login function with django restframework simplejwt. Now trying to add function to lock out users after multiple wrong login attempts. Many people suggest django-axes package, but it only works with Django's default authentication backend, not with simplejwt's views. Any existing python packages help for this? Otherwise, how do you implement such a function with simplejwt? -
Django: No random letters in same name file uploaded
This is my code to let my user upload files, when more then one file is uploaded with the same condition by default random letters are added to the file name to avoid duplicate, is it possible to have the quantity number of file uploaded instead? so instead of having randomfilename randomfilename_jlCtWGb randomfilename_aOMtTeb have this randomfilename_1 randomfilename_2 randomfilename_3 Code: models.py def user_directory_path(instance, filename): filename = "word_file_%s.%s" % (instance.option, extension) return 'word_folder/{0}/{1}'.format(instance.option, filename) class Document(models.Model): option_choice = [ ('1', 'Option One'), ('2', 'Option Two') ] user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) option = models.CharField(max_length=250, choices=option_choice, blank=True, null=True) original_filename = models.CharField(max_length=250, blank=True, null=True) docfile = models.FileField(upload_to=user_directory_path) def __str__(self): return word_db_' + self.option views.py @login_required def upload_file(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) uploaded_file= request.FILES if form.is_valid(): form.instance.user = request.user.userinformation form.instance.original_filename = uploaded_file['docfile'].name form.save() return redirect('upload_file') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() context = { 'form': form, 'message': message } return render(request, 'list.html', context) -
Encoding and decoding a base64 image in django
I have a django project in which I encode an image to Base64 via a serializer with the Base64ImageField field method There are no problems, but there is no way to get the image back:( In order not to get a 404 error in the serializer, I use SerializerMethodField and return STATIC_ROOT + obj.image.name . In this case, the code 200 is returned, but the picture is not displayed. I tried to decode through base64.b64decode(obj.image.encode('UTF-8')) and other methods of decoding and processing base64 drawings, but no one of them looks out the necessary code in the file. My decode serializer code to read: class DecodeSerializer(ModelSerializer): image = SerializerMethodField() class Meta: fields = "__all__" model = MyModel def get_image(self, obj): return STATIC_ROOT + obj.image.name My encode serializer: class EncodeSerializer(RecipesSerializer): image = Base64ImageField(max_length=None, use_url=True) class Meta: fields = "__all__" model = MyModel