Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert a string of list of ordereddict to a list with dictionaries
I have a dataframe in which every row contains a string like the following: "[OrderedDict([('id', 946), ('product', 'CRT6423'), ('quantity', 1)]), OrderedDict([('id', 947), ('product', 'CIN1199B'), ('quantity', 1)]), OrderedDict([('id', 948), ('product', 'CSS001'), ('quantity', 2)])]" This is in string format. I want to convert this into a list of dictionaries for which I am using literal_eval but it gives me the following error": ValueError: malformed node or string: <_ast.Call object at 0x00000175D77D9DF0> Expected output: [{"product":"CRT6423", "quantity":1}, {"product":"CIN1199B", "quantity":1}, {"product":"CSS001", "quantity":2}] -
unable to display image using jinja
I created a separate model for users to upload a profile pic. models.py class Image(models.Model): profilepic = models.ImageField(upload_to='images/', null = True) def __str__(self): return self.title html <img src="/images/{{ image.profilepic }}"/> all I am getting back is a empty canvas with an image icon I should note the images are uploading to the folder just not displaying -
Windows Django: Error: You don't have permission to access that port
I am trying to run a Django project in Windows but I am getting Error: You don't have permission to access that port. Running python manage.py runserver and python manage.py runserver "IP":"PORT" returned same result/error. I searched for answers but most or all of them are for Linux. -
how to handle this error when user search but didn't pass anything and found this kind of error in Django but user input id it work
views.py def paitent(request): search_query = '' if request.GET.get('search_query'): search_query = request.GET.get('search_query') if search_query == ' ': print('Ex') else: userprofile = Profile.objects.filter(id=search_query) profiles = Totallcount.objects.filter(image_owner=search_query) context = { 'profiles':profiles, 'userprofile':userprofile, } return render(request, "medical_report/paitent.html",context) paitent.html <form class="d-flex ms-auto my-3 my-lg-0" id='searchForm' action="{% url 'paitent' %}" method="get"> <div class="input-group"> <input class="form-control" type="search" placeholder="Search by Name" aria-label="Search" id="formInput#search" type="text" name="search_query" value="" /> <button class="btn btn-primary" type="submit" value="Search"> <i class="bi bi-search"></i> </button> </div> </form> Error. UnboundLocalError at /paitent/ local variable 'profiles' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/paitent/?search_query= Django Version: 3.2.15 Exception Type: UnboundLocalError Exception Value: local variable 'profiles' referenced before assignment Exception Location: C:\Users\21100002\Desktop\myreports\medical_report\views.py, line 176, in paitent Python Executable: C:\Users\21100002\Desktop\ocr\env\Scripts\python.exe Python Version: 3.7.0 -
How can i implement multi websites in one core in django?
How can I implement multi websites with one core in Django? I have multi websites with this structure: example.com (Main website) example.com/subdirectory1 (Second website) example.com/subdirectory2 (Third website) example.com/subdirectory2/en (Fourth website) example.com/subdirectory3 (Fifth website) I want to use one core to manage all websites. -
Django: Show data from current user
I'm having trouble displaying data from current user. It shows all the shifts that was given to other users also. I don't have any idea how to do this. Below is my code. models.py class User(models.Model): user_name = models.CharField(max_length=32, unique=True) pass_word = models.CharField(max_length=150) is_active = models.BooleanField(default=True) class Rostering(models.Model): name = models.CharField(max_length=64) begin_time = models.TimeField(default="") end_time = models.TimeField(default="") is_active = models.BooleanField(default=True) class RosteringUser(models.Model): rostering_user = models.ForeignKey(Rostering, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) views.py def my_shift(request): if request.method == 'GET': queryset = RosteringUser.objects.all() if queryset: for obj in queryset: id = Rostering.objects.get(rosteringuser=obj.id) obj.id = id return render(request, 'my_shift.html', {'queryset': queryset}) my_shift.html {% for obj in queryset %} <tr> <td>{{ obj.user.user_name }}</td> <td>{{ obj.id.name }}-{{ obj.id.begin_time }}</td> <td>{{ obj.id.name }}-{{ obj.id.end_time }}</td> </tr> {% endfor %} Thank you in advance! -
Django admin filter_horizontal-like view without ManyToMany field
I need to assign many string values to one field in a model, and it should be possible with a tables like in filter_horizontal and ManyToMany field. Is there any way to do it without saving those strings in model?enter image description here -
Installed package was successful outside virtual env but errors inside virtual env
I have a package "fretboardgtr" successfully installed outside virtual env using pip. The modules work without any errors. I started a django project inside a virtual env and tried to install the same package inside the virtual env but it errors with the following error: Collecting fretboardgtr Using cached fretboardgtr-0.0.4-py3-none-any.whl (32 kB) Processing /Users/sajwaltamrakar/Library/Caches/pip/wheels/83/85/db/f83adc7591329e230cb5bda2a339e66a8dbd0f69ade492db56/svglib-1.4.1-py3-none-any.whl Collecting Pillow>=7.1.2 Using cached Pillow-9.2.0.tar.gz (50.0 MB) Collecting webencodings>=0.5.1 Using cached webencodings-0.5.1-py2.py3-none-any.whl (11 kB) Collecting svgwrite>=1.4 Using cached svgwrite-1.4.3-py3-none-any.whl (67 kB) Collecting cssselect2>=0.3.0 Using cached cssselect2-0.7.0-py3-none-any.whl (15 kB) Collecting lxml>=4.5.1 Using cached lxml-4.9.1.tar.gz (3.4 MB) Collecting tinycss2>=1.0.2 Using cached tinycss2-1.1.1-py3-none-any.whl (21 kB) Collecting reportlab>=3.5.42 Using cached reportlab-3.6.11.tar.gz (4.5 MB) ERROR: Command errored out with exit status 1: command: /Users/MYNAME/Documents/Python/content_creator/CC_env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/h2/xy8.... Complete output (10 lines): ##### setup-python-3.9.1-macosx-11-x86_64: ================================================ ##### setup-python-3.9.1-macosx-11-x86_64: Attempting build of _rl_accel ##### setup-python-3.9.1-macosx-11-x86_64: extensions from 'src/rl_addons/rl_accel' ##### setup-python-3.9.1-macosx-11-x86_64: ================================================ ##### setup-python-3.9.1-macosx-11-x86_64: =================================================== ##### setup-python-3.9.1-macosx-11-x86_64: Attempting build of _renderPM ##### setup-python-3.9.1-macosx-11-x86_64: extensions from 'src/rl_addons/renderPM' ##### setup-python-3.9.1-macosx-11-x86_64: =================================================== ##### setup-python-3.9.1-macosx-11-x86_64: will use package libart 2.3.21 !!!!! cannot find ft2build.h ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django when running tests ValueError: Related model cannot be resolved. Related to previous migrations issue
Had an issue with django migration files not syncing with the db (was getting column not found) due to a Model being renamed. I don't completely understand migrations but after following different stackoverflow answers - performing fake zero migrations and then adding the manual migration file: # Generated by Django 4.1 on 2022-10-10 00:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('campaigns', '0015_blah_blah'), ] operations = [ migrations.RenameModel("PreviousModelName", "ModelName") ] I thought the issue had been fixed. I can query the database without errors, I can add new fields to the renamed model and migrate them. Everything seemed to be working. But now I've realised that when I run python manage.py test I get the following error: Traceback (most recent call last): File "/code/manage.py", line 25, in <module> main() File "/code/manage.py", line 21, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.9/site-packages/django/test/runner.py", line 1045, in run_tests old_config = self.setup_databases( File "/usr/local/lib/python3.9/site-packages/django/test/runner.py", line 941, in … -
Django inspectdb for Oracle
I am doing a project and need retrieve tables/models from a Oracle database(version 19c). So I am trying to use Django ‘inspectdb’ to do this. – my settings.py looks like: import cx_Oracle cx_Oracle.init_oracle_client(lib_dir=“/opt/oracle/instantclient_21_7”) DATABASES = { ‘default’: { ‘ENGINE’: ‘django.db.backends.oracle’, ‘NAME’: ‘service name’, ‘USER’: ‘XXX’, ‘PASSWORD’: ‘XXX’, ‘HOST’: ‘’, ‘PORT’: ‘’, ‘OPTIONS’: { ‘threaded’: True, ‘use_returning_into’: False, }, } } – Running these followings in shell are all good: import cx_Oracle dsn_tns = cx_Oracle.makedsn(‘Host Name’, ‘Port Number’, service_name=‘Service Name’) conn = cx_Oracle.connect(user=‘User Name’, password=‘Personal Password’, dsn=dsn_tns) c = conn.cursor() c.execute(‘select * from schema.table’) for row in c: print (row) Issues: But when I try using : python3 manage.py inspectdb schema.table It returns error : "The error was: ORA-00942: table or view does not exist " Could anyone help me? thanks alot! -
How to solve ProgrammingError "relation "django_session" does not exist" when using Django with Heroku
I have looked at different threads on here and can't seem to find the solution. It's presenting itself like its an error in the heroku code (I know its not, I've done something wrong), regardless I am very stuck. I have deployed the django project with sqlite3, no issues and am currently trying to convert it postgreSQL. My Settings File: from pathlib import Path import os import django_heroku import dj_database_url from decouple import config import dj_database_url import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # .env configuration: dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! #SECRET_KEY = 'django-insecure-#r@o%yo-#92(0*j%9vn*9l7itkd50l7wadkc=55p$wd46ljl5-' with open('secret_key.txt', 'r') as f: SECRET_KEY = f.readline().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'core.apps.CoreConfig', 'files.apps.FilesConfig', 'django_unused_media', ] AUTH_USER_MODEL = 'accounts.User' LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = "/" MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = … -
How to modify this django Model to create single table in database?
backend.py from storages.backends.s3boto3 import S3Boto3Storage class PublicStorage(S3Boto3Storage): location = getattr(settings,'PUBLIC_FILES_LOCATION','PUBLIC_URL') default_acl = 'public-read' file_overwrite = False custom_domain = False class PrivateStorage(S3Boto3Storage): location = getattr(settings,'PUBLIC_FILES_LOCATION','PRIVATE_URL') default_acl = 'public-read' file_overwrite = False custom_domain = False Model.py from django.db import models from django.conf import settings from accounts_engine.models import CustomUser from Main.aws.backend import * class Template_Core(models.Model): user = models.ForeignKey(CustomUser,on_delete=models.CASCADE) original_filename = models.CharField(max_length = 500) TEMPLATE_TYPE_LIST = [ ('0','Private'), ('1','Public'), ('2','Shared'), ] template_type = models.CharField(max_length=15,choices=TEMPLATE_TYPE_LIST,default='Public') VIEW_TYPE_LIST = [ ('0','Edit'), ('1','Import'), ] view_type = models.CharField(max_length=10,choices=VIEW_TYPE_LIST,default='Import') template_name = models.CharField(max_length=255,default='mytemplate',null=False) template_description = models.CharField(max_length=500) creation_date = models.DateTimeField(auto_now_add=True) class Meta: abstract = True #class created for path to store path in db and also call public and private storage class based on requirement. class Template_Public(Template_Core): path = models.FileField(storage = PublicStorage()) class Template_Private(Template_Core): path = models.FileField(storage = PrivateStorage()) I don't want seperate class (Template_public,Template_private) because it's creating seperate table in db. How to modify this model.py file so that only one table can be created and path constructer can also be called for public and private storage. -
Django Fobi - runserver URL (http://127.0.0.1:8000/) Page Not Found
In order to be able to quickly evaluate the django-fobi, a demo app (with a quick installer) has been created (works on Ubuntu/Debian, may work on other Linux systems as well, although not guaranteed). Follow the instructions below for having the demo running within a minute. Grab the latest django_fobi_example_app_installer.sh: wget https://raw.github.com/barseghyanartur/django-fobi/stable/examples/django_fobi_example_app_installer.sh Assign execute rights to the installer and run the django_fobi_example_app_installer.sh: chmod +x django_fobi_example_app_installer.sh ./django_fobi_example_app_installer.sh Open your browser and test the app. Dashboard: URL: http://127.0.0.1:8001/fobi/ Admin username: test_admin Admin password: test Django admin interface: URL: http://127.0.0.1:8001/admin/ Admin username: test_admin Admin password: test After running all these command and also pip install django-fobi, the result of the runserver website url was 'Page Not Found'. But there are no pending migrations, and everything working normally. Also the urls.py seems to be okay. Can anyone solve this? thx -
Automatically fill in the user field in Models Django
After creating the user field in models.py, how can you make it fill itself by detecting the user by itself? -
Django Websocket getting slow as the connected users increases
I am using Django Channels to send messages to the frontend. and the frequency of the messages is one message per second, everything works fine when I am working on local but on production where I used Nginx, Gunicorn and Daphne to host the server, the connection to the websocket happened after 2-3 attempts, and after the webscokets get connected the messages started coming really slow. Is this issue is related to the server or with the code. Thank you !!! -
How can I redirect this to a slug url in django?
So I have one detail view and one function in my views.py. So i have included the form in detail view template list_detail.html. and upon posting the form successfully. It redirects to all page(homepage basically). Now I want it to redirect to detailview page which is like this. and for that I need to pass the slug value of that List models specific object. But can build the logic here. I am new to django. path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'), path('all',views.all, name='all'), path('create_comment',views.create_comment, name='create_comment'), class TheirDetailView(DetailView): model = List def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) modell = Review.objects.all() context["modam"] = modell context["form"] = ReviewForm() return context def create_comment(request): context = {} form = ReviewForm(request.POST or None) if form.is_valid(): form.save() return redirect('app:all') else: context['form'] = form return render(request, "app/create_comment.html", context) -
Create a Telegram bot inside my website in Django
I will be deploying a website in a few days and I would like to know if it is possible to run a Telegram bot together with my website. Because? This way, I would take better advantage of Django's ORM and would not need to create separate queries to the Database, since my Bot will provide information according to the client's wishes. Is there a library for this or could you create a separate code and run with Celery? -
Hi My Django Forms.cleaned_data is not giving me any output. Can someone help me?
I am trying to create a page to generate passwords and the user will select either level 0 or level 1 for varying strengths of the password. And I am not able to get the users selection of level 0 or level 1 using the radio button. My views.py from django.shortcuts import render import random import string from types import NoneType from random_word import RandomWords from .forms import CHOICES def password(request): passw = passGenAdvanced() form = CHOICES(request.POST) if form.is_valid(): selected = form.cleaned_data.get("password") print(selected) return render(request, 'generator/password.html', {"password":passw}) My forms.py from django import forms password = [('0','Level 0'), ('1', 'Level 1')] class CHOICES(forms.Form): password = forms.ChoiceField(choices=password, widget=forms.RadioSelect) My html file {% extends 'generator/base.html'%} {% block content %} <style> .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } </style> <form method = "POST"> {% csrf_token %} <div class="form-check"> <input class="form-check-input" type="radio" name="password" id="Level0"> <label class="form-check-label" for="password">Level 0</label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="password" id="Level1"> <label class="form-check-label" for="password">Level 1</label> </div> <button type="submit" class="button">Submit</button> </form> <h5 class="alert alert-success">Your Generated Password: <strong>{{password}}</strong></h5> {% endblock %} Sorry if the problem may seem obvious, I am new to django. -
Djano error :TypeError: Object of type CharField is not JSON serializable.Thanks in Advance
**models.py** from django.db import models class Identity(models.Model): first_name=models.CharField(max_length=40,null=True,blank=False), last_name=models.CharField(max_length=40,null=True,blank=False), def __str__ (self): return self.first_name **serializers.py** from rest_framework import serializers from .models import Identity class IdentitySerializer(serializers.ModelSerializer): class Meta: model = Identity fields=('first_name','last_name',) **views.py** from rest_framework import generics from .models import Identity from .serializers import IdentitySerializer class IdentityList(generics.ListCreateAPIView): queryset=Identity.objects.all() serializer_class=IdentitySerializer class Identity(generics.RetrieveUpdateDestroyAPIView): queryset=Identity.objects.all() serializer_class=IdentitySerializer **Application** **urls.py** from django.urls import path,include; from App import views urlpatterns = [ path('identity', views.IdentityList.as_view()), path('<int:ik>/', views.Identity.as_view()), ] **Project** **urls.py** from django.contrib import admin from django.urls import path, include from rest_framework.schemas import get_schema_view from django.views.generic import TemplateView urlpatterns = [ path('', include('App.urls')), #path('', admin.site.urls), path('openapi', get_schema_view( title="Service", description="API development" ), name='openapi-schema'), path('docs/', TemplateView.as_view( template_name='documentation.html', extra_context={'schema_url':'openapi-schema'} ), name='swagger-ui'), ] **setting.py** """ Django settings for solutionOne project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-72^br23d)5w=bk6q_7s)88u)ld!9yrpwzyv*vsn5qmpbts(_m-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = … -
Filtering the last Query Created and Iterating through manytomany relationship in a Django Project
I have the following model: class Log(models.Model): log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') In my view I am trying to get the very last create ActiveSession which has a many to many relationship with Log model to iterate between them. This is how I created the views: def get_context_data(self, **kwargs): active_session =ActiveSession.objects.get(id=ActiveSession.objects.last().id) context = super().get_context_data(**kwargs) return context I think my problem is with the get i tried using filter(id=id).latest but it did not work. here is the template: {% for x in active_session %} {{ x.log_order }} {% endfor %} I am currently getting TypeError: 'ActiveSession' object is not iterable my question: How to fix this error and how can I use the for loop in the template to display the details of each Log which is inside each ActiveSession. In this example there are 3 Logs inside the Active session and I want to show the log_order of each -
jQuery onclick event doens't work on the first click
So my problem is that I created a jQuery function to open menu on button click. Menu code is located on another html template of my Django project, and what happens is that the menu doesn't open at the first click, but works after second. I also included part that changes the span element of the button which works from the first click. Here is my snippet for the jQuery: <script> $(document).ready(() => { $('#btn').on('click', function () { var thisElement = $(this); var buttonSpan = thisElement.find('span'); var menu = $("#menu"); if(buttonSpan.text() === "Close"){ buttonSpan.text('Open'); menu.css('width', '0'); } else { if(buttonSpan.text() === "Open"){ buttonSpan.text('Close'); menu.css('width', '20%'); } } }) }) </script> There is no any scripts on my html where the menu is located, it is just basic div with id 'menu'. But like I said, it should work as it opens at the second click. I think this is something to do with eventlistener as I read something about it, but I couldn't make a sense of it in a perspective of my problme. Also tried to change (document).ready(() => { to (document).ready(function() {, but it didn't do the trick. Is there somethign clear that I am missing? -
GridLayout not not containing generated cards in for loop
I want to make a gridlayout of cards in html that stores a bunch of cards generated using information I pull from a database. project_photo is an array of image file paths that are referred to generate the cards within the for loop. However, when I run it the gridlayout (named card-grid) only contains the first card that is generated from the for loop. Is there any way to make it so that it contains all the cards generated from the for loop? <div class="card-grid"> {% for project in context %} {% with 'jweb/images/'|add:project.image as project_photo %} <div class="card"> <h2 class="card-header" style="text-align:center">{{project.title}} <div class="card-image"> <img src="{% static project_photo %}" style="float:left"> </div> </h2> </div> </div> </div> -
nginx is giving 502 Bad Gateway, with user www-data and works when user is root
trying to debug this for the last two days, but I could not figure out what's wrong these are my permissions for the socket file srw-rw-rw- 1 www-data www-data 0 Oct 10 02:48 cafe.sock and my nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; with this conf I am getting this error "502 bad gateway" cafe.sock failed (13: Permission denied) while connecting to the upstream, client: 106.217.200.51, server: 65. 2.186.229, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://unix:/home/ubuntu/lakegarden/cafe.sock:", host: "65.2.186.229", referrer: "http://65.2.186.229/admin/" after changing user root; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; it is working fine, I can see the admin panel, but read it in SO that we should not have root as a user for security reasons. is there something that i am missing. thank you -
'AppSettings' object has no attribute 'STORE_TOKENS'
I have Object: AppSettings in app_settings.py class AppSettings(object): def init(self, prefix): self.prefix = prefix def _setting(self, name, dflt): from django.conf import settings getter = getattr( settings, "ALLAUTH_SETTING_GETTER", lambda name, dflt: getattr(settings, name, dflt), ) return getter(self.prefix + name, dflt) @property def STORE_TOKENS(self): return self._setting("STORE_TOKENS", False)` And when it get requested in my models.py by: if app_settings.STORE_TOKENS and self.token and self.token.app.pk: getting attribute error saying! 'AppSettings' object has no attribute 'STORE_TOKENS' Any input will be highly appreciated! -
Django Models create product bundle
I have a products model class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=8, decimal_places=2) weight= models.PositiveIntegerField(default=454) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="product_brand", blank=True, default=1) flavour = models.CharField(max_length=200, blank=True) discription = models.TextField(default='') image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url Now I want to be able to create a bundle of let's say, buy 5 items for £ 10. In the shopping cart, it will be added as a 5 X Multibuy. So I have another model called Multibuy class Multibuy(models.Model): name = models.CharField(max_length=200, default='Multibuy') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="multibuy_brand", blank=True, default=1) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) max_items = models.IntegerField(default=8, null=True, blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) I am curious to know if there is a better way to do this. For example, write a decorator in the products model, and do away with the Multibuy model. Bearing in mind that the price and the quantity of the bundles for different products will be different and the admin needs to add that and may want to alter it later.