Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add text into a link in src=" "
I have this src="https://open.spotify.com/embed/track/1Go9q6KaCpAsQ0wkZFGzY2?utm_source=generator" and I want it to be like this src="https://open.spotify.com/embed/track/{{ spotify_trackid }}?utm_source=generator" how can I do this using django without it breaking the link? sorry for the bad explanation i'm pretty new to this -
how to return result to html django
I want to make text file contains with b'Y\xf5\x11m' (it's result from encryption). And I want txt file can be downloaded using html. But I got next error when I return it: 'int' object has no attribute 'get' Here's the code: def create_file(f): with open("file.txt", 'w') as file: download = file.write(str(f)) print(download) return download I called that func like this: #in views download = create_file(enc) print(download) #in urls path("create_file", views.create_file, name="create_file"), #in html <a href="{% url 'create_file' %}"> -
django CK-Editor not working in production shared hosting
My Django application has a django-ckeditor which seemed to work fine in the local host but dosent work in the production enviornment . I have used proper static path settings cause all of my other static files are loading properly . but the ck-editor is not working fine . This is my settings.py file . STATIC_URL = '/static/' # Add these new lines STATIC_ROOT = "/home/username/public_html/static/" MEDIA_URL = '/media/' MEDIA_ROOT = "/home/username/public_html/media/" CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_BASEPATH = "/home/username/public_html/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = 'uploads/' This is my wsgi.py file import os from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hrnindia.settings') application = get_wsgi_application() application = WhiteNoise(application, root="/home/username/public_html/static/") application.add_files("/home/username/public_html/static/ckeditor/ckeditor/", prefix="more-ck-files/") application.add_files("/home/username/public_html/static/ckeditor/", prefix="more-files/") I have tried out all the other solutions like configuring the path and using whitenoise . But nothing seems to make the ck-editor work . -
Best practice for Python typing out of dictionary (self.fields type in Django ModelForm)
I have a form like this class MerchantBrandsForm(forms.Form): brands = forms.ModelChoiceField(required=True, queryset=None) def __init__(self: merchant: Merchant): self.fields['brands'].queryset = merchant.brands.all() But I have an error with mypy with the queryset as fields has a type Dict[str, Field], which cause error: "Field" has no attribute "queryset". I know I can cast the fields using cast or ignore the typing, but I don't think this is a clean solution. What is the best way to assign brands queryset without ignoring the type or using cast function? -
AttributeError: 'NoneType' object has no attribute 'is_superuser'
I'm working with Django, and I keep getting this error when trying to create a new superuser inside the terminal: AttributeError: 'NoneType' object has no attribute 'is_superuser' I've tried everything I've looked up to fix it. No luck. Also, this code is greyed-out inside my user model, and when I hover over the text it says: Code is unreachable Pylance if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) email = email.lower() user = self.model( email = email, name = name ) user.set_password(password) user.save(using=self._db) return user Here is my full user model: from abc import abstractmethod from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): @abstractmethod def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) email = email.lower() user = self.model( email = email, name = name ) user.set_password(password) user.save(using=self._db) return user def create_realtor(self, email, name, password=None): user = self.create_user(email, name, password) user.is_realtor = True user.save(using=self._db) return user def create_superuser(self, email, name, password=None): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # … -
'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte django
so i have variable contains in bytes and i want to save it to str. but how to do it? i tried various kinds of ways, but always got error 'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte i want to save the result encrypt file to text file. so i have the proof it the file was encrypt. here;s my ways 1: def create_file(f): response = HttpResponse(content_type="text/plain") response['Content-Disposition'] = 'attachment; filename=file.txt' filename = f print(filename) name_byte = codecs.decode(filename) print(name_byte) return response my ways 2 : def create_file(enc): with open("file.txt", "w", encoding="utf-8") as f: enc = enc.decode('utf-8') f.write(enc) my ways 3: def create_file(f): file = open("file.txt", "w") f = f.decode('utf-8') download = file.write(f) file.close() print(download) return download f = b'\xa0\x0e\xdc\x14' f is the return result of encrypt -
Is it possible to return the display name of a choice in Django?
So when you make choices for a form/model you do this: EXP_CHOICES = ( ('1ST','First'), ('2ND','Second'), ....... ('XXX','YYY'), ) # where XXX is the value stored in the database and YYY is what you see in a form. This also applies to the queries, so when you have the mentioned choices and select one, do a query on the model and it returns '1ST'/'2ND'/'XXX'. But what if you want to display the YYY instead? So we know that '1ST' is 'First', but we want to make it user readable. Is there a way to access that EXP_CHOICES and write out the YYY tied to them, or you must make an if&else/selector to be like {% if data.chosen == '1ST'%} First {% elif ... %} ... {% endif %} -
Django annotate: sum all records by asset | only one table
My django model: class Movimentacao(models.Model): product = models.CharField(max_length=300) value = models.DecimalField(max_digits=19, decimal_places=2) I'm trying to SUM all value by product using django annotate. I tried: query = Movimentacao.objects.annotate(total=Sum('value') ).values('product', 'total' ).order_by('product') There are a lot of repeated products (multiple lines) with different values and I'd like to group all same products and sum their respective values. But it's showing all records without grouping and summing all of them. I wouldn't like to use aggregate in this case. Tks -
Access a json object form views django
i have tired a number of suggestions but need help. in my views.py def findnamesurname(request): username = request.POST['username'] obj = Users.objects.all().values("first_name") return HttpResponse(obj) in my json $.ajax({ url: "/findnamesurname", method: "POST", data: { 'csrfmiddlewaretoken': '{{csrf_token}}', "username": data, }, success: function (data) { alert(JSON.stringify(data)) } }) } I want to get first name please in a viable I get the following when i alert: {'first_name': 'Daniel'} How to access this object please. -
What type of database replication is used by Digital Ocean's read-only nodes?
I'm working on two Django projects that need to share a PostgreSQL database, a database which needs to be replicated for read-only operation. The reason is that one of the projects mostly performs write operations while the other performs read operations. To achieve this, I'm considering Digital Ocean's read-only nodes. The question that comes to my mind how long it takes to propagate a write operation in the primary sever to the read-only server located in the same datacenter, so that future read requests return consistent results. And, more importantly, is the replication synchronous or asynchronous ? Some solutions are synchronous, meaning that a data-modifying transaction is not considered committed until all servers have committed the transaction. This guarantees that a failover will not lose any data and that all load-balanced servers will return consistent results no matter which server is queried. In contrast, asynchronous solutions allow some delay between the time of a commit and its propagation to the other servers, opening the possibility that some transactions might be lost in the switch to a backup server, and that load balanced servers might return slightly stale results. Asynchronous communication is used when synchronous would be too slow. https://www.postgresql.org/docs/current/high-availability.html -
Why I am getting django.db.utils.IntegrityError even after removing default=0?
I am new to Django. I was working on a project whose one of the database tables has a recursive foreignkey. I am sharing that table here. class Categories(models.Model): name = models.CharField(max_length=25) slug = models.CharField(max_length=25) parent = models.ForeignKey("self",on_delete=CASCADE,default=None,blank=True) My database migration did not work when the default was 0. It worked fine when there was null = True. The problem occurred when I removed the null and set default to 0. After having the error, I removed the default=0 and set the null to true. Whatever I try I still have the same problem when I run the python manage.py migrate command. This is my problem: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, stock_app Running migrations: Applying stock_app.0005_alter_categories_parent...Traceback (most recent call last): File "C:\Users\Rakin Shahriar\Desktop\stock-image-sharing-platform\stock_image_sharing_platform\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.ForeignKeyViolation: insert or update on table "stock_app_categories" violates foreign key constraint "stock_app_categories_parent_id_b0ca10d8_fk_stock_app" DETAIL: Key (parent_id)=(0) is not present in table "stock_app_categories". The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Rakin Shahriar\Desktop\stock-image-sharing-platform\stock_image_sharing_platform\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Rakin Shahriar\Desktop\stock-image-sharing-platform\stock_image_sharing_platform\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in … -
Permission has not appear in the admin site
Django 4.1 class ExamPart(models.Model): name = models.CharField(max_length=255, null=False, default="") class Meta: permissions = [('fipi', 'n-fipi')] Problem I have set a permission to the model. Then I created a new user in the admin site. And wanted to grant him this privilege. But I can't see this permission in the admin site. Could you help me? -
cannot get 404 page while entering a invalid url
project Url.py handler404 = 'patient.views.handler404' Patient views.py def handler404(request,exception): return render(request, 'error/404.html') 404.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>404ERROR</title> <link href="{% static 'css/404style.css' %}" rel="stylesheet"> </head> <body> <h2>Page Not Found</h2> </body> </html> And also turn off debug=False but still its shows server error(500) -
Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. while using Django, Nginx, Dophne
daphne.service file [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root #Group=www-data WorkingDirectory=/var/www/html/app EnvironmentFile=/var/www/html/app/.env ExecStart=/var/www/html/Env/myapp/bin/python3 /var/www/html/Env/myapp/bin/daphne -b 0.0.0.0 -p 8000 config.asgi:application #Restart=on-failure [Install] WantedBy=multi-user.target My nginx configuration file upstream channels-backend { server localhost:8000; } server { server_name my.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /var/www/html/app/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/var/www/html/app/gunicorn.sock; } location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass channels-backend; } client_max_body_size 500M; } my asgi.py file """ ASGI entrypoint. Configures Django and then runs the application defined in the ASGI_APPLICATION setting. """ import os from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator import base.urls os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( base.urls.websocket_url_patterns, ) ) ), }) So these things are easily available on the internet and I used it. The problem here is in the front end I have connected like this this.state.notificationSocket = new WebSocket( 'wss://' + window.location.host + '/ws/notification/' ); this.state.notificationSocket.onmessage = function(e) { const data = JSON.parse(e.data); console.log('ON MESSAGE'); … -
Sum numbers and group them by the given month, is there a 'best practice'?
I don't know what I messed up. I tried so many methods and solutions and so far this works the best, but the ordering is messy. I want to sum the expenses grouped by the month extracted from the datefield it was given. So far I made this: def index(req): qs = Expense.objects.filter(pom='OUT').annotate(month=TruncMonth('when')).values('month').annotate(total_amount=Sum('amount')) # pom='OUT' -- expense (there are expenses and incomes) return render(req, 'index.html', {'data': qs}) which works perfectly, returns them as "sept. 15.000, aug. 10.000" which is nice! But the last/latest month is always at the bottom so I wanted to give it an order_by, which returns each unique object in the model (so if sept. 15.000 came up as sept.15 10.000 and sept.22 5.000, when they're not summed up but returned/shown separately). What did I mess up? EQ: The mentioned query (without order_by) returns a queryset as of <QuerySet [{'month': datetime.date(2022, 8, 1), 'total_amount': 15000.0}, {'month': datetime.date(2022, 9, 1), 'total_amount': 16000.0}]> by default making it look they all have been recorded at the start of the given month. Drop a reply for further information if I forgot to include something/explained something poorly! -
How to properly import an existing Django project in Eclipse/Pydev?
I cannot figure how to import correctly an existing Django project in Eclipse/Pydev, and I can't find my way in the documentation of Pydev. My question is pretty simple : I have an existing project from a different computer, that I want to migrate on a new one. I installed Eclipse and Pydev on the new machine, and everything seems normal for a new project: I can create a new Django project and run it without issue. I also have been able to import my pre-existing project, but when I run the project, I encounter the following error : Finding files... done. Importing test modules ... Traceback (most recent call last): File "/home/francois/.p2/pool/plugins/org.python.pydev.core_9.3.0.202203051235/pysrc/_pydev_runfiles/pydev_runfiles.py", line 468, in __get_module_from_str mod = __import__(modname) File "/home/francois/eclipse-workspace/Test/Test/urls.py", line 20, in <module> path('', include('myApp.urls')), File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/francois/eclipse-workspace/Test/myApp/urls.py", line 2, in <module> from . import views File "/home/francois/eclipse-workspace/Test/myApp/views.py", line 2, in <module> from myApp.forms import CreateGroupForm, JoinGroupForm File "/home/francois/eclipse-workspace/Test/myApp/forms.py", line 4, in <module> from .models import Group, User File "/home/francois/eclipse-workspace/Test/myApp/models.py", line 2, in <module> from django.contrib.auth.models import AbstractUser File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager … -
Django REST API JWT user verification failed : No active account found with the given credentials
i am using django JWT for account validation but fails for every user that is not super user but works for superuser created using python manage.py createsuperuser Here is the model for User profile class AccountManager(BaseUserManager): def create_user(self, name, phone, email, password=None, **extra_fields): """ Creates and saves a User with z given name,phone,email and password. """ user = self.model(name=name,email=self.normalize_email(email),phone=phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, name, phone, email, password=None, **extra_fields): user = self.create_user(name, phone, email, password, **extra_fields) user.is_admin = True user.is_superuser = True user.is_staff = True return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email address',max_length=255,unique=True,) phone = models.CharField(max_length=15,unique=True) name = models.CharField(max_length=150,unique=True) picture = models.ImageField(blank=True, null=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(null=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['name', 'phone', 'email', 'password'] def __str__(self): return self.name and here is my signup API function that creates a normal user def signup(request): if request.method == 'POST': try: values = [request.POST.get('name'),request.POST.get('email'),request.POST.get('phone'),request.POST.get('password'),request.POST.get('password2')] user = Account.objects.create_user(name=values[0],phone=values[2],email=values[1],password=values[3]) user.save() # send email verification current_site = get_current_site(request) mail_subject = 'Activate your account.' message = f'{current_site.domain}/account/activate/{urlsafe_base64_encode(force_bytes(user.pk))}/{account_activation_token.make_token(user)}' to_email = values[1] send_mail(mail_subject, message, 'youremail', [to_email]) return JsonResponse({'success': 'User registered successfully.But need to activate account.'}) except Exception: extype, exc, tb = sys.exc_info() print(f"\t\t****** … -
Test a custom django filter
Written a filter that is functioning as it should class ExternalProductActiveStatusFilter(admin.SimpleListFilter): title = "EP Active status" parameter_name = "ep active status" def lookups(self, request, model_admin): return [ ("active", "Active"), ("inactive", "Inactive"), ] def queryset(self, request, queryset): if self.value() == "active": return queryset.distinct().filter(external_products__active=True) if self.value() == "inactive": return queryset.exclude(external_products__active=True) Now I want to test it but can't get it to work. Looked into old SO questions but the solutions do not do the trick. These ones in particular, Test a custom filter in admin.py(7 years old) and Django filter testing My test as of right now def test_externalproductactivestatusfilter_active(self): self.product1 = baker.make( "products.Product", id=uuid4(), title="Active product" ) self.product2 = baker.make( "products.Product", id=uuid4(), title="Inactive product" ) self.external_product1 = baker.make( "external_products.ExternalProduct", internal_product=self.product1, active=True, ) self.external_product2 = baker.make( "external_products.ExternalProduct", internal_product=self.product1, active=False, ) request = MockRequest() f = ExternalProductActiveStatusFilter( None, {"active": "Active"}, Product, ProductAdmin ) result = f.queryset(request, Product.objects.all()) print(result) result is None -
Django rest framework filtering and grouping items in serializer
I have models like this: class schoolCycle(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=255) class measurements(models.Model): name = models.CharField(max_length=255) weight = models.FloatField() school_cycle_id = models.ForeignKey(schoolCycle,on_delete=models.DO_NOTHING, related_name='measurements') code = models.CharField(max_length=255) class aspects(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=255) measurement_id = models.ForeignKey(measurements,on_delete=models.DO_NOTHING, related_name='aspects') class standards(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=255) weight = models.FloatField() aspect_id = models.ForeignKey(aspects,on_delete =models.DO_NOTHING, related_name='standards') as can be seen, "standard" refers an 'aspect' and aspect refers 'a measurement" and measurement refers a 'school cycle' as foreign key. in want to create a seriallizer like this: [{ "measurement 1" : { "school cycle 1" :{ "aspect 1": { {"standard 1" : ...}, {"standard 2" : ...}, } "aspect 2": { {"standard 3" : ...}, {"standard 4" : ...}, } } "school cycle 2" :{ "aspect 3": { {"standard 5" : ...}, {"standard 6" : ...}, } "aspect 4": { {"standard 7" : ...}, {"standard 8" : ...}, } } "measurement 2" : { "school cycle 3" :{ "aspect 5": { {"standard 9" : ...}, {"standard 10" : ...}, } "aspect 6": { {"standard 11" : ...}, {"standard 12" : ...}, } } "school cycle 4" :{ "aspect 7": { {"standard 13" : ...}, {"standard 14" : ...}, } "aspect 8": … -
how to set delay to restart container in docker-compose?
I have a problem with the initial launch of docker-compose up, when DB is not initialized yet and django throws an error. I tried to use 'restart_police', but it didn't help and the webservice was restarted almost without waiting and forward the DB service, regardless of which reload period I wouldn't set version: "3.9" services: web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - "8000:8000" deploy: restart_policy: condition: on-failure delay: 15s environment: - POSTGRES_NAME=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_HOST=db depends_on: - db db: container_name: db_pg image: postgres hostname: postgres environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_HOST: db volumes: - ./data/db:/var/lib/postgresql/data restart: unless-stopped pgadmin: image: dpage/pgadmin4 depends_on: - db ports: - "5555:80" environment: PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin.org PGADMIN_DEFAULT_PASSWORD: admin volumes: - ./data/pgadmin:/var/lib/pgadmin/data -
Django Model '<' not supported between instances of 'str' and 'int'
I have a Django script which runs fine locally, but on Render.com it fails with this error: Sep 4 01:01:54 PM create_tasks(limit=limit) Sep 4 01:01:54 PM File "/opt/render/project/src/scripts/pull_from_outscraper.py", line 94, in create_tasks Sep 4 01:01:54 PM for task_object in task_objects[0:limit]: Sep 4 01:01:54 PM File "/opt/render/project/src/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 422, in __getitem__ Sep 4 01:01:54 PM or (k.stop is not None and k.stop < 0) Sep 4 01:01:54 PM TypeError: '<' not supported between instances of 'str' and 'int'``` -
Avoid hardcoding of a model name
Django 4.1 class Task(models.Model): cypher = models.CharField( max_length=255, null=False, default="", ) class Meta: db_table = "{}_{}_{}".format(TablePrefixes.FIPI.value, __package__, "Task") Here in db_table I hardcoded "Task". Could you tell me whether it is possible to somehow avoid hardcoding? -
Django template includes + extends
This is my Directory Tree. base.html: {% load static %} <!DOCTYPE html> <html lang="en"> {% include 'weapons/head/head.html' %} {% include 'weapons/body/body.html' %} </html> body.html: {% load static %} <body> {% block content %}{% endblock content %} </body> home.html: {% extends 'weapons/base/base.html' %} {% block content %} <span>Hello!</span> {% endblock content %} When I visit my home.html, it doesn't appear to be working correctly. I see nothing on my page, however the "Hello!" message is expected to be shown. What is the problem? -
Django modelformset_factory error is not displayed in template
I have a modelformset_factory displaying 20 forms with 20 staff names whose phone numbers are to be entered but if there is an error(s), they are not displayed in the template and the entered data are also lost. And even if the forms are valid I am not redirected to the home page. Fresh forms are loaded all the times I click submit button. class PhoneEntryView(LoginRequiredMixin, FormView): template_name = "myportal/ca_entry_form.html" success_url = '/myportal/home-page' def get_initial(self): initial = super().get_initial() logged_in_user = User.objects.get(id=self.kwargs['pk']) staff_list = Staff.objects.filter(manager=logged_in_user) initial_staff = [{'staff': staff} for staff in staff_list] staff_qs = Staff.objects.none() StaffFormSet = modelformset_factory(Staff, form=StaffForm, formset=StaffModelFormSet, extra=len(staff_list), max_num=len(staff_list), validate_max=True) formset = StaffFormSet(queryset=staff_qs, initial=initial_staff) initial['initial_staff'] = initial_staff initial['StaffFormSet'] = StaffFormSet initial['formset'] = formset initial['staff_qs'] = staff_qs return initial def get_form_class(self, *args, **kwargs): return self.get_form() def get_form(self, *args, **kwargs): return self.get_initial()['formset'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = self.get_form() context['form_message'] = 'Update phone directory for your staff' return context def post(self, request, *args, **kwargs): StaffFormSet = self.get_initial()['StaffFormSet'] initial_staff = self.get_initial()['initial_staff'] submitted_form = StaffFormSet(request.POST, initial=initial_staff) if submitted_form.is_valid(): self.form_valid(submitted_form) print("This form is valid, Sir!") else: print("Non Form Errors: ", submitted_form.non_form_errors()) self.get_context_data()['formset'] = submitted_form self.form_invalid(submitted_form) return super().post(request, *args, **kwargs) def form_valid(self, form, **kwargs): saved_forms = form.save(commit=False) #Save forms here return … -
how to deploy ec2 instance using ASGI django application (apache2 production)
please any one help to solve this issues how to deploy ec2 instance using ASGI django application (apache2 production) .