Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms AttributeError 'NoneType' object has no attribute 'disabled'
I keep having trouble with a custom Django form that I am trying to implement. I really didn't know any way for getting the data from the frontend besides trying to pull the data by force through request.POST.get(), but once I started doing that I ran into an AttributeError that kept saying 'NoneType' object has no attribute 'disabled', and the error referenced the form.save() line as the problem in my views.py. Here is the code for the views.py @login_required def volunteer_instance_creation(request): form = VolunteerInstanceForm(request.POST or None, request.FILES) values_dict = { "organization": request.POST.get('organization'), "supervisor_Name": request.POST.get('supervisor_Name'), "supervisor_Phone_Number": request.POST.get('supervisor_Phone_Number'), "volunteering_Duration": request.POST.get('volunteering_Duration'), "volunteering_Date": request.POST.get('volunteering_Date'), "description": request.POST.get('description'), "scanned_Form": request.POST.get('scanned_Form'), } for i in values_dict: form.fields[i] = values_dict[i] if form.is_valid: obj = form.save(commit = False) obj.student_id = get_student_id(str(User.objects.get(pk = request.user.id))) obj.grad_year = get_grad_year(str(User.objects.get(pk = request.user.id))) obj.save() return redirect("submission_success") return render(request, "members_only/yes_form.html") Here is my models.py class VolunteerInstance(models.Model): student_id = models.CharField( blank = True, editable = True, default = 'No Student ID Provided', max_length = 255 ) grad_year = models.CharField( blank = True, max_length = 255, default = 'No Graduation Year Provided', editable = True ) organization = models.CharField( blank = False, max_length = 255 ) description = models.TextField( blank = False, ) supervisor_Name = models.CharField( blank … -
Django AbstractBaseUser Authentication-Login
this is my views.py file def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('user_home_url') else: messages.info(request, 'invalid username and password') return redirect('user_login_url') models.py class User(AbstractBaseUser, PermissionsMixin): """Database Model for storing users profile""" first_name = models.CharField(max_length = 15) last_name = models.CharField(max_length = 15) email = models.EmailField(max_length = 35, unique = True) username = models.CharField(max_length = 35, unique = True) is_active = models.BooleanField(default = False) is_staff = models.BooleanField(default = False) password = models.CharField(max_length = 25) phone = models.CharField(max_length = 13, null = False, blank = False, unique = True) phone_verified = models.BooleanField(default = False) otp = models.IntegerField(null = True) objects = UserProfileManager() USERNAME_FIELD='username' REQUIRED_FIELDS=['password','email','phone','first_name','last_name'] def get_full_name(self): """return full name of user""" return self.first_name + self.last_name def __str__(self): """return string representation of user""" return self.email settings.py AUTH_USER_MODEL = 'Users.User' Tried different methods using authenticate method but always getting invalid username and password def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] users = User.objects.all() for user in users: if user.email == email and user.password == password: return redirect('user_home_url') when I use this code in views.py instead of "authenticate" method it's working perfectly but the … -
How to remove catalogue from url string
What are the best method to have this url structure namedomain.com/ instead of namedomain.com/catalogue for Django Oscar. Do I have to create new app call frontpage or can I edit the myshop/urls.py such as this line? path('', include(apps.get_app_config('oscar').urls[0])), -
ValueError at /accounts/register The given username must be set
veiws.py from django.shortcuts import render,redirect from django.contrib.auth.models import User, auth from django.contrib import messages from travello.models import Destination import traceback from django.core.files.storage import FileSystemStorage # Create your views here. def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request,user) return redirect("/") else: messages.info(request,'invalid credentials') return redirect('login') else: return render(request, 'login.html') def register(request): if request.method == "POST": first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 == password2: if User.objects.filter(username=username).exists(): messages.info(request,'Username taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'EMAIL taken') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password1, first_name=first_name, last_name=last_name) user.save(); print("User created") return redirect('login') else: messages.info(request,'password not matching...') return redirect('register') else : return render(request, 'register.html') def logout(request): auth.logout(request) return redirect('/') def postdestination(request): if request.method == 'POST': try: f = request.FILES["img"] fs = FileSystemStorage() filename = fs.save(f.name, f) uploaded_file_url = fs.url(filename) name = request.POST['name'] # img = request.POST['img'] description = request.POST['description'] price = request.POST['price'] offer = request.POST.get('offer') if offer == "on": offer = True else: offer = False d = Destination.objects.create(name=name, desc=description,img=uploaded_file_url,price=price,offer=offer) d.save() except Exception as e: traceback.print_exc() return redirect('/') else: return render(request, 'post_destination.html') while registering this error is coming.how … -
Is it a bad practice not to use django forms?
I have watched a lot of django tutorials where some use the plain html form and some use django forms and model forms. Personally, I like using the plain html form because of the ease of customization. Other than validation, I don't really see any other advantages to using django forms. So, i just wanted to ask if it is a bad practice to use html forms rather than django forms? -
docker and django, DisallowedHost at / Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS
ubuntu 20.04 in the docker container python 3.8 after running the Django server python manage.py runserver In the browser, it said allowed_host I have changed the allowed host, restart the container, restart the django server, but the browser continuesly said "You may need to add '127.0.0.1' to ALLOWED_HOSTS." changed allowed host I have tried ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['127.0.0.1','localhost'] Neither of them worked Also I have tried this which is also not working for me python manage.py runserver --insecure -
Pass a value from view.py to a url link in html
I am working on CS50 Web Development on the lesson of Django. I want to pass a string from view.py to HTML as the URL link here is the view.py def layout(request, name): randompage = random.choice(util.list_entries()) return render(request, "encyclopedia/layout.html", { "randompage": randompage}) and this is the HTML page <a href={% url "wiki/{{randompage}}" %}> Random Page </a> the error code is NoReverseMatch at / Reverse for 'wiki/{{randompage}}' not found. 'wiki/{{randompage}}' is not a valid view function or pattern name. I know I shall you templatetag URL, but I don't really understand how it works and I cant find anyone have a similar situation with me. -
What are the ways to make it possible to change contents of homepage through django admin?
I want to make it possible to easily modify the contents of my django site's homepage(and other pages too) through admin page directly. If I had multiple records of each instance I would definitely create a database model for it, which can then easily be modified through admin panel. But for things like the banner image, site description etc. which only have a single instance, am I supposed to have a database model with a single row or is there some better implementation for it? -
How to upload PDFs in Django-CKEditor?
I am trying to upload PDFs file in CKEditor for Django. Here are my settings in settings.py: CKEDITOR_CONFIGS = { 'default': { 'removePlugins': 'stylesheetparser', # Toolbar configuration # name - Toolbar name # items - The buttons enabled in the toolbar 'toolbar_DefaultToolbarConfig': [ { 'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', "BGColor"], }, { 'name': 'clipboard', 'items': ['Undo', 'Redo', ], }, { 'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', 'Outdent', 'Indent', 'HorizontalRule', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', ], }, { 'name': 'format', 'items': ['Format', ], }, { 'name': 'extra', 'items': ['Link', 'Unlink', 'Blockquote', 'Image', 'Update', 'Table', 'CodeSnippet', 'Mathjax', 'Embed', ], }, { 'name': 'source', 'items': ['Maximize', 'Source', ], }, ], # This hides the default title provided by CKEditor 'title': False, # Use this toolbar 'toolbar': 'DefaultToolbarConfig', # Which tags to allow in format tab 'format_tags': 'p;h1;h2', # Remove these dialog tabs (semicolon separated dialog:tab) 'removeDialogTabs': ';'.join([ 'image:advanced', 'image:Link', 'link:upload', 'table:advanced', 'tableProperties:advanced', ]), 'linkShowTargetTab': False, 'linkShowAdvancedTab': False, # CKEditor height and width settings 'height': '250px', 'width': 'auto', 'forcePasteAsPlainText ': True, # Class used inside span to render mathematical formulae using latex 'mathJaxClass': 'mathjax-latex', # Mathjax library link to be used to render mathematical formulae 'mathJaxLib': 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_SVG', # Tab = 4 spaces … -
Beautiful soup question, for loop problem
#Well this is my code and i have no idea why doesnt it show more results on the page, its grabs the price, link, title but shows 1 result, ident is ok, no erros, tried all the containers from find all , still one result, can you please advise me the mistake.Benn through this for a week import requests from bs4 import BeautifulSoup from django.shortcuts import render from urllib.parse import quote_plus #adding plus sign in search from . import models BASE_URL = 'https://www.olx.ua/list/q-{}' def home(request): return render(request,'base.html') def new_search(request): search=request.POST.get('search') #pull data out of search bar # that post request we are fetching #search model gives to searches to database models.Search.objects.create(search=search) #model creating search object with search argument is search and feeds to search request final_url = BASE_URL.format(quote_plus(search)) # response = requests.get(final_url) data= response.text #spit out text soup= BeautifulSoup(data, features='html.parser') final_postings= [] post_listings = soup.find_all("div", class_="rel listHandler") for post in post_listings: #looping through each post and show text post_titles = post.find('a',class_= ['marginright5 link linkWithHash detailsLink', 'marginright5 link linkWithHash detailsLink linkWithHashPromoted', ]).text post_url = post.find('a',class_= ['marginright5 link linkWithHash detailsLink', 'marginright5 link linkWithHash detailsLink linkWithHashPromoted']).get('href') if post.find('div',class_= 'space inlblk rel'): post_price = post.find('div',class_= 'space inlblk rel').text else: post_price= 'N/A' if post.find('img',class_='fleft').get('src'): post_image= … -
Django admin can't access to specific items
I'm working in Django with a model (Check) with foreign key. client_id = models.ForeignKey(Client, on_delete=models.CASCADE) Everything works fine with a regular admin register, but when I use class ChecksAdminSite, it crashes. Here is the Client model: class Client (models.Model): def __str__(self): return self.name + ' '+ self.surname name = models.CharField(max_length=120) surname = models.CharField(max_length=120, null=True) phone = models.PositiveIntegerField(null=True) mail = models.EmailField(null=True) sport = models.TextField(blank=True, null=True) gender_options=( ("F", "femenino"), ("M", "masculino"), ) gender = models.CharField(max_length=120, null=True, choices=gender_options) birth = models.DateField(null=True) def get_absolute_url(self): return reverse("clientes:cliente", kwargs={"client_id": self.id}) pass So, when I get into the admin specific item, it displays the following error: Field 'id' expected a number but got <Client: Juan Orjuela>. (Juan Orjuela is the name and the surname of that specific item). I just can't seem to find a solution or error. Can someone help me? Thanks! -
Django form missing none required field
I have a django admin form. The model contains a single field, called calculated. The calculated value is detemined by querying the database and performing some complex logic depending on the selection of some other field the user selects from a select box called pickme. So to make it much easier for the user, when they wish to alter an instance of the model, they select a pickme, and the system automatically calculates the required calculated field. The following code works for editing existing entries, however when I add a new entry, when I click save in the django admin interface it fails with ValueError: 'FooForm' has no field named 'calculated'. The error is raised within the Form._post_clean() method. I suspect it is because the form is not posting the value of calculated so it thinks its not a field. Looking at djangos code python3.8/site-packages/django/forms/forms.py, within _post_clean(): There seems to be a block that creates a DB instance: try: self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude) except ValidationError as e: self._update_errors(e) And then a block that cleans the instance, this is where it fails: try: self.instance.full_clean(exclude=exclude, validate_unique=False) except ValidationError as e: self._update_errors(e) I could try override _post_clean but it seems extremely … -
How do I inject an HTML string into executable html with Javascript?
I am using the Django framework to create a web app, and I am passing a variable which is a string of html (like 'hello world') to a template. In my template I create a to inject this string into actual executable html rather than text, which is where my error is occuring. It seems either there is something wrong with my injection code, something wrong with my use of Jinja to import the html string, or that this is the wrong way of doing things. Here is my current code: HTML (Javascript) <script> var htmlWrapper = document.querySelector('#graph_input'); var htmlstring = {{figure}}; htmlWrapper.innerHTML = htmlstring; </script> Views def home(request, symbol): file = open('saved_model_weights', 'r') model_json = file.read() loaded_model = model_from_json(model_json) loaded_model.load_weights('h5_file') predictions = loaded_model.predict(test) fig = Figure() ax = fig.subplots() ax.plot(predictions, linewidth=0.7) ax.plot(close, linewidth=0.7) ax.set_title(symbol) figure = mpld3.fig_to_html(fig) return render(request, 'mysite/home.html', {'figure': figure}) ^ figure is the html string I want to execute in my template, which is generated by mpld3.fig_to_html(), a matplotlib library to translate graphs into. -
ImportError: attempted relative import with no known parent package in Django
I have this folder structure: This is the full error message: Traceback (most recent call last): File "d:\jaime\Coding\Django\MyProjects\horus\app\core\erp\tests.py", line 1, in <module> from .models import Type ImportError: attempted relative import with no known parent package And this is the code: # from .models import Type from app.core.erp.models import Type t = Type(name="aaaa") print(t) And when in the erp tests.py I import my "Type" model, it gives me the title error, I don't understand what is wrong. -
Working wtih django sessions the right way
i was working with Django sessions and it was good until i wanted to modify it and explore it more. i have this code request.session['username_stored_in_session'] = user_name request.session['password_stored_in_session'] = pass_inp where it stores the username and the password on login if the user is using 2fac auth and redirect him to check the 2fac code and use them to auth the user if the code is correct, now i want to set expiry date to those sessions and how to secure them etc cause i'm planing on using them more, i know how to delete them using del and calling them, but not how to use expiry_date() and all the stuff on Django session docs. Thanks. -
Django - MongoDb - GraphQL query returning an empty array
This my first time using graphQL. I'm using django along with mongodb. this is my models.py from djongo import models class Car(models.Model): name = models.CharField(max_length=100) this is my schema.py import graphene from .models import Car from graphene_django import DjangoObjectType class CarType(DjangoObjectType): class Meta: model = Car fields = "__all__" class Query(graphene.ObjectType): allcar = graphene.List(CarType) def resolve_allcar(self, info): return Car.objects.all() schema = graphene.Schema(query=Query) setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'graph', } } after typing the follwing queny in graphql interface query { allcar { name } } the results are the follwing: { "data": { "allcar": [] } } in the terminal i can see : [12/Jun/2021 14:33:49] "POST /graphql HTTP/1.1" 200 22 my mongo database it has two records as mention in the picture bellow -
Heroku redis deployed backend does not cache data
First time deploying app. I'm trying to run my backend on Heroku url example:(this_is_my_app_name.herokuapp.com). I have my database deployed at AWS and connected to my backend. I've tested locally and everything seems to work. But now I have a problem when I'm trying to access my backend admin panel on deployed backend I can't access it with my login information (I can access by creating superuser but theres no data from database). I think it's redis problem and can't configure my redis right. I've tried importing urlparse and using like this : redis_url = os.environ.get('REDISTOGO_URL', 'http://localhost:6959') redis_url = urlparse.urlparse(redis_url) ......... 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), ........ For example this is my local redis cache working locally: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "REDIS_CLIENT_CLASS": "redis.client.StrictRedis", "REDIS_CLIENT_KWARGS": {"decode_responses": True}, # Custom serializer "SERIALIZER": "core.redis.JSONSerializer", }, } } This is my code deployed to Heroku I used this article 'Connecting in Django' (https://devcenter.heroku.com/articles/heroku-redis). I've tried aswell this article (https://devcenter.heroku.com/articles/redistogo#install-redis-in-python) but still it does not work. CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), <-------------------- my change "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "REDIS_CLIENT_CLASS": "redis.client.StrictRedis", "REDIS_CLIENT_KWARGS": {"decode_responses": True}, # Custom serializer "SERIALIZER": "core.redis.JSONSerializer", }, } } -
how to store uploaded files for a web application while using AWS ECS FARGATE
I am very new to the concept of AWS EFS. As i am currently building a web application using Django with ECS - AWS Fargate backend and javascript with react front end, which is deployed to s3. About the backend, I am wondering what would be the best way for a user to: 1/ store/upload the images related to their profile? 2/ assuming the user also own a product in the app and each product has images, how to store these images as well... Would AWS S3 or AWS EFS be the most appropriate way to store 1 and 2 above? Thanks for the feedback -
django Type error 'Bank' model object is not iterbale
i am trying to create list and detail api view. I have database with over 100K object model.py from django.db import models # Create your models here. class Banks(models.Model): name = models.CharField(max_length=49, blank=True, null=True) id = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'banks' class Branches(models.Model): ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=250, blank=True, null=True) address = models.CharField(max_length=250, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) class Meta: managed = False db_table = 'branches' serializers.py from rest_framework import serializers from .models import Branches, Banks class BankSerializer(serializers.ModelSerializer): class Meta: model = Banks fields= ['name', 'id'] class BranchSerializer(serializers.ModelSerializer): bank = BankSerializer(many=True,read_only=True) class Meta: model = Branches fields= ['ifsc','bank','branch','address','city','district','state'] views.py from rest_framework import viewsets from .serializers import BranchSerializer from rest_framework import viewsets class BankViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed. """ queryset = Branches.objects.all() serializer_class = BranchSerializer I tried using .get_queryset(), .filter() in place of .all() but its still throwing error error datail Request Method: GET Request URL: http://127.0.0.1:8000/bankdetailapi/ Django Version: 3.2.3 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'corsheaders', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
Python Django: Django won't render images from a folder outside static
Been working on a Django project for a personal portfolio. Inside the project I have different apps: a blog app and a projects app. When I try to render a images it wont display unless a use a specific path from the templates folder to the static folder. For example, based on my project directory, if I use "../static/img/example.jpg" it renders the image with out problem, but as soon as I use another path like "../../media/img/example.jpg" the image wont render and a blank space will appear. I would like to know id this is normal behavior with Django and if its then what is the best practice to display images, because nothing comes to mind right now.enter image description here -
Cannot close a running event loop
What is the way to close the discord.py bot loop once tasks are done? Added: nest_asyncio.apply() Tried: bot.logout(), bot.close(), bot.cancel() Code: async def helper(bot, discord_user_feed): nest_asyncio.apply() await bot.wait_until_ready() # await asyncio.sleep(10) for each_id, events_list in discord_user_feed.items(): discord_user = await bot.fetch_user(int(each_id)) for each_one in events_list: msg_sent = True while msg_sent: await discord_user.send(each_one) msg_sent = False await bot.close() return 'discord messages sent' async def discord_headlines(request): nest_asyncio.apply() discord_user_feed = await get_details() bot = commands.Bot(command_prefix='!') bot.loop.create_task(helper(bot, discord_user_feed)) message = bot.run('my_token') return HttpResponse(message) I can be able to send messages to discord users using id and discord bot. But, even after, django view api is continuously running and getting the error. It needs to return a response message - discord messages sent. Error: Exception in callback <TaskWakeupMethWrapper object at 0x000001C852D2DA38>(<Future finis...SWdZVtXT7E']}>) handle: <Handle <TaskWakeupMethWrapper object at 0x000001C852D2DA38>(<Future finis...SWdZVtXT7E']}>)> Traceback (most recent call last): File "E:\sd\envs\port\lib\asyncio\events.py", line 145, in _run self._callback(*self._args) KeyError: <_WindowsSelectorEventLoop running=True closed=False debug=False> Internal Server Error: /api/v0/discord_headlines/ Traceback (most recent call last): File "E:\sd\envs\port\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\sd\envs\port\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\sd\envs\port\lib\site-packages\asgiref\sync.py", line 139, in __call__ return call_result.result() File "E:\sd\envs\port\lib\concurrent\futures\_base.py", line 425, in result return self.__get_result() File "E:\sd\envs\port\lib\concurrent\futures\_base.py", line 384, in … -
DRF: Is two sided object creation and relation assignment possible?
For example, I have two models, Questionnaire Model Profile Model These two models are linked by a one-to-one relation, where the one-to-one-field is declared on the questionnaire model. I want to be able to: Create a new questionnaire instance, and assign an existing profile instance to it Create a new profile instance, and assign an existing questionnaire instance to it Currently, because my one-to-one relation is defined on the questionnaire model, I can do 1) However, I am not able to achieve 2) How do i get both 1) and 2) working? Serializer class ProfileCreateSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = "__all__" Models class Questionnaire(models.Model): distance = models.FloatField(null=True) profile = models.OneToOneField("Profile", on_delete=models.SET_NULL, null=True, related_name="questionnaire", blank=True) class Profile(models.Model): bio = models.CharField(max_length=300, blank=True) Views class ProfileCreate(generics.CreateAPIView): queryset = Profile.objects.all() serializer_class = ProfileCreateSerializer permission_classes = [IsAuthenticated] POST Request { "bio": "I like to eat pizza", "questionnaire": 2 } -
django how to merge selling product row if product id and price is same
hi I'm new in Django please anyone help me how to merge the selling product row if the product id and price is the same my deman is bellow seconod image. here is my code: my view method code is: def invoiceTest(request): SaleData = Sales.objects.get(pk=322) SalesDetailsData = SalesDetails.objects.filter(SalesID_id=322) TotalPrice = totalPriceCalculate(request,322) NetAmonut = Decimal(TotalPrice)+Decimal(SaleData.BillVatAmount)-Decimal(SaleData.BillDiscountAmount) ExtraCharge = 0.00 context = { 'SaleData': SaleData, 'SalesDetailsData':SalesDetailsData, 'TotalPrice':TotalPrice, 'NetAmonut':NetAmonut, 'ExtraCharge':ExtraCharge } return render(request, 'Admin UI/Bill Invoice Challan/Bill Invoice.html',context) def totalPriceCalculate(request,SaleID): SalesDetailsData = SalesDetails.objects.filter(SalesID_id=SaleID) TotalAmount = 0.00 for SingleSale in SalesDetailsData: TotalAmount = Decimal(TotalAmount)+Decimal(SingleSale.Qty)*Decimal(SingleSale.UnitPrice) return TotalAmount class SalesDetails(models.Model): SalesID = models.ForeignKey(Sales, null=False, on_delete=models.RESTRICT) Purchase = models.ForeignKey(Purchase, null=False, on_delete=models.RESTRICT) ProductID = models.ForeignKey(Product_Master.ProductList, related_name='ProductID', null=False, on_delete=models.RESTRICT) StoreID = models.ForeignKey(Setup_Master.StoreList, null=False, on_delete=models.RESTRICT) EnterdBy = models.CharField(max_length=250, null=True) EntryTime = models.DateTimeField(auto_now_add=True) EntryDate = models.DateTimeField(auto_now_add=True) EntryDate = models.DateTimeField(auto_now_add=True) Serial = models.CharField(max_length=250, null=True) Qty = models.FloatField(default=1) Warranty = models.CharField(max_length=250, null=True) Cost = models.DecimalField(max_digits=50, decimal_places=2, default=0) AverageCost = models.DecimalField(max_digits=50, decimal_places=2, default=0) UnitPrice = models.DecimalField(max_digits=50, decimal_places=2, default=0) ItemDiscountPercent = models.DecimalField(max_digits=50, decimal_places=2, default=0) ItemDiscountAmount = models.DecimalField(max_digits=50, decimal_places=2, default=0) ItemVatPercent = models.DecimalField(max_digits=50, decimal_places=2, default=0) ItemVatAmount = models.DecimalField(max_digits=50, decimal_places=2, default=0) Approved = models.CharField(max_length=250, null=True,default='NO') Inventory = models.CharField(max_length=250, null=True, default='YES') <div class="row"> <table class="table table-sm table-bordered"> <thead> <tr style="background-color: #e2f0ff"> <th style="width: 40px" scope="col">SL</th> <th scope="col">Description</th> <th style="width: … -
Django how to pass an argument into a form made with Model_FormFactory?
I have an abstract form, that is used as a template form when calling modelform_factory. However this abstract form requires some initialising data, foo. How do I pass the initialising data foo from the concrete class to AbstractForm.__init__? class AbstractForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) foo = kwargs.pop('foo') # Need to get this initialising value self.fields['some_field'] = forms.ModelChoiceField(required=True, queryset=SomeModel.objects.filter(baz=foo).all()) class AbstractAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, change=False, **kwargs): # How to pass self.foo into AbstractForm? form = forms.modelform_factory(self.model, form=AbstractForm, exclude=[]) return form class ConcreteAdmin(AbstractAdmin): foo = 123 -
How to deploy django web App on windows iis server?
i am trying to host django web app on windows iis server and i am having problem with web.config file .the auto generated web.config file doesnot have complete setup ,is there any way to complete this config file manually . django version 3.2.4