Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add 0.17 value to database in condition Django
I'm working on django-form project with some customer detail, all things are good condition work properly but a value of tax 0.17 is not added in tax column, tax column still show NULL value in database and all other value added successfully, I use checkbox in tax field in my html form I want if taxamount == ['0.17'] a value 0.17 is added in tax column else 0 added in tax column with other value (print function is just use to check that my condition is working or not but condition work properly) models.py class CustomerDetail(models.Model): customer_name = models.CharField(max_length=200) customer_number = models.CharField(max_length=200) Ship_No = models.IntegerField(primary_key=True) Cell_qty = models.FloatField(null=True, blank=True) Cell_price = models.FloatField(null=True, blank=True) thimble = models.FloatField(null=True, blank=True) thimble_price = models.FloatField(null=True, blank=True) tax = models.FloatField(null=True, blank=True) DatePur = models.DateTimeField(auto_now_add=True) Description = models.CharField(max_length=200, null=True, blank=True) view.py def addcustomer_view(request): if form.is_valid(): taxamount = request.POST.getlist('taxamount') if taxamount == ['0.17']: print('Tax added to database') CustomerDetail.tax = 0.17 else: print('Tax not added to database') CustomerDetail.tax = 0 form.save() return render(request, "customer.html") or is there any other way if checkbox is checked add 0.17 value to database otherwise add 0 to database in tax column -
remove Decimal like we remove 'u' for unicode how can we remove Decimal for the above problem
({'user__username': u'allen.davoudpour@compass.com', 'total': Decimal('599.97'), 'user__company__name': u'Allen Davoudpour', 'reference': u'1143001681', 'product__group__name': u'Property Video'}, {'user__username': u'Ross.McGinley', 'total': Decimal('150.00'), 'user__company__name': u'Slater Hogg Cumbernauld ', 'reference': u'4011416', 'product__group__name': u'Property Video'}) -
Bespoke form on Django - dropdown menu matching models choices
I am creating a form with all sorts of headers and question before each field. I initially create a form in Forms.py, but it seems quite difficult to customise it the way I want it. I resorted to build the form in the html template. I am struggling to create a drop down menu. In this example, when selecting the colour, users would have 4 choices listed in the choices in models.py. I am clearly not linking the form in the template to the actual form. What am I doing wrong? Here is the code Models.py LOOKCOLOUR=( (1,'Straw'), (2,'Yellow'), (3,'Gold'), (4,'Amber'), ) class ChampageRating(models.Model): user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="champcomments", on_delete=models.CASCADE) look_colour=models.IntegerField(choices=LOOKCOLOUR, default=0) .. def __str__(self): return '%s - %s - %s'%(self.user, self.product, self.date_added) forms.py class ElderFlowerChampForm(ModelForm): class Meta: model = ChampageRating fields = ('look_colour', ) labels ={ 'look_colour': 'Colour', } widgets = { 'look_colour':forms.Select(attrs={'class':'form-control'}), } views.py def elderflowerchamp(request, product_id): global ChampageRating product = Product.objects.get(pk=product_id) url = request.META.get('HTTP_REFERER') submitted = False try: if request.method == "POST": reviews = ChampageRating.objects.get(pk=product_id) if request.user.is_superuser: form = ElderFlowerChampFormAdmin(request.POST, instance=reviews) if form.is_valid(): form.save() return redirect('home') else: form = ElderFlowerChampForm(request.POST, instance=reviews) if form.is_valid(): ChampageRating = form.save(commit=False) ChampageRating.user = request.user ChampageRating.save() return redirect('home') else: #This part goes to … -
Heroku CLI error, can't access my django admin
I have deployed my backend of webproject through Heroku CLI. To access my database, I went through herokuapp.com/admin, but I got Internal Servor Error. So, I went to cmd to run heroku run bash command so that I can run migrations, but its showing this error. enter image description here My frontend which is in Next.js is deployed on Vercel and it shows my website. Just that I want to access my database to add data, and Heroku is giving me Problems. My database is Postgres. -
Change verbose name and help text on Django Admin Page
i'm developing a django site deployed via Nginx and PostgreSQL. I did some changes to my models.py and admin.py pages to correct a field. Yet this change is not being shown in my Django admin page, it's still with the old field names regardless of the change in my models.py folder. Here's the models.py and admin.py sections of code models.py title = models.CharField(max_length=100, help_text="Titulo del Proyecto", verbose_name="Titulo") subtitle = models.CharField(max_length=100, help_text="Subtitulo", verbose_name="Subtitulo") image = models.ImageField(upload_to='media/images',blank=True, help_text="Imagen del Proyecto", verbose_name="Imagen") slug = models.SlugField(max_length=100, help_text="No tocar", verbose_name="Slug") description = models.TextField(help_text="Descripcion del Proyecto", verbose_name="Descripcion") date = models.DateField() video_url = models.CharField(max_length=200, blank=True,help_text='Url del video ', verbose_name='Video URL') source = models.ForeignKey('Source', on_delete=models.CASCADE,blank=True, help_text='Youtube o Vimeo o NONE si no hay video',verbose_name='Source') category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, help_text='Categoria del projecto', verbose_name='Categoria') admin.py class ProjectAdmin(admin.ModelAdmin): pass list_display = ('title', 'date', 'category', 'source') list_filter = ('date', 'category', 'source') search_fields = ('title', 'description') ordering = ['-date', 'title'] date_hierarchy = 'date' fieldsets = ( (None, { 'fields': ('title','subtitle', 'description', 'image', 'date', 'video_url', 'source', 'category', 'slug') }), ) prepopulated_fields = {'slug': ('title',)} -
include tag vs block tag. The differences
What is the difference between the include tag and the block tag? In my opinion, it is much easier to use the include tag instead of the block tag. -
Increment Last Id from String in python Django
I am trying to generate auto increment number as a ID with Company Label. Company Label will be changes for every user. So I cant use slicing here. My ID is like TES-PRODUCT-01 TES is company label PRODUCT is as it is name But now I wish to change my last number when I am adding new product to TES-PRODUCT-02 and so on Getting Error can only concatenate str (not "int") to str Here is my code views.py def add_new_stock(request): stock_data=New_Stock_Entry.objects.all() if not stock_data: latest_item_code="TES-PRODUCT-001" else: latest_item_code = (New_Stock_Entry.objects.last()).item_code+1 get_tax_code=Tax_Settings.objects.values('name', 'tax_percentage','tax_id') if request.method == 'POST': item = request.POST['item'] hsn = request.POST['hsn'] item_code=latest_item_code stock_in_date=request.POST['stock_in_date'] quantity_in_hand=request.POST['quantity_in_hand'] sales_price=request.POST['sales_price'] item_description=request.POST['item_description'] unit=request.POST['unit'] tax_code = request.POST['tax_code'] tax_obj = Tax_Settings.objects.get(tax_id=tax_code) item_creation_details = New_Stock_Entry.objects.create(item=item, hsn=hsn, item_code=item_code,stock_in_date=stock_in_date,quantity_in_hand=quantity_in_hand,sales_price=sales_price ,item_description=item_description, unit=unit, tax_code=tax_obj) item_creation_details.save() print("item_details",item_creation_details) return render(request,"inventory/add-stock.html") return render(request,"inventory/add-stock.html",{'get_tax':get_tax_code,'latest_item_code':latest_item_code}) html <input type="text" class="form-control" placeholder="TES-PRODUCT-{{latest_item_code}}" name="item_code"> How Can I increment my last number from string? -
Why is Arrays.find() returning undefined in this situation?
I am following a Python/Django tutorial and the frontend part is done using React. I've reached a point where we're building reducers and actions and using Redux but while building the shopping cart I've reached a dead-end. Here is my reducer: import { CART_ADD_ITEM } from "../constants/cartConstants"; export const cartReducer = (state = { cartItems: [] }, action) => { switch (action.type) { case CART_ADD_ITEM: const item = action.payload; const existItem = state.cartItems.find((x) => {return x.product === item.product}); if (existItem) { return { ...state, cartItems: state.cartItems.map((x) => x.product === existItem.product ? item : x ), }; } else { return { ...state, cartItems: [...state.cartItems, item], }; } default: return state; } }; The 'existItem' variable comes off as undefined, and I am expecting a boolean value. First, 'existItem' used to look like this const existItem = state.cartItems.find((x) => x.product === item.product); I read here about how to fix this issue but that didn't seem to make a difference. Whenever existItem is undefined I basically cannot keep adding items to my shopping cart and I cannot dynamically change their quantities. Where am I going wrong with this? -
Why doesn't my CSS style sheet link to my HTML template?
One of my HTML templates that extends the layout.html template has a CSS file linked to it but when I try to style the HTML content through the CSS file, nothing happens even after reloading. There is already a CSS file linked to the layout.html file but that does not style the page either. How do I make the style.css file style the new.html file (the page that should be styled)? Or should I make a new CSS file to style the new.html file? layout.html: {% load static %} <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> {% block style %}{% endblock %} </head> <body> {% block body %} {% endblock %} </body> new.html: {% extends "encyclopedia/layout.html" %} {% load static %} {% block title %} New Entry {% endblock %} {% block style %} <link href="{% static 'encyclopedia/new.css' %}" rel="stylesheet"> {% endblock %} {% block body %} <form action=""> <input type="text" name="title" class="title" placeholder="Title"> <textarea name="content" class="content" cols="30" rows="10" placeholder="Enter Content"></textarea> <input type="submit" value="Save" class="save"> </form> {% endblock %} style.css: /* styling for the layout page */ body { margin: 0; background-color: white; } code { white-space: pre; } … -
Trying to access a file in a subfolder in link django html
Lets say i have a file style.css which is located at TemplateData folder . Im currently recreating the path but problem is the parent folder of TemplateData is dynamically changing. So lets say i have : user/42/TemplateData/style.css or it could be user/66/TemplateData/style.css . How do i make the path so it can pass the number ? Im currently using : <link rel="stylesheet" href="{{ request.scheme }}://{{ request.get_host }}/{{ application.gameDirectory }}TemplateData/style.css"> and i am missing one folder between {{gameDirectory}} and TemplateData. -
Rendering Values in Html using Python Django
** HTML FILE ** {% extends 'shop/layouts/main.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-12"> <h1>Collections</h1> {% for item in items %} {{ item.name }} {% endfor %} </div> </div> </div> {% endblock content %} ** VIEWS.PY FILE ** from django.shortcuts import render from . models import * def collections(request): items = Product.objects.all() return render(request, "shop/collections.html", {"Item": items}) I need an help that I couldn't load my {items} on html it simply shows nothing in the output -
CORS Error when calling API from Lambda Custom Domain
I have a django backend that allow 2 domains(I am using django-cors) https://xxxxxx.execute-api.us-east-2.amazonaws.com https://mycustomdomainname.com When accessing the website through https://xxxxxx.execute-api.us-east-2.amazonaws.com the API calls work as expected. But when I access on my custom domain, I get CORS error Access to XMLHttpRequest at 'https://cool.api/api/v1/' from origin 'https://mycustomdomainname.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
dj-rest-auth registration fetch
Using dj-rest-auth for user auth and registration on my react app. Got login and logout to work using api endpoints in the docs. Failing to register a user, getting HTTP bad request 400. Reading on the web, explains that there's something wrong with my request but cannot figure what: register.js fetch('/api/dj-rest-auth/registration/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user: 'alalala', password1: '1234', password2: '1234', email: 'ala@gmail.com', }) }) .then(res => { res.json() }) settings.py SITE_ID = 1 CORS_ORIGIN_ALLOW_ALL = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'api.serializers.CustomRegisterSerializer' } INSTALLED_APPS = [ #local 'api', # 3'rd party apps 'rest_framework', 'corsheaders', 'rest_framework.authtoken', 'dj_rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', # added django but it disable admin login logout pages 'django.contrib.sites', # django default... ] serializer.py class CustomRegisterSerializer(RegisterSerializer): def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'password2': self.validated_data.get('password2', ''), 'email': self.validated_data.get('email', ''), } -
Django registration different type users with different fields
I need to create two different users: Gym and Client. The client should theoretically be connected by a many-to-many bond because he can be enrolled in multiple gyms. My doubt is about user registration. I found this around: class User(AbstractUser): is_gym = models.BooleanField(default=False) is_client = models.BooleanField(default=False) class Gym(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_gym = True class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gyms = models.ManyToManyField(Gym, related_name='clients') user.is_client = True @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.is_gym: Gym.objects.create(user=instance) elif instance.is_client: Client.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): if instance.is_gym: instance.gym.save() elif instance.is_client: instance.client.save() My doubts are two: If I wanted to register users with a button "I am a gym" or "I am a customer" with this code, theoretically I could not do it because User class differs, the gym does not have a surname for example. With this code I should create the Gym and Client class populated at a later time so I should make a second form after verifying the account. -
how do I solved a super(type, obj): obj must be an instance or subtype of type type error?
I'm trying to run a test on my app's index.html and here I have: test.py class IndexTest(TestCase): def setUp(self): url = reverse ('index') self.response = self.client_class.get(self, url) and I get this traceback error Traceback (most recent call last) ... File "...\django\test\client.py", line 836, in get response = super().get(path, data=data, secure=secure, **extra) TypeError: super(type, obj), obj must be an instance or a subtype of type I don't know how to go about this -
Filter Field In Object Where Field Has Many Choices
How can I show a list in object.filter()? When I load the page I'm only getting the queryset2 print to show a post. Which makes sense. but why does the queryset and queryset1 not show the posts with these categories? models.py class Post(models.Model): ANALYSIS = "Analysis" MILESTONE = "Milestone" FEATURES = "Features" TUTORIALS = "Tutorials" CAREERS = "Careers" COMMUNITY = "Community" CATEGORY_CHOICES = [ (ANALYSIS, 'Analysis'), (MILESTONE, "Milestone"), (FEATURES, "Features"), (TUTORIALS, "Tutorials"), (CAREERS, "Careers"), (COMMUNITY, "Community"), ] user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=125) body = RichTextUploadingField(blank=True, null=True) category = models.CharField( max_length=20, choices=CATEGORY_CHOICES, default="watchlist" ) views.py class BlogFilterView(LoginRequiredMixin, FilterListViewDate): model = Post filterset_class = PostFilter template_name = "dashboard/blog_filter.html" paginate_by = 5 def get_queryset(self): # categories = ["ANALYSIS", "MILESTONE", "FEATURES", "TUTORIALS", "CAREERS", "COMMUNITY",] categories = ["Analysis", "Milestone", "Features", "Tutorials", "Careers", "Community",] queryset = Post.objects.filter(category__icontains=categories) print("queryset =", queryset) queryset1 = Post.objects.filter(category__icontains="Analysis").filter(category__icontains="Milestone") \ .filter(category__icontains="Features").filter(category__icontains="Tutorials") \ .filter(category__icontains="Careers").filter(category__icontains="Community") print("queryset1 =", queryset1) queryset2 = Post.objects.filter(category__icontains="Community") print("queryset2 =", queryset2) return queryset -
Limit choices to m2m field of a foreign_key
I have these models class SubjectTeacher(models.Model): teacher = models.ForeignKey(TeacherProfile, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) SEMESTER_CHOICES = [("1st", "First Quarter"), ("2nd", 'Second Quarter'), ('3rd', 'Third Quarter'), ('4th', 'Fourth Quarter')] semester = models.CharField(choices = SEMESTER_CHOICES, default = "1st", max_length=3) students = models.ManyToManyField(StudentProfile, related_name="subjects") def __str__(self): return f'{self.subject.subject_name} | {self.teacher.user.first_name}' class Meta: constraints = [ UniqueConstraint(fields = ["teacher", "subject"], name = "Unique Subject Teacher") ] class StudentGrade(models.Model): subject_teacher = models.ForeignKey("SubjectTeacher", on_delete=models.CASCADE) student = models.ForeignKey('StudentProfile', on_delete=models.CASCADE) grade = models.IntegerField() now I want StudentGrade.student to be based on what is selected (in django-admin) on the StudentGrade.subject_teacher Example: subject_teacher = <subject1> <subject2> selected: <subject1> student = choices from <subject1>.students I already tried looking on similar cases such as editing the ModelForm but I couldn't get the gist of it. -
how to select a specific part of a string Django?
I have strings in the database that are the names of countries and cities for example like this: Italy-Milan OR France-Paris. How can i select only the city part, like select what comes only after the '-' using python? -
Steps to perform after updating nginx config - Django
I run a django+nginx+wsgi app in Ec2. App was working fine until I changed server_name in nginx.conf since I had to stop and start Ec2. After updating the server_name, app was broken I tried symlinking sites-available and sites-enabled I restarted nginx, gunicorn process and supervisord I deleted the app.sock file and recreated it using commands But Stil app is broken Here are my files django.conf(/etc/nginx/sites-available/django.conf) server { listen 80; server_name <public_ip>; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/degrep-v2-base/app.sock; }} gunicorn.conf(/etc/supervisor/conf.d/gunicorn.conf) [program:gunicorn] directory=/home/ubuntu/degrep-v2-base command=/home/ubuntu/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/degrep-v2-base/app.sock degrep_v2.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn If im updating nginx.conf in future, what all steps I need to perform for no downtime? -
How to aggregate the sum of a class model field in django
I've been attempting unsuccessfully to show the total_net_profit on my dashboard. I think there is a problem with my strategy. Does anyone have a solution to this issue? Model class Investment(models.Model): PLAN_CHOICES = ( ("Basic - Daily 2% for 182 Days", "Basic - Daily 2% for 182 Days"), ("Premium - Daily 4% for 365 Days", "Premium - Daily 4% for 365 Days"), ) plan = models.CharField(max_length=100, choices=PLAN_CHOICES, null=True) principal_amount = models.IntegerField(default=0, null=True) investment_id = models.CharField(max_length=10, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) due_date = models.DateTimeField(null=True, blank=True) def daily_interest(self): if self.plan == "Basic - Daily 2% for 182 Days": return self.principal_amount * 365 * 0.02/2/182 else: return self.principal_amount * 365 * 0.04/365 def net_interest(self): if self.plan == "Basic - Daily 2% for 182 Days": return self.principal_amount * 365 * 0.02/2 else: return self.principal_amount * 365 * 0.04 def total_net_profit(self): return self.Investment.aggregate(total_net_interest=Sum('net_interest'))['total_net_interest'] -
How to unittest AWS Stack (coming from Django)?
I am coming from Django stack and now I am on AWS and I have problem with testing my code which use a lot of AWS Stack. With Django, when you run a test, a temporary database is created and migration applied. How to do that when testing the unnittest I am writing for AWS ? Is there any way to simulate the behaviour of AWS component like SQS, Lambda invoke, etc. I am coming in the Django world and you could test everything you want without problem but now it seems like very complicated. Thanks for you help -
Django - form object has no attribute 'status_code'
I am new to Django and working on forms. I got this error message File "C:\Users\foo\what\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\foo\what\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\foo\what\lib\site-packages\django\middleware\common.py", line 108, in process_response if response.status_code == 404 and self.should_redirect_with_slash(request): AttributeError: 'Product' object has no attribute 'status_code' models.py class Product(models.Model): product_name = models.CharField(max_length=100) product_price = models.IntegerField() product_photo = models.ImageField(upload_to='product_photos', height_field=None, width_field=None, max_length=100) def get(self, request): a = Product() return a forms.py class UploadProduct(ModelForm): product_name = forms.TextInput() product_price = forms.NumberInput() product_photo = forms.FileInput() class Meta: model = Product fields = ['product_name', 'product_price', 'product_photo'] views.py def uploadProduct(request): if request.POST: form = UploadProduct(request.POST) if form.is_valid(): form.save() return redirect(upload_product_ok_page) return render(request, 'upload_product.html', {'form': UploadProduct}) def upload_product_ok_page(request): return HttpResponse('ok') urls.py path('upload_product/', Product), path('upload_product/', views.uploadProduct, name="upload_product"), path('', views.upload_product_ok_page, name='upload_product_ok_page'), upload_product.html <form method="POST" action="{% url 'upload_product' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button>Submit</button> </form> I made sure I imported the correct functions, classes and objects. Thanks in advance. -
How to set up Django i18n on Google App Engine (GAE)?
Using Django 4.0.2, and GAE standard, the site text does not change when a language is selected. The main language is english. The second language is Dutch. If I switch the language, then the url changes and includes /nl instead of en/, but the English text remains. On localhost, the English text is replaced with the Dutch text. I'm using django-rosetta and on GAE its dashboard finds two instances of my application, called workspace/ and srv/. Each contains the same .mo file in the same location /workspace/locale/nl/LC_MESSAGES/django.po. I dont know why there are two applications, or if this is relevant. On localhost, I have one application in the expected location. There are no errors, and checking the existence of the .mo file returns True. My locale directory is in the project root. On local this is my project name, on GAE the name of the project root directory is workspace. This should be fine because building file paths using ROOT_DIR still works as expected for locale settings and also all other settings. The relevant settings are: ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent _locale_dir = ROOT_DIR / "locale" _locale_file = _locale_dir / "nl/LC_MESSAGES/django.po" print(f"--- {_locale_file.is_file() = }") LOCALE_PATHS = [ROOT_DIR / "locale", "/workspace/locale", "/srv/locale"] … -
Django form refused to validate because of Select widget
I have a Django form that refused to validate because of this Select widget, I have tried to debug and found out that the particular form field has been returning None instead of 'Buy' or 'Sell'. I can't seem to figure out what's wrong with my code, albeit I suspect it has something to do with my HTML. models.py class Transaction(models.Model): buy = 'BUY' sell = 'SELL' transaction_choices = [ (buy, 'Buy'), (sell, 'Sell'), ] transaction_type = models.CharField( max_length=4, choices=transaction_choices, default=buy, ) forms.py class UpdatePortfolio(forms.ModelForm): transaction_choices = [ ('BUY', 'Buy'), ('SELL', 'Sell'), ] transaction_type = forms.CharField( max_length=4, widget=forms.Select( choices=transaction_choices, attrs={ 'class': 'form-select', 'name': 'transaction_type', 'id': 'floatingTransaction', }) ) class Meta: model = Transaction fields = ( 'transaction_date', 'symbol', 'transaction_date', 'share', 'avg_price', 'cost_basis', ) def clean_transaction_type(self): type = self.cleaned_data.get('transaction_type') if type != 'Buy' or 'Sell': raise forms.ValidationError(f'{type} is an invalid transaction') return type updateportfolio.html <form action="{% url 'mainpage:update' user.id %}" method="POST"> {% csrf_token %} <div class="row1"> <div class="transaction_type col-6"> <p>Transaction Type</p> <select class="form-select" required> {% for type in form.transaction_type %} <option>{{ type }}</option> {% endfor %} </select> </div> <div class="symbol col-6"> <label for="floatingSymbol" class="form-label">Ticker</label> {{ form.symbol }} <datalist id="tickers"> {% for ticker in tickers %} <option value="{{ ticker.tickersymbol }}"></option> {% endfor … -
I'm not getting any option to select product list in order form
Models.py from django.db import models from re import I from django.utils import timezone from django.dispatch import receiver from more_itertools import quantify from django.db.models import Sum # Create your models here. CHOICES = ( ("1", "Available"), ("2", "Not Available") ) class Brand(models.Model): name = models.CharField(max_length=255) status = models.CharField(max_length=10, choices=CHOICES) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=255) status = models.CharField(max_length=10, choices=CHOICES) def __str__(self): return self.name class Product(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=255) code = models.CharField(max_length=10) #image = models.ImageField(upload_to="media/product/images/") quantity = models.IntegerField() rate = models.FloatField(max_length=100) status = models.CharField(max_length=10, choices=CHOICES) def __str__(self): return self.name class Order(models.Model): date = models.DateTimeField(auto_now_add=True) sub_total = models.FloatField(max_length=100) vat = models.FloatField(max_length=100) total_amount = models.FloatField(max_length=100) discount = models.FloatField(max_length=100) grand_total = models.FloatField(max_length=100) paid = models.FloatField(max_length=100) due = models.FloatField(max_length=100) payment_type = models.CharField(max_length=100) payment_status = models.IntegerField() status = models.IntegerField() class OrderItem(models.Model): order_id = models.ForeignKey(Order, on_delete=models.CASCADE) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() rate = models.FloatField(max_length=100) total = models.FloatField(max_length=100) status = models.IntegerField() views.py from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.template.loader import render_to_string from django.views.decorators.csrf import csrf_exempt import json from .models import Brand, Category, Product, …