Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reopening a closed django InMemoryFileUpload using class based views
I have a Django project which involves a user uploading a CSV file via a form. I parse this file in the forms clean method, and then in the views form_valid method I want to read the file data again (for the purposes of long term storage). My issue is that after parsing the file in the clean method, I'm no longer able to perform IO operations on the file object, any attempt to do so raises an error. Code as below: class MyForm(forms.Form): file = forms.FileField() def clean(self): cleaned_data = super().clean() file = cleaned_data["file"] reader = csv.DictReader(io.TextIOWrapper(file)) for row in reader: ... # process data return cleaned_data class MyView(generic.FormView): form_class = MyForm def form_valid(self, form): file = form.files["file"] file.read() # raises ValueError: I/O operation on closed file. At this point it's no longer possible to call other methods like file.open() either as this leads to the same exception being raised. What I am finding confusing about this is that there are other examples in my application of where IO operations can be performed on the file in the form_valid method, example below: class MyOtherForm(forms.Form): file = forms.FileField() class MyOtherView(generic.FormView): form_class = MyOtherForm def form_valid(self, form): file = form.files["file"] file.read() … -
only a single result allowed for a SELECT that is part of an expression with Django 3.0
I am using Django version 3.0 and Python version 3.7 When trying to save my job i am getting this issue only a single result allowed for a SELECT that is part of an expression Here is my views.py def convert_quote_to_job(request, pk): client = request.user.client quote_data = get_object_or_404(Quote, id=pk, client=client) user = request.user form = ConvertQuoteToJobForm(user=user) if request.POST: dob = request.POST.get('due_date') time_hour = request.POST.get('time_hour') time_minute = request.POST.get('time_minute') assigned_to = request.POST.getlist('assigned_to') maridian = 'AM' if int(time_hour) > 12: time_hour = int(time_hour)-12 maridian = 'PM' if int(time_hour) == 12: maridian = 'PM' form = ConvertQuoteToJobForm(request.POST, user=user) if form.is_valid(): job = form.save(commit=False) job.title = quote_data.job_title job.job_type = JobType.objects.filter(client=client, is_deleted=False).first() job.created_by = user job.contact_info = quote_data.address job.contact = quote_data.contact job.duration = (int(len(assigned_to))*int(request.POST.get('duration', '').strip())) job.quotes_id = pk job.client = client job.save() ..... ..... Here is my forms.py class ConvertQuoteToJobForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ConvertQuoteToJobForm, self).__init__(*args, **kwargs) client = self.user.client self.fields["assigned_to"] = forms.ModelMultipleChoiceField( widget=forms.SelectMultiple(attrs={'required': 'required'}), queryset=ClientUser.objects.filter(client=client). filter(Q(role__role_attribute='Job Worker') | Q(role__role_attribute='Job Worker with documents') | Q(role__role_attribute='Job Administrator') | Q(role__role_attribute='Job / Stock') | Q(role__role_attribute='Job / Stock / Opportunities') | Q(role__role_attribute='Job Worker / Stock')). exclude(is_active=False)) self.fields["duration"].required = True instance = getattr(self, 'instance', None) def clean(self): cleaned_data = super(ConvertQuoteToJobForm, self).clean() return cleaned_data class Meta: model = AddJob … -
Django: How to make json data readable in django?
i am trying to retrieve the lastest news from hackernews api, everthing seems to be working fine and when i print the status code, i get Status Code:200. Now i am getting some data but they are not readable this is how there are displayed b'[31349988,31344981,31348529,31344863,31341698,31348097,31347740,31348772,31347286,31348463,31345478,31348316,31345749,31347983,3' and this is code i used to retrieve the data from the api https://hackernews.api-docs.io/ def index(request): response = requests.get("https://hacker-news.firebaseio.com/v0/topstories.json") return render(request, "index.html", {'response': response}) -
Edit user permission in django admin, for custom user model
I have a custom user model as below: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='ایمیل', max_length=60, unique=True) username = models.CharField(verbose_name='نام کاربری', max_length=30, unique=True) ... USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Then I write a code like this in admin.py: @admin.register(Account) class PersonAdmin(ImportExportModelAdmin): list_display = ('email', 'username', 'phone_number', 'chart_level', 'chart_view_count') list_filter = ("is_admin", 'is_active', 'is_staff', 'chart_level', 'is_plus') search_fields = ['username', 'email', 'phone_number', 'referral_code'] readonly_fields = ("date_joined", "last_login", "chart_view_count", "id") fieldsets = ( ('اطلاعات فردی', { 'classes': ('collapse',), 'fields': ('email', 'username', 'phone_number', 'telegram_user_id', 'profile_image', 'date_joined', 'last_login', 'is_english', 'is_foreign', 'chart_view_count', 'password') }), ('اطلاعات خرید', { 'classes': ('collapse',), 'fields': ('used_referral_code', 'total_pay_r', 'total_pay_c', 'is_using_discount', 'using_discount_code', 'current_transaction_address', 'referral_code', 'is_first_payment') }), ('سطح کاربری', { 'classes': ('collapse',), 'fields': ('chart_level', 'is_plus', 'expiration_date', 'reserved_trader', 'is_admin', 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions') }), ) It works perfectly for thousands of users. now I want to add user permissions to change user page in admin panel, so I add "PermissionsMixin" like this: class Account(AbstractBaseUser, PermissionsMixin): ... then I tried to migrate and get this error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "accounts_account" what should I do? -
Create asyncio tasks indefinitely without blocking (django)
So, I'm trying to create a polling system internal to django commands for fun and to learn async/django. I'm using django_tenants, although it's not overly important. The idea is that there is a table that holds "tenants". I want to loop through those tenants in a higher infinite loop. For each tenant that isn't already in the async queue (perhaps because the process from the last time that tenant was found hasn't finished yet), I want to add a new asyncio task to be run. My test case has this one tenant which I wait 5 seconds for to ensure I get the internal queue/loop working. The idea is that, say there are 3 tenants: t_a, t_b and t_c, and t_a and t_c take 2 and 1 seconds respectively to run, with t_b taking 5. I would ultimate see the infinite loop running like this: t_c Done t_c Done t_a Done t_c Done t_c Done t_a Done t_c Done t_b Done t_c Done --- The long running one t_a Done .... So, t_c doesn't hold up the other tenants from being re-run. Each iteration of the tenants fetches NEW data as tenants might get created between runs. class Command(BaseCommand): help … -
Can Django render a React component that is using React-Router
I was building an application in Django and using templates for the majority of the application as I had simple html pages. I already have a sign in and sign up page as well as some portal pages. I tried react and started using it and building some components with the Django rest framework and I liked it for the majority but now I have the issue of routing. I was migrating the react build folders to the respective Django folders and have Django render the components. However, I built a user list where each user is clickable and takes me to an edit page (admin type). But once I migrated the component it simply did not render while other components rendered normally as they should. This is the list set up ReactDOM.render( <React.StrictMode> <Router> <App /> </Router> </React.StrictMode>, document.getElementById("root") ); Then I call a id "root" div in the index and that works fine in the react server but it does not render at all when I move it to the Django server. If I remove the router related code and make it a simple component it does render but means I will not be able to use routing … -
Getting Error Object of type bytes is not JSON serializable in django
I Everyone i my trying to to convert my response to to json its getting error which i have mention in question. how can i convert this response to json as per me problem is Decimal and b(byte), please help me out. Response. [{'number': '0001', 'name': 'john', 'total_trips': Decimal('32'), 'status': '', 'day1_trips': b'8', 'day2_trips': b'17', 'day3_trips': b'0', 'day4_trips': b'0', 'day5_trips': b'7', 'day6_trips': b'R', 'day7_trips': b'0'}] -
stripe CardError handle django
// value error // from django.shortcuts import redirect, render import stripe import stripe stripe.api_key = 'sk_test_' # Create your views here. def index(request): return render(request,'template/donate.html') def thanks(request): return render(request,'template/thanks.html') def cargo(request): card_num=request.POST['num_card'] month=request.POST['month'] year=request.POST['year'] cvv=request.POST['cvv'] if request.POST: token = stripe.Token.create( card={ "number": card_num, "exp_month": month, "exp_year": year, "cvc": cvv }, ) doc=stripe.Customer.create( email=request.POST['email'], name=request.POST['name'], source=token ) stripe.Charge.create( customer=doc, amount=request.POST['cantidad'], currency='cad', description= "DONATIVO" ) return render(request,'template/thanks.html') else: return render(request,'template/index.html') // stripe card error handle how to render errors in html page because it redirects me to a error page if client insert an invalid CVV or card num or expirationdate i think that i should try using stripe.error.CardError but documentation is not getting in my head // -
Websocket failed in live server , WebSocket connection to 'wss://my_domain.com:8001/' failed:
I am adapting websocket in django app, it was working but I don't know what happened it failed now. I used different channel layer code in live server and in local server. Any Idea about this problem? notification.js const ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; if (ws_scheme == 'wss') ws_path = ws_scheme + '://' + window.location.host + ":8001/"; else ws_path = ws_scheme + '://' + window.location.host; const notificationSocket = new WebSocket(ws_path); routing.py import os from decouple import config from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from django.urls import re_path, path os.environ.setdefault("DJANGO_SETTINGS_MODULE", f'{config("PROJECT_NAME")}.settings') django_asgi_app = get_asgi_application() from chatapp.consumers import ChatConsumer from notification.nconsumers import NotificationConsumer application = ProtocolTypeRouter({ "http": django_asgi_app, 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('chatapp/<int:room_id>/', ChatConsumer.as_asgi()), path('', NotificationConsumer.as_asgi()), ]) ) ), }) asgi.py import os import django from decouple import config from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", f'{config("PROJECT_NAME")}.settings') django.setup() application = get_default_application() consumers.py from django.conf import settings from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from chatapp.models import UnreadChatRoomMessages from notification.models import Notification class NotificationConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, code): pass settings.py INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chat', 'customer', 'notification', 'rest_framework', … -
Is Model.objects.update() in Django is synchronous? How to get updated rows after updating values?
I'm using Django with MySQL I want to get effected rows after run Model.objects.update() I have code below: # 1 User.objects.filter( pk__in=ids, status=old_status, ).update( status=new_status, pre_update_key=uuid_str, updated_at=datetime.datetime.now(), ) # 2 updated_users = list( User.objects.filter(pre_update_key=uuid_str).values() ) print(len(updated_users)) Results are different between environments Database 1: Users has 3000 rows => len(updated_users) != 0 is correct Database 2: Users has 300000 rows => len(updated_users) = 0 How can I get updated_users after #1 query is done completely? -
Django modifying admin edit interface
So here is my admin.py class ContentPageAdmin(admin.ModelAdmin): fields = (("category", "listing_title1", "show_listing1"),) the category is ManyToMany fields, listing_title1 is CharField, and show_listing1 is a BooleanField. Now it will display all of them in one line, but I want to put the show_listing1 below the listing_title1. How can I do that? -
No module named 'django.conf.urls.defaults'
I upgraded from django 3.2.5 to django 4.0.4. I know that this 'django.conf.urls.defaults' must be deprecated. My problem is that I don't get this error in the development environment but when I push to production, it shows the error. Why is this so??? Also I tried to locate the file so that I can change that line of code to the correct one but could find it's location. It's giving me this path which I can't see how to get to (/workspace/.heroku/python/lib/python3.9/site-packages/django/conf/urls/__init__.py)) -
Error ModuleNotFoundError: No module named 'api'
My Python program is throwing the following error: ModuleNotFoundError: No module named 'api' How to remove the ModuleNotFoundError: No module named 'api' error? -
Comments DateTimeField() Django
I'm trying to build a comments section in my website, and I'm pretty much done, but I'm trying to display the time that it was posted, but it keeps displaying the wrong time. This is my code in my models.py Posts class: ''' date = models.DateTimeField(default=timezone.now) ''' I know that the database recognizes something is wrong because it shows me this message: but I don't know how to fix it. Can someone please help me? Thanks! -
Calculating income and expense by filtering according to the entered date
I have a date picker and I will calculate income and expense based on this date. I want to add a parameter named random_date to my function in view.py. I want the user to set the end date. The start time will be today's date. For example, if the user has selected June 1 as the date, I want to sum the income and expenses from today to June 1st. How can I do that? Here is my views.py file: import datetime from django.shortcuts import render from incomes.models import Income, Source from expenses.models import Expense, Category from .models import SummaryModel # Create your views here. def Summary(request): todays_date = datetime.date.today() six_months_later = todays_date + datetime.timedelta(days=180) all_expenses = Expense.objects.filter(owner=request.user, date__gte=todays_date, date__lte=six_months_later) all_incomes = Income.objects.filter(owner=request.user, date__gte=todays_date, date__lte=six_months_later) def get_amount(EorI): amount = 0 for item in EorI: amount += item.amount return amount final_rep = {'Net_Income' : get_amount(all_incomes) - get_amount(all_expenses)} return render(request, 'summary.html', final_rep) Here is my summary.html file: <div class="card"> <div class="card-body"> </select> <div class="form-group"> <label for="">Choose a date</label> <input type="date" value="{{values.date | date:'Y-d-m'}}" class="form-control form-control-sm" name="random_date" /> </div> <input type="submit" value="Submit" class="btn btn-primary btn-primary-sm" /> <div class="container"> <div class="col s12 m12 l4"> <div class="card-panel"> <h8 class="bold">Net Budget</h8> <h1 class="bold">${{ Net_Income }}</h1> </div> … -
django orm foreign key latest data using filter query
class Schedule(models.Model): user = models.ForeignKey(USER, on_delete=models.SET_NULL, null=True) area = models.ForeignKey(Site, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) area = Schedule.objects.values("area").annotate(latest=Max('created_at')).values("area") latest = Schedule.objects.values("area").annotate(latest=Max('created_at')).values("latest") Schedule.objects.filter(created_at__in=latest, area__in=area) I got the value I want. However, I am uneasy when I filter with ForeignKey and DateTimeField. Can't there be a better way? Also, can't you make it cleaner other than the code above? -
How to Add uuid field in django Existing User model?
I really need your help, I've been looking everywhere but can't find anything? -
Subtract Year from an object in a Django Project
I'm trying to subtract year data from a model object created in a Django project. I would like to obtain a final value comparing a date in an object registered in my model with the value of the current year, 2022. Something like an anniversary date calculation for an ephemeris project. Logic: Current Year - object with a 'year' value in a date field "1952"; Logic Example: 2022 - some_variable Expected result = 70 My model: class Person(models.Model): dateborn= models.DateField() I'm trying to use .dates() in the logic in my views.py to get the year: from app.models import Person persons = Person.objects.all() dateborn = persons.dates('dateborn','year') then I get a result: <QuerySet [datetime.date(1935, 1, 1)]> OK! I'm struggling now to elaborate a logic to subtract the result of this QuerySet using only the 'YEAR' of the object. I know that if I use an INT I will not be able to perform the calculation. I try: #used resultfinal = 2022 - dateborn AND #used resultfinal = datetime.today().strftime('%d/%m') - dateborn Then #My expected end result would be something like this: resultfinal = 2022 - 1935 I know I'm mixing things up, but I can't find a method of subtracting correctly. :( I … -
I got unexpected keyword argument 'providing_args' after installing Django extensions
I am creating a Django website. I was recently using the management command runserver_plus provided by Django Extensions to run the development server. When I attempt to run the website through terminal I receive the error message: C:\Users\Hp\anaconda3\DJANGO\website> python manage.py runserver_plus --cert-file cert.crt Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\__init__.py", line 279, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\__init__.py", line 48, in load_command_class module = import_module("%s.management.commands.%s" % (app_name, name)) File "C:\Users\Hp\anaconda3\lib\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 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Hp\anaconda3\lib\site- packages\django_extensions\management\commands\runserver_plus.py", line 40, in <module> from django_extensions.management.utils import RedirectHandler, has_ipdb, setup_logger, signalcommand File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\utils.py", line 6, in <module> from django_extensions.management.signals import post_command, pre_command File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\signals.py", line 13, in <module> pre_command = Signal(providing_args=["args", "kwargs"]) TypeError: __init__() got an unexpected keyword argument 'providing_args' -
Django Admin Editable but Hidden field
Currently I have an editable field in a model in Django Admin. I would like this to remain editable, but not readable. For example, it would look like a password field with asterisks that an admin can change, but not read. How can I do this? -
Bad request 400 react + django
I am receiving error 400 bad request while trying to authenticate react with django rest framework Here is Signup.js import React from "react"; import { Button, Form, Grid, Header, Message, Segment, } from "semantic-ui-react"; import { connect } from "react-redux"; import { NavLink, Navigate } from "react-router-dom"; import { authSignup } from "../store/actions/auth"; class RegistrationForm extends React.Component { constructor (props) { super(props); this.state = { username: "", email: "", password1: "", password2: "", userType: "", is_student : true }; this.handleSubmit = this.handleSubmit.bind(this); this.handleChange = this.handleChange.bind(this); }; handleSubmit = e => { e.preventDefault(); const { username, email, password1, password2, userType, is_student } = this.state; this.props.signup(username, email, password1, password2, userType, is_student); const signupFormValid = !username?.length || !email?.length || !password1?.length || !password2?.length || !userType?.length ; }; handleChange = e => { this.setState({ [e.target.name]: e.target.value }); }; render() { const { username, email, password1, password2, userType } = this.state; const { error, loading, token } = this.props; if (token) { return <Navigate to="/" />; } return ( <Grid textAlign="center" style={{ height: "100vh" }} verticalAlign="middle" > <Grid.Column style={{ maxWidth: 450 }}> <Header as="h2" color="teal" textAlign="center"> Signup to your account </Header> {error && <p>{this.props.error.message}</p>} <React.Fragment> <Form size="large" method='post' onSubmit={this.handleSubmit}> <Segment stacked> <Form.Input onChange={this.handleChange} value={username} name="username" fluid … -
problem with migrate in heroku in windows 10
Cheers! i am trying to do heroku run python manage.py migrate from git on windows 10 and this is the result ` heroku run python manage.py migrate Running python manage.py migrate on `enter code here`tornilub... starting, run.3211 (Free) Running python manage.py migrate on tornilub... connecting, run.3211 (Free)Running python manage.py migrate on tornilub... up, run.3211 (Free) Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 91, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 480, in check for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.name] = … -
Deploying django with apache + mod_wsgi _ Error 500
I'm trying to deploy my first django app in windows 10 (x64), so installed apache 2.4(x86), installed and build mod_wsgi (4.9.1) with python 3.8(x86) (I have microsoft visual studio 2019 installed) and configured Apache httpd.conf and httpd-vhosts.conf files. My app runs fine, but the annoying error 500 keeps showing every now and then, and goes away by refreshing the browser every time. There seems to be a bug with python 3.8, so decided to upgrade to python 3.10 (X86), Reinstalled mod-wsgi and other packages using pip in new virtual environment in the same directory, and reconfigured httpd.conf accordingly. now apache service fails to start with error: "windows could not start the Apache2.4 on local computer....". If I change httpd.conf configuration to load and use the python3.8 , Apache starts with no error. but again Error 500 keeps showing. by the way I tried the same with python3.9 (x64) and Apache 2.4 (X64), with no luck. any help would be greatly appreciated. In httpd.conf: This configuration fails: LoadFile "C:/Program Files (x86)/Python310-32/python310.dll" LoadModule wsgi_module "d:/django project/unemployment project/.venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win32.pyd" WSGIPythonHome "d:/django project/unemployment project/.venv" This configuration works: LoadFile "C:/Program Files (x86)/Python38-32/python38.dll" LoadModule wsgi_module "d:/django project/unemployment project/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win32.pyd" WSGIPythonHome "d:/django project/unemployment project/venv" -
Formset and django-autocomplete-light creates extra value
Formset creates an extra value when I click "add another" button. I don't know how to fix it. I will be happy if you could give me advice. Moreover, the second line does not work, that is, I cannot select any value. It doesn't show any options. forms.py class BirdForm(forms.ModelForm): name = forms.ModelChoiceField( queryset=Bird.objects.all(), widget=autocomplete.ModelSelect2( url='birdautocomplete'), ) class Meta: model = Bird fields = ('name', 'description') BirdFormSet = modelformset_factory( Bird, form=BirdForm, extra=1, ) template.html <div class="check_bird form-row"> <label class="form-label" for="myCheck">If you want to add new bird</label> <input type="checkbox" id="myCheck" onclick="FunctionBird()"> </div> <div class="check_bird_form" id="bird" style="display:none"> {{formset.management_form}} {% for form in formset %} <div class="bird-form form-row"> {{form}} </div> {% endfor %} <button style="margin-top:25px;" id="add-form" type="button">Add Another</button> </div> {{formset.media}} <script> function BirdCoauthor() { var checkBox = document.getElementById("myCheck"); var text = document.getElementById("bird"); if (checkBox.checked == true) { text.style.display = "block"; } else { text.style.display = "none"; } } let birdForm = document.querySelectorAll(".bird-form") let container = document.querySelector("#coauthor") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = birdForm.length - 1 addButton.addEventListener('click', addForm) function addForm(e) { e.preventDefault() let newForm = birdForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`, 'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } $("#1").val(null).trigger("change"); </script> -
i want to add value to a field by calculating two values for tow fields in django api rest framework not template
#models file I want to add value to deserved_amount field by calculating a payments minus from the class product inside field selling_price ... If there are any modifications to the important classes, I want to deduct a payment from the original amount and then show the remaining amount after each payment to the user... I want the process to rest framework api endpoint # this class adds payment to each product price class Payment(models.Model): PK = models.AutoField(primary_key=True) payments = models.FloatField(default=0) description_paid = models.TextField(max_length=1500, default='') payment_date = models.DateField(default=datetime.date.today) product = models.ForeignKey('Product',related_name='paymentProducts' , on_delete=models.CASCADE) imag_file = models.ImageField(upload_to='uploads' , blank=True , null=True) deserved_amount = models.FloatField(default=0, null=True , blank=True) ''' I want to add value to deserved_amount field by calculating a payments minus from the class product inside field selling_price ... please help me , thanks ''' #this is class add a product this is class add a product this is #class add a product this is class add a product this is class add #**strong text**product class Product(models.Model): JAWWAL = 'JAWWAL' type_category = [ (JAWWAL,'جوال'), ('SCREEN','شاشة'), ('FRIDGE','ثلاجة'), ('LAPTOP','لابتوب'), ('WASHER','غسالة'), ('ELECTRICAL DEVICES','جهاز كهربائي'), ('FURNITURE','موبيليا'), ('ATHER','اخرى'), ] PK = models.AutoField(primary_key=True) cost_price = models.FloatField(default=0) selling_price = models.FloatField(default=0) supplier_name = models.CharField(max_length=70 , blank=True , null=True) category = …