Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django post_save: create_or_update not working
@receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses) for each in teachers: if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( pk=each.id, Students_Enrollment_Records=instance, Subject_Section_Teacher=each ) else: StudentsEnrolledSubject.objects.get( Students_Enrollment_Records=instance, Subject_Section_Teacher=each ) Inserting data is working perfectly but when I update the existing data it insert another data but not update, the update_or_create is not working -
Django: Cannot Add Clickable Link in the Template
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models for: Brand – details on brand, such as, name, origin, manufacturing since, etc Model – details on model, such as, model name, launch date, platform, etc Review – review article on the mobile phone and date published, etc Many-to-many relationship between Review and Model. I also have created views for the following: a. An index page that display all Brands available for mobile phone in the database b. A phone model page that display model when a brand is selected. c. A detail page when a model is selected that contain reviews and newslink Now, I am facing a problem. I cannot put any clickable link that will redirect the phone brands, like Apple and Samsung, of brandlist.html web page, to their respective phone model page (phonemodel.html). Here is the screenshot: Here are the codes of models.py inside "PhoneReview" folder. from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin … -
Testing That File Was Uploaded in Django
I am writing some unit-tests for an app. One of the features of this app is that it allows the user to upload videos to the server (or S3, depending on the configuration). The difficulty I am having is coming up with a meaningful unit-test for this. So, the question is two-fold. First, what is a solid way to test this functionality? Second, the following test fails because videofile entry in the dictionary is a string. Having done prints, I can see that in a real upload it is actually of type <class django.db.models.fields.files.FieldFile>. How should one go about creating this in a test to make the types similar to the real upload via the browser? class VideoFormTest(TestCase): def test_upload_form_valid(self): form = VideoForm(data={'title':"Test Video Title", 'videofile':"videos/navigator.mp4"}) self.assertTrue(form.is_valid()) -
How to deploy django project on docker?
I am deploying the Django project on Docker. I have no any knowledge about Django and dokcer, so please help me with example. -
Issue while trying to convert into class
This was my original code from django.shortcuts import render def login(request): if(request.method == "POST"): return render(request, 'login1.html') else: return render(request, 'login.html') Converted above code to class below. class login(View): def loginForm(self, request): return render(request, 'login.html') def authenticate(self, request): return HttpResponse("Inside Post") New Url.py file from django.urls import path from .import views app_name = 'authapp' urlpatterns = [ path('', views.login.loginForm(), name='loginForm'), path('', views.login.authenticate(), name='authenticate') ] I got an error loginForm() is missing 2 required positional arguments: self and request. Can you please suggest something? I was actually trying to convert the code into class. Everything was fine without class. -
Django filter listview by url parameter not working
I'm trying to filter the result of a ListView through a URL parameter but it is not working. What the webapp does is that in a session, many pictures can be saved, so the idea is through a search bar you can filter the sessions and see its pictures. I have tried using in the ListView which uses two models that are linked through a foreign key, the postgresql search lookup but it does not filter views.py class SessionPictures(generic.ListView): model = PostSession template_name = 'photoadmin/gallery.html' def get_context_data(self, **kwargs): context = super(SessionPictures, self).get_context_data(**kwargs) context['picture'] = Images.objects.filter( name__session_name__search='search') return context urls.py urlpatterns = [ path('', views.index, name='index'), path('upload', views.UploadView.as_view(), name='upload'), path('gallery/<search>/', views.SessionPictures.as_view(), name='gallery') ] models.py class PostSession(models.Model): session_name = models.CharField(max_length=25) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.session_name) class Images(models.Model): name = models.ForeignKey( PostSession, related_name='images', on_delete=models.CASCADE, null=True, blank=True) picture = models.ImageField(upload_to='pictures') The idea is to filter the sessions. I don't get an error, it just don´t filter. -
How To Fix Django Heroku Requirements Deploy Failure
I'm trying to deploy a staging version of my Django app to Heroku, and I'm receiving an error. The reason I mention that it's a staging app is that my production app is running fine, but I think maybe some packages updated since I set it up? The error is referencing python-http-client==3.1.0 which I don't understand, since my requirements.txt has python-http-client==3.2.1 I think I used Pipenv originally a long time ago but ended up switching back to not using it, and to be honest I'm a bit confused about it. I don't currently have a pipfile or pipfile.lock, yet Heroku says Installing dependencies from Pipfile.lock during deployment, so I'm at a loss. Here is the error: remote: -----> Installing python-3.6.5 remote: -----> Installing pip remote: -----> Installing dependencies with Pipenv 2018.5.18… remote: Installing dependencies from Pipfile.lock (d4a1e0)… remote: An error occurred while installing python-http-client==3.1.0! Will try again. remote: Installing initially–failed dependencies… remote: Collecting python-http-client==3.1.0 remote: Using cached https://files.pythonhosted.org/packages/5c/5c/9e0cde562757bdb385a3644235e7c4da6f76c8a43d573eb76384ef461d40/python_http_client-3.1.0-py3-none-any.whl remote: remote: THESE PACKAGES DO NOT MATCH THE HASHES FROM Pipfile.lock!. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them. remote: python-http-client==3.1.0 from https://files.pythonhosted.org/packages/5c/5c/9e0cde562757bdb385a3644235e7c4da6f76c8a43d573eb76384ef461d40/python_http_client-3.1.0-py3-none-any.whl#sha256=84267d8dcb7bcdf4c5cef321a533cc584c5b52159d4a4d3d4139bfed347b8006 (from -r /tmp/pipenv-6k8jlqu1-requirements/pipenv-73gxws2n-requirement.txt (line … -
How to block an ip address in httpd.conf [duplicate]
This question already has an answer here: Apache block an ip address from accessing the website 2 answers Blocking multiple ip ranges using mod access in htaccess 1 answer My website was hit by a few ip's continuously sending bad requests with some garbled parameters causing a large amount of error output in log file. At a peak the attack could reach 6000-7000 hits an hour. I am trying to block these ip's in httpd.config file. Here is what I have. But these ip's are still coming through. Note: I also loaded authz_host_module and tried to use directive with no success. ServerRoot "/home/myapp/apache2" LoadModule authz_host_module modules/mod_authz_host.so LoadModule authz_core_module modules/mod_authz_core.so LoadModule dir_module modules/mod_dir.so LoadModule env_module modules/mod_env.so LoadModule log_config_module modules/mod_log_config.so LoadModule mime_module modules/mod_mime.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule wsgi_module modules/mod_wsgi.so LoadModule unixd_module modules/mod_unixd.so LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog /home/myapp/logs/access_orchidroots.log combined ErrorLog /home/myall/logs/error_orchidroots.log Listen 28277 KeepAlive Off SetEnvIf X-Forwarded-SSL on HTTPS=1 ServerLimit 1 StartServers 1 MaxRequestWorkers 5 MinSpareThreads 1 MaxSpareThreads 3 ThreadsPerChild 5 SetEnvIf X-Forwarded-For 185\.166\.240\.100 blocked SetEnvIf X-Forwarded-For 46\.229\.168 blocked SetEnvIf X-Forwarded-For 176\.214\.210\.197 blocked SetEnvIf X-Forwarded-For 91\.102\.75\.95 blocked SetEnvIf X-Forwarded-For 91\.242\.162\.7 blocked WSGIDaemonProcess orchidroots processes=2 threads=12 python-path=/home/myapp:/home/myapp/myproject:/home/myapp/lib/python3.7 WSGIProcessGroup myapp WSGIRestrictEmbedded On WSGILazyInitialization On … -
Integrate django rest auth with django allauth
I am trying to integrate django rest auth with django allauth. I installed them both as their documentation says and I have issue with configuring the routes. This is what I made in my urls file: urlpatterns = [ re_path(r'^auth/', include('rest_auth.urls')), re_path(r'^auth/signup/', include('rest_auth.registration.urls')), ... ] The registration works fine, but on my confirmation email that I receive there is a link. Clicking on that link gives 500 status code with the following exception: TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()' What did I do wrong? how should I configure django rest auth and django allauth? Is there any tutorial that provide step by step instructions (I am new to django)? -
ValueError: Missing staticfiles while deploying Django app to Heroku with Whitenoise
I've followed several tutorials on how to deploy a Django app with static files- however, I'm having no luck getting this working! Settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) del DATABASES['default']['OPTIONS']['sslmode'] Example template file: {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> Error: ValueError: Missing staticfiles manifest entry for 'vendor/fontawesome-free/css/all.min.css' Thanks so much! -
Django simple annotation across two models
I've got three models, User, Achievement, and UserAchievement: class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) ... class Achievement(models.Model): name = models.CharField(max_length=64) points = models.PositiveIntegerField(default=1) class UserAchievement(models.Model): # Use a lazy reference to avoid circular import issues user = models.ForeignKey('users.User', on_delete=models.CASCADE) achievement = models.ForeignKey(Achievement, on_delete=models.CASCADE) I'd like to annotate Users with a 'points' column that sums up the total points they've earned for all their achievements as listed in the UserAchievement table. But clearly I'm not fully up to speed with how annotations work. When I try: users = User.objects.annotate(points=Sum('userachievement__achievement__points')) for u in users: print(u.email, u.points) It crashes with: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/dylan/.local/share/virtualenvs/server-E23dvZwD/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File "/Users/dylan/.local/share/virtualenvs/server-E23dvZwD/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/dylan/.local/share/virtualenvs/server-E23dvZwD/lib/python3.7/site-packages/django/db/models/query.py", line 78, in __iter__ setattr(obj, attr_name, row[col_pos]) AttributeError: can't set attribute -
Django database objects not showing on the template
Am i am rendering django objects using django_tables and the for loop iteration but both methods aren't working i am trying to render objects saved in the database by a modelform. My first approach i used the django_tables2 which returned non-type object. currently i have used the for loop to iterate through the objects but the object values are not being displayed. what intrigues me is that all rows are being returned with no data. kindly help. models.py keynumber=models.CharField(max_length=10); workorder=models.CharField(max_length=50); contrator=models.CharField(max_length=50); contrator_contact=models.IntegerField(); assigned_name=models.CharField(max_length=50); assigned_ID=models.IntegerField(); assigned_contact=models.IntegerField(); date_to_return=models.DateField(); class Meta: managed=False db_table='ieng_mis_issuekeys'``` views.py ```def issuetable(request): query_set=zip(Issuekeys.objects.all()) context={'query_set': query_set} return render(request, 'keymanager.html',context)``` url.py ```url(r'^keymanager$', views.issuetable,name='keymanager'),``` keymanager.html ```<div class="bg-light" style="margin-top: 1em; margin-left: 1mm"> <table class="table table-hover"> <tbody> <tr> <th scope="col">Key Number</th> <th scope="col">Work Order</th> <th scope="col">Contractor</th> <th scope="col">Assignee Name</th> <th scope="col">Assignee Contact</th> <th scope="col">Date issued</th> </tr> {% for key in query_set %} <tr> <td>{{key.keynumber}}</td> <td>{{key.workorder}}</td> <td>{{key.contractor}}</td> <td>{{key.assigned_name}}</td> <td>{{key.assigned_contract}}</td> <td>{{key.date_to_return}}</td> </tr> {% endfor %} </tbody> </table> </div>``` output -
Is it possible for Models to know which tenant is using it?
I'm offering a SaaS, mostly as a django dashboard and customized admin panel. Using tenants I have one schema per customer sharing a database. The problem I have is that the customer should be able to create objects through the admin page and the objects should create an url with information about the tenant. For example customer Y's url would be Y.xzxzxz.com and customer X's url would be X.xzxzxz.com. There will be multiple types of urls with the same prefix. Currently I the customers have to manually input the customer prefix. Is it possible for the Models class to know which schema is using it? -
Pillow installed, but getting “no module named pillow”
i can't import PIL even when i installed it ? -
Django using __init__ method in classes extending (admin.ModelAdmin)
I am fairly new to Django. I have an admin.Models extended class that's pretty typical (has list_display, search_fields, etc). It looks something like this: class FooAdmin(admin.ModelAdmin): list_display = ( 'all', 'my', 'things', ) ... admin.site.register(Foo, FooAdmin) My problem is that this ModelAdmin loads somethings from a model with something like foo_list = Foo.objects.filter(group__name='something'). Because this is a heavy task, I'd like to do it once on initialization, and then use the same thing over and over again when specifying custom "_field" functions. My thoughts are to do this in the __init__ method of this class, but when implement my own constructor, it doesn't register with Django as a url; i.e. class FooAdmin(admin.ModelAdmin): def __init__(self, *args, **kwargs): super(Foo, self).__init__(*args, **kwargs) list_display = ( 'all', 'my', 'things', ) ... # This register portion removed. # admin.site.register(Foo, FooAdmin) The above will "build" correctly and run, but attempting to visit the site says the URL is not found (not surprising since I removed the register part). However, when I add the register portion back in, I get a message about a misuse of my constructor, i.e adding back the admin.site.register and running python manage.py runserver ... results in something like: TypeError: super(type, obj): obj … -
Django/uWSGI site not loading static assets when accessed from URL, loads fine when accessed from IP address
When going to http://159.89.34.173 the site loads fine. However, when going to http://cometthon.org the site either doesn't load entirely, or doesn't load static resources (such as images, JS, and CSS). I'm running on a Digital Ocean server, spawning uwsgi with the following command: uwsgi --http :80 --home ~/comet_env/ --chdir ~/CometTHON/ -w CometTHON.wsgi -p 5 -M *I know this isn't best practice, but I'm just trying to get this thing up and running Here's my domain configuration: I've watched the uWSGI logs, when trying to connect from the URL-side I don't see any activity in the logs. My allowed_hosts is set to all, so I know that's not the problem. -
unable to display Image in a Django Template (using ImageField)
i'm uploading an image from the admin site into the imagefield of the model.i've made the necessary changes in the settings.py and urls.py file and added the media directory in my project. Although the image shows up in the admin site, i get "The 'image' attribute has no file associated with it" error while rendering the template. here are my files: template(users.html) <!DOCTYPE html> {% load static %} <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href=""> </head> <body> <h1>Here are your users</h1> {% if user_list %} <ol> {% for user in user_list %} <li> User Info</li> <ul> <li>First Name:{{user.f_name}}</li> <li>Last Name:{{user.l_name}}</li> <li>Email:{{user.email}}</li> <li>Image:<img src="{{ user.image.url }}"></li> </ul> {% endfor %} </ol> {% endif %} </body> </html> models.py from django.db import models # Create your models here. class User(models.Model): f_name=models.CharField(max_length=20) l_name=models.CharField(max_length=20) email=models.EmailField() image=models.ImageField(upload_to='pictures',null=True,blank=True) def __str__(self): return (self.f_name+" "+self.l_name) views.py from django.shortcuts import render from django.http import HttpResponse from .models import User # Create your views here. def index(request): return HttpResponse("<em>My Second Project</em>") def help(request): helpdict = {'help_insert':'HELP PAGE'} return render(request,'appTwo/help.html',context=helpdict) def dispUsers(request): user=User.objects.order_by('f_name') user_dict={"user_list":user} return render(request,'appTwo/users.html',context=user_dict) settings.py """ Django settings for ProTwo project. Generated by 'django-admin startproject' using Django 2.0.5. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list … -
Django pagination does not match input Query
I have a bit of code that looks something like this. page_objects = Page.objects.exclude(lorem).filter(blah).annotate(key=bar).order_by(foo) paginator = Paginator(page_objects, 50) On my UI, I notice that with certain values of bar, I am missing rows in the output. I ran an experiment to compare the output of paginator against that of the query. page_results = [] for page_number in paginator.page_range: result = paginator.page(page_number) page_results += result.object_list paginator_ids = sorted([x.id for x in page_results]) page_object_ids = sorted(x.id for x in list(page_objects)) print(paginator_ids == page_object_ids) => FALSE print(len(paginator_ids) == len(page_object_ids)) => TRUE As you can see, the list of objects in the query and the list of all objects in the paginator did not match. I visually inspected the lists to confirm that this is correct (the ids in the two lists are clearly different). I am on Django==1.11.3 What is going on and why is my paginator not behaving like the docs? Interestingly, if I change the order_by to order_by(foo, 'id'), the paginator behaves as expected. -
Exception Value: no such table: vacancy_list_advuser
I added user class for registration AdvUser When I want to login or register, or createsuperuser I receive error: Exception Value: no such table: vacancy_list_advuser File "/home/alex/dev/python/django/junjob/myvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 305, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: vacancy_list_advuser What I did Checked AUTH_USER_MODEL = 'vacancy_list.AdvUser' # <app_name.model_name> Removed all migrations in vacancy_list/migrations then did makemigrations and migrate python manage.py migrate --run-syncdb What should I do to solve problem? My code: models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser from django.db import models from django.dispatch import Signal from .utilities import send_activation_notification class Company(models.Model): name = models.CharField(max_length=200) about = models.TextField() def __str__(self): return self.name class Vacancy(models.Model): company_key = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField(max_length=200) salary = models.CharField(max_length=200, default='40.000') text = models.TextField(default="The text about vacancy") city = models.CharField(max_length=200, default='Москва') date_str = models.CharField(max_length=50, default='12 сентября') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class AdvUser(AbstractUser): """ Model of user for registration """ is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Прошёл активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещёния о новых комментариях?') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) urls.py urlpatterns = [ path('', HomePageView.as_view(), name='vacancy_list'), path('search/', … -
How to encapsulate specific file parsing Django REST framework
I would like to create parsers for several types of files when I uploading them. After parsing i want to create model for each uploaded file. I create a function that takes xyz file and parse it to dict. I create an APIView, which handle request and applicate my function: I need more convenient and flexible code where each class has single responsibility. I think I need DRM serializers and parsers. But how I can connect them? views.py class parseXYZfile(generics.CreateAPIView): # serializer_class = parseXYZFileSerializer # parser_classes = [XYZFileParser] def post(self, request): files_data_list = request.FILES.getlist("files") d = {} for data in files_data_list: path = default_storage.save('tmp/tmp_file.xyz', ContentFile(data.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) d[str(data)] = parseXYZ(tmp_file) os.remove(tmp_file) return Response(d) -
How to access Django Model Fields from save_formset
I have an Inline Model in Django model admin , and I need to create a condition before saving the items, here is the code am using : class PRCItemInline(admin.TabularInline): def get_form(self, request, obj=None, **kwargs): form = super(PRCItemInline, self).get_form(request, obj, **kwargs) form.base_fields['product'].widget.attrs['style'] = 'width: 50px;' return form ordering = ['id'] model = PRCItem extra = 1 autocomplete_fields = [ 'product', 'supplier', ] fields = ( 'product', # 1 'quantity', # 2 'unitary_value_reais_updated', # 4 'issuing_status', 'approval_status', 'receiving_status', ) readonly_fields = ['issuing_status', 'approval_status', 'receiving_status', ] def save_formset(self, request, form, formset, change): obj = form.instance if obj.purchase_request.is_analizer: return HttpResponse("You can't change this") else: obj.save() As you see, I used the save_formset method to be able to reach the fields of the model, and then filter based on it. but it just saves the items no matter the If statement I added. -
How to calculate number of remaining monthly recurring dates between now and a date in the future in Django with Postgres
I have a Django application with Django Rest Framework that is storing records in Postgres. A Vehicle model has an end_date DateField that represents the final payment date of a finance agreement, and a monthly_payment FloatField that represents the payment amount. The finance payment is made monthly, on the same day of the month as the final payment (e.g. if end_date is 25/01/2020, a payment is made on the 25th of every month between now and 25/01/2020 inclusive.) I have a ListVehicle ListCreateAPIView that returns a paginated list of vehicle records. I am using a custom PageNumberPagination class to return a data object alongside the results array that is populated by aggregating some of the fields in the Vehicle model. I want to include a field in this data object that contains the total remaining amount left to pay on all of the Vehicle entities in the database. I have tried using @property fields in the model that calculate the total remaining amount for each Vehicle, but you can't aggregate over calculated properties (at least not with queryset.aggregate), so the following solution did not work: @property def remaining_balance(self): return max(self.remaining_monthly_payments * self.monthly_payment, 0) @property def remaining_monthly_payments(self): now = datetime.datetime.now() end … -
"GET /static/my_style.css HTTP/1.1" 404 1660
Im getting this error "GET /static/my_style.css HTTP/1.1" 404 1660 in my terminal whenever I update my page I build. I think it's my code in my settings.py that is wrong and with the static files also. Tried different thing but still not working My static code right now STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] This type of error [06/Nov/2019 19:54:58] "GET /static/my_style.css HTTP/1.1" 404 1660 -
ValueError: invalid literal for int() with base 10: '<view class>'
I try to update value in database but it show ValueError at /edit_account/edit_account invalid literal for int() with base 10: 'edit_account' Why it send to 'localhost:8000/edit_account/edit_account'. It should 'localhost:8000/useraccount' when I save the value. views.py def edit_account(request, id): user = User.objects.get(id=id) user = { 'user':user, } if request.method == 'POST': user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.save(user.last_name, user.first_name) return redirect('useraccount') else: return render(request, 'polls/edit_account.html', user) urls.py path('edit_account/<id>', views.edit_account, name='edit_account'), templates <form action="edit_account" method="POST"> {% csrf_token %} <div class="form-group"> <label for="username1">Username: {{user.username}}</label><br> <label for="first_name">First name</label> <input type="text" class="form-control" name="first_name" value="{{user.first_name}}"> <label for="last_name">Last name</label> <input type="text" class="form-control" name="last_name" value="{{user.last_name}}"> </div> <div class="form-group"> <button type="Submit" class="btn btn-success">Save</button> </div> </form> -
Django - multiple inline forms validate 1 formset using another formset data
I have a main Model: MainModel -> MainModelForm that's used in a view I also have 2 inline forms that have the MainModel as primary key InlineModel1 => InlineModel1Form (formset = CustomOperatorFormset(BaseInlineFormset)) which has it's own set of validations. It is a 1 or none setup, I.e. it's not required, but once it's added, it has some validations in place. Using the CustomSetup from BaseInlineFormSet is working great. However, I have another model - InlineModel2 which is not required - until the user has entered atleast 1 row in InLineModel1Form. I'm losing hair over how to send/validate this, i.e using InlineModel1form data and check if there are any rows added, in InlineModel2Form Form. I need both set of inline forms setup separately, so a mixin showing everything in 1 place wouldn't work for me.