Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configure django server in httpd with reverse proxy
I have an application running on django server 1.8x which I need to configure in apache httpd server 2.2.x using reverse proxy method. I tried making changes in sites-available/000-default.conf, but it didn't worked. It tried to navigate but it got timed out. My httpd server is running on port 80 and django server on port 8000. Since I am new to django and httpd, so needs assistance. -
How to get Django forms data and use it for further processing and rendering ?
I am very new to Django and learning with my own I am able to build few basic app and I can say my concept about Django views, urls and models are quite clear but forms are quite confusing topic for me. And I am not able to deal with it.. Lets assume one situation. I have created one form "Calculator" gets two values from user with the mathematical operator addition, subtraction or multiplication : example: My form: value_1 = 8 Value_2 = 6 Math_op = + now I define a calculator function in views which gets values from the form and do some math and generates results like this Answers = 14 Now I want to transfer this result or answers variables value to a new webpage to show out put of calculator event. My confusion is that how can I define a url for this case and how can i define a method which takes value from template and render this value to another form template. -
Media optimisation - AWS web app
I am in the process of building a web based application (Django, Angular on AWS). The application will be media heavy as in users will be uploading lots of images, videos and recordings. Currently we are storing these in S3. Any thoughts on the best approach to 1. Minimize storage 2. Reduce data transfer 3. Not drastically impact the image/video quality. Thanks in advance. -
Python request download a file and save to a specific directory
Hello sorry if this question has been asked before. But I have tried a lot of methods that provided. Basically, I want to download the file from a website, which is I will show my coding below. The code works perfectly, but the problem is the file was auto download in our download folder path directory. My concern is to download the file and save it to a specific folder. I'm aware we can change our browser setting since this was a server that will remote by different users. So, it will automatically download to their temporarily /users/adam_01/download/ folder. I want it to save in server disk which is, C://ExcelFile/ Below are my script and some of the data have been changing because it is confidential. import pandas as pd import html5lib import time from bs4 import BeautifulSoup import requests import csv from datetime import datetime import urllib.request import os with requests.Session() as c: proxies = {"http": "http://:911"} url = 'https://......./login.jsp' USERNAME = 'mwirzonw' PASSWORD = 'Fiqr123' c.get(url,verify= False) csrftoken = '' login_data = dict(proxies,atl_token = csrftoken, os_username=USERNAME, os_password=PASSWORD, next='/') c.post(url, data=login_data, headers={"referer" : "https://.....com"}) page = c.get('https://........s...../SearchRequest-96010.csv') location = 'C:/Users/..../Downloads/' with open('asdsad906010.csv', 'wb') as output: output.write(page.content ) print("Done!") Thank … -
git rm -rf --cached causes remove db. &merge conflict git
What I want to do is I do not want the locally changed db to be applied to the server and I use Github to handle files. I wrote db.sqlite3 in '.gitignore' file. But it doesn't work. So I did git rm -rf —cached . and git add, commit, push. The problem is that, in spite of there's DB.sqlite3 file in my local, it causes to remove the db.sqlite3 in GitHub. How can I apply db.sqlite3 gitignore without git rm -rf --cached. ? When I git pull in ubuntu(AWS, ubuntu instance). The error happens below. your local changes to the following files would be overwritten by merge: health/db.sqlite3 health/nohup So, I did sudo git stash And, when I git pull, Automatic merge failed: fix conflicts and then commit the result git status unmerged paths: deleted by them : db.sqlite3 both modifiled : management/__pacache__/forms.cpython-35.pyc Because, in git there's no db.sqlite3. But I want to store my db in ubuntu server. How I solve the problem?? -
Office 365 with allauth
We are creating an application for use in our organization, but we only want people in our organization to be able to use the app. We had the idea of using Microsoft's OAuth endpoint in order to authenticate whether a user is part of our org or not. The idea is to bring up a sign in screen where the user can enter their Office 365 username and password, which will then allow them to use our app upon submission of their credentials. Our app is running on Django, and I've only found a solution to this problem using Flask and Microsoft's Graph API connect sample for Python. This sample uses a similar idea to the one above to log in to the app. Could anyone help direct me to where I could find a similar method of authentication for Django? ^^Question I posed earlier on another post. It seems like the best way to implement this feature, but Office 365 unfortunately isn't in the allauth providers list. Is there a way to implement Office 365 with allauth? -
django rest get instance of validator field of serializer
I need to get the instance of the serializer field validator. I have not found such information on the Internet... If i have a model: class MyModel(models.Model): file = FileField(max_length=200, storage=Storage(), upload_to=get_file_path, validators=FileValidator(max_size=10*1024*1024)) I can get the instance of validator somehow this way MyModel._meta.get_field('file').validators[0] I need it for an example to mock max_size attribute in tests with mock.patch.object(target=Mymodel._meta.get_field('file').validators[0], attribute='max_size, new=1) Now I have another model for which validation occurs on the serializer class TextItemFileSerializer(serializers.Serializer): attachments = SomeCustomField(validators=[ArrayMaxLengthValidator(limit_value=30)]) and I need to mock limit_value in the same way as for the model via the validator instance But the problem is that I do not know how to access to the instance of validator. Are there any ideas? -
Save multiple data using loops in django models using save function with admin save button
I'm trying to save data in loops from django admin. As i press it should save in database with same argument except one field which will have different value in each row. class DealersList(models.Model): dealers_company = models.CharField(unique=True,max_length=100) concern_district = models.CharField(max_length=25, choices=CITY_CHOICES, default=False) address = models.CharField(max_length=50) vdc = models.CharField(max_length=30) contact_person = models.CharField(max_length=50,blank=True) phone_number = models.CharField(max_length=14,blank=True) email = models.EmailField(max_length=70,blank=True, null= True, unique= True) And my SimDetail class which will have save() function contains a ForeignKey too class SimDetail(models.Model): mobile_no = models.BigIntegerField("Mobile Number",unique=True) number_of_sim = models.IntegerField() agent = models.ForeignKey('DealersList',on_delete=models.CASCADE,to_field='dealers_company') sim_activation_date = models.DateField(auto_now=False, auto_now_add=False) submission_date = models.DateField(auto_now=False, auto_now_add=False) remarks = models.TextField(null=True,blank=True,validators=[MaxLengthValidator(200)]) def save(self,*args, **kwargs): ite=0 for x in xrange(0,self.number_of_sim): self.mobile_no=self.mobile_no+ite ite=1 super(SimDetail, self).save(*args, **kwargs) Currently it's only saving last data which i think(i may be wrong) might being replaced again and again so at last it only stores the last value. Can anyone help me, i'm trying to use it from admin only without using forms. -
Django load model folder images
I have a user model similar to this: def usr_img_path(instance, filename): return 'Usr/{}/{}'.format(instance.name, filename) class User(models.Model): name = models.CharField(max_length = 20) images_folder = models.ImageField(upload_to=usr_img_path) so this uploads an image to the user's name folder. The problem is.. I'd like to have more than 1 image in that folder.. How do I fetch them? I tried something like this in a template: {% for user in users %} {% for image in user.images_folder %} <p>{{image.name}}</p> {% endfor %} {% endfor %} but this didn't work. Should I make models for the Folder and the Images or is there a better way? -
Django Template Tags in Angular Partial
I'm trying to build a single page application with a state router which contains no specified URL. All HTML is dynamically rendered at the root of the server making use of Angular partials. My only question is how would I render server side template tags in addition to the client side angular injection, for instance a form. <h1>{$ ngTitle $}</h1><!-- example of Angular injection --> <ng-include src = "'/static/partials/navbar/anonymous.html'"></ng-include> <!-- form that I am trying to inject from context --> <form method = "POST" action = "/login/"> {% csrf_token %} {{ form.as_p }} <input type = "submit" value = "Sign In"> </form> As it now stands my Django template tags are rendered as verbatim text. I understand that this is a result of the order of parsing and interpretation. Django first interprets the template, Angular then interprets all the partials, never for Django to then interpret the partials as well. Is there a work around? I've looked into third party packages and I haven't really found much that could be of use. -
Django Autocomplete Light override html options to return custom value
I am starting to use DAL, but I cannot use the default behavior that set the value to the PKs of the objects in my queryset. So I overriden the 'get_result_value' function to set a custom field as the value of my options. class CategoryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): country = Agent.get_user_country(self.request.user) if not self.request.user.is_authenticated(): return Category.objects.none() qs = Category.objects.filter(country=country) if self.q: qs = qs.filter(full_category__icontains=self.q) return qs def get_result_value(self, result): return result.special_key My issue is that when I submit I get this ModelChoiceField error: Select a valid choice. That choice is not one of the available choices. Here is the Form: class OnsiteCategoryForm(forms.Form): category = forms.ModelChoiceField(queryset=Category.objects.all(), required=True, widget=autocomplete.ModelSelect2(url='category_autocomplete')) Do you have any idea of what could be causing this error ? Thanks -
How to POST with a field which is not specified in Form's Meta fields?
I wanted to just add referenceData to the class Meta fields and use it, but the number of options for <select> was too high, so instead of doing this I added a reference field to the ModelForm and then read the data record referenced by this value. However, when POST is done, only referenceData field is missing and data is created. views.py class CorrectView(IndexView): ... form_class = DataCorrectForm ... def post(self, request, *args, **kwargs): form = self.form_class(request.POST or None) if form.is_valid(): the_form = form.save(commit=False) the_form.clean() # HERE ! the_form.save() # HERE ! return self.form_valid(form) else: return self.form_invalid(form) forms.py class DataCorrectForm(forms.ModelForm): reference = forms.IntegerField() def clean(self): cleaned_data = super(DataCorrectForm, self).clean() cleaned_data['referenceData'] = DataNeedsCorrection.objects.get(data_id=cleaned_data['reference']) # I extract a record that matches data_id and assign it to the form data return cleaned_data def save(self, commit=True): return super(DataCorrectForm, self).save(commit=commit) class Meta: model = DataCorrected fields = [ 'reference', # 'referenceData', # If I comment this out it works! but not that I wanted 'correctedText', ] If I comment out the 'referenceData', at least POST works and data record is properly created but it is a method that can not be adopted. models.py class DataCorrected(models.Model): data_id = models.AutoField(primary_key=True) referenceData = models.ForeignKey('DataNeedsCorrection', on_delete=models.CASCADE, null=True) correctedText = … -
How to use Django with Azure's CosmosDB?
I'm curious if it is possible to use CosmosDB as the database backend for Django projects. -
Django Form - Select a valid choice. That choice is not one of the available choices
I have a formset (InvoiceItemForm) where the initial form is created by Django, but for adding aditional forms to the formset I use Jquery. Inside this forms there is a select field (product). The first form of the select is generated by ModelChoiceField, but the rest are generated and populated dynamically using ajax. When I get the request, the first one (generated by django) does not have problems, but the rest show this form.error in the product field: Select a valid choice. That choice is not one of the available choices. What I am doing wrong? I checked the forms and I don't see differences between the generated by ModelChoiceField and the ones with Jquery Model class Invoice(models.Model): number = models.CharField(max_length=200) def __str__(self): return self.number class Product(models.Model): description = models.CharField(max_length=200) measurement_unit = models.CharField(max_length=200) def __str__(self): return self.description class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, related_name='items') product = models.ForeignKey(Product) unit_price = models.DecimalField(max_digits=8, decimal_places=2, default=0) quantity = models.DecimalField(max_digits=8, decimal_places=2, default=0) Forms.py class InvoiceItemForm(forms.Form): product = forms.ModelChoiceField(queryset=Product.objects.all().order_by('description')) unit_price = forms.DecimalField(max_digits=8, decimal_places=2, widget=forms.TextInput(attrs={'placeholder': 'Precio', 'class': 'rate'})) quantity = forms.DecimalField(max_digits=8, decimal_places=2, widget=forms.TextInput(attrs={'placeholder': 'Cantidad', 'class':'quantity'})) class InvoiceForm(forms.Form): number = forms.CharField() Views.py def invoice(request): InvoiceFormSet = formset_factory(InvoiceItemForm) if request.method == 'POST': invoice_form = InvoiceForm(request.POST) formset = InvoiceFormSet(request.POST) if invoice_form.is_valid(): … -
Cant seem to assign the right values in a formset django
I have a view that has a formset that is created and validate. There is a queryset within the same view that takes the number of results in a query and uses that number to determine the number of forms in the queryset. When the formset is submitted it has default labels like the following: form-TOTAL_FORMS '4' form-INITIAL_FORMS '0' form-MIN_NUM_FORMS '0' form-MAX_NUM_FORMS '1000' form-0-amount '1.11' form-0-description 'gbsabf' form-1-amount '2.22' form-1-description 'hbsaefrdg' form-2-amount '3.33' form-2-description 'dfsasdfg' form-3-amount '1.23' form-3-description 'hfsbdf' tax '2.21' tip '3.12' submit 'submit' I have a query set that used to determine the number of forms that I have. I want to go through the queryset and each form in the formset and assign the first form's values with the first result of the query set and then go to the next form's values and the second result from teh query set and assign the form values to the query result... I have not idea how to get them to run similtaniously. Example: query results = josh, jake, james, jacob. fromset = form-1, form-2, form3, form4 I want to run both of the queries and assign the form value to query result josh.amount = form-1-amount josh.description = form-1-description … -
Accessing static in django
I'm having trouble sorting my static directory and linking css files through templates in html pages with django. I keep getting the error "Not Found: /CSS/bootstrap.min.css" I know this is a problem with how my directory is set up in settings.py but I can't seem to fix the issue. Below is my code for settings.py and layout.html (the page i'm using the call the css file). layout.html {% load staticfiles %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Testing {% block title %}{% endblock %}</title> <link href="{% static 'css/bootstrap.min.css' %}" type="text/css" rel="stylesheet"> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> </html> settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = 'C:/Users/Luke/Desktop/Capstone/CapstoneNotespool/capstonenotespool/capstonenotespool/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] -
How do I send the selected value of a drop down menu to an email in django
I have this site where the user can fill out a form and when they hit submit all the results of the form get sent to me in an email. All the parts of the form get sent except for their choice from a drop down menu. Does anyone know where I went wrong in my code? Here is my forms.py CONDOS=[ ('silvermountaincondo', 'Silver Mountain Condo'), ('redhillcondo', 'Red Hill Condo'), ('lakesidecondo', 'Lakeside Condo'), ('pointeplacecondo', 'Pointe PLace Condo'), ('rhodesviewcondo', 'Rhodes View Condo'), ] class ContactForm(forms.Form): contact_name = forms.CharField(required=True, label='Full name') contact_email = forms.EmailField(required=True, label='Email Address') contact_phone = forms.CharField(required=True, label='Phone number') condo = forms.ChoiceField(required=True, label='Which condo would you like to reserve?', choices=CONDOS) arrival_date = forms.DateField(required=True, help_text='Please enter your arrival date (YYYY-MM-DD)') departure_date = forms.DateField(required=True, help_text='Please choose your departure date (YYYY-MM-DD)') Here is my views.py def contact(request): form_class = ContactForm if request.method =='POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name', '') contact_email = request.POST.get('contact_email','') contact_phone = request.POST.get('contact_phone','') condo = request.POST.getlist('condo','') arrival_date = request.POST.get('arrival_date','') departure_date = request.POST.get('departure_date','') template = get_template('contact_template.txt') content = template.render({ 'contact_name': contact_name, 'contact_email': contact_email, 'contact_phone': contact_phone, 'condo': condo, 'arrival_date': arrival_date, 'departure_date': departure_date, }) send_mail( "New Booking from vacationcondos.vegas", content, "www.vacationcondos.vegas" + '', ['email@gmail.com'], #headers = {'Reply-To': contact_email} ) return redirect('Properties/contact') … -
Django / Azure : serving static files in production
I want to deploy a Django website hosted in an Azure Web App. The static files are served perfectly in DEBUG mode (DEBUG=False), but I can't find the right settings to have the server take care of it in production. All my static files are collected in a "static" directory at the app root wwwroot/static/. Here is the web.config, at the root of the application. <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="MyApp.wsgi.application" /> <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" value="D:\home\site\wwwroot\env\Scripts\python.exe" /> <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_venv_handler()" /> <add key="PYTHONPATH" value="D:\home\site\wwwroot" /> <add key="DJANGO_SETTINGS_MODULE" value="MyApp.settings" /> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgit.log"/> </appSettings> <system.webServer> <handlers> <add name="PythonHandler" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\Python34\python.exe|D:\Python34\Scripts\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> <rewrite> <rules> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> I also added the following web.config in the static directory: <?xml version="1.0"?> <configuration> <system.webServer> <!-- this configuration overrides the FastCGI handler to let IIS serve the static files --> <handlers> <clear /> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" resourceType="Either" requireAccess="Read" /> </handlers> </system.webServer> I also defined the static directory as a "virtual directory" in the web app settings, with "\static" refering to "\site\wwwroot\static", and checking the … -
django.db.migrations.exceptions.NodeNotFoundError:
I happen to mess up my migration files ended up deleting everything in the folder trying to fix django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0010_user_following dependencies reference nonexistent parent node ('account', '0006_contact') But failed to solve it I have been through a lot of online proposed solutions but to no avail I even flush the database but it gives the same Traceback error whenever I try to run python manage.py makemigrations. Thanks for help in advance -
Django admin: Creating a form for handling one field's entries, nesting it in another form
This is mainly for django admin, which I'm new to. I have a model called Statements with a field called statement-contexts. statement-contexts creates a manytomany relationship with another model, Contexts. Contexts are words (so the first field they have is "word") but they have to be paired with Keywords, another model that's basicaly another set of words. On my admin page for adding statements, django default settings don't leave the best way to enter in multiple new statement-contexts. While it generates a pop-up menu to create a context, this won't be the most user friendly for the website's future use in which people will enter a large amount of statement-contexts with corresponding keywords. So I've been looking for a way to change this formatting. My experience with admin is very little, so doing any formatting change to it is very confusing to me. I've been to led to the the idea of django formsets being the best way for me to make these changes while not making a totally new template for the admin site. I found this tutorial http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html and actually, the first gif contained is ideally what I would like to make. Even the process detailed is helpful. … -
Django Runtime error
I'm creating a django application and I recently installed django tinymce. I added the app to my settings.py. But when I try to migrate, I get this error: Unhandled exception in thread started by <function wrapper at 0x7fec01852d70> Traceback (most recent call last): File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/agozie/kingdom-ambassadors/kingdom/urls.py", line 23, in <module> url(r'^', include('blog.urls')), File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/home/agozie/anaconda2/envs/my_env/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/agozie/kingdom-ambassadors/blog/urls.py", line 2, in <module> from blog import views File "/home/agozie/kingdom-ambassadors/blog/views.py", line 8, in <module> from .forms import RegisterForm, LoginForm, CommentForm File "/home/agozie/kingdom-ambassadors/blog/forms.py", line 7, in <module> … -
Django channels without virtualization?
I wanted to try Django channels really bad :) However, my processor does not support virtualization technology. I've tried several ways, but at some stage virtualization was always required. So, is it even possible to use channels without virtualization? Or do I have to change my whole computer/processor? -
Django - Prevent database hit when rendering ModelForms with an especified queryset
As the title says, every time I render a ModelForm with an especified queryset, it makes a database hit to retrieve the choices, even if I'm using "prefetch_related" beforehand. For context, I'm making a polls app. Each poll has a set of questions, and each question has a set of choices. The models are as follows: class Poll( models.Model ): name = models.CharField( max_length = 100 ) class Question( models.Model ): poll = models.ForeignKey( Poll ) class Choice( models.Model ): question = models.ForeignKey( Question ) text = models.CharField( max_length = 100 ) class Answer( models.Model ): question = models.ForeignKey( Question ) selectedChoice = models.ForeignKey( Choice ) I also have a ModelForm to manage the answer of a question. It receives the queryset of choices in its constructor so that only you can select a choice related to that question (otherwise choices from all questions will be available to select.) class AnswerForm( ModelForm ): class Meta: model = Answer fields = ["selectedChoice"] def __init__( self, *args, **kwargs ): choices = kwargs.pop( "choices" ) super( AnswerForm, self ).__init__( *args, **kwargs ) self.fields["selectedChoice"].queryset = choices Finally, in a view I get the poll I want to answer along with all its questions and … -
How to have Django test files in a "tests" folder?
The structure of my project is as follows: project_name api Now, when I had all of my tests*.py files in the 'api' folder then everything ran fine. Specifically, this worked fine: response = self.client.post('/graphql/?query=...') But when I tried to create a folder called "tests" and place all of my tests in it, then the aforementioned line of code didn't work. I know it's some kind of relative referencing issue but I don't know how to fix it. Any suggestions? Robert -
Cant call and validate a formset in Django
I have a fromset that I am working with in a django view and I can not seem to figure out how to call the formset to validate it and grab the values from the forms. Is there a way for me to call the formset after the user submits it and then validate all of the fields before I start gathering the users inputs into the forms... Here is the code that I have: also is there a way to create a prefix for each of the forms within the formset that are unique so that when i am grabbing the values I can do it much easier than the default id or lables for the fields. The validation code would be in line 26 & 27. def addTransaction(request, groupId, recordId): if 'username' not in request.session: return redirect('login') else: username = request.session['username'] currentUser = User.objects.get(username = username) group = Group.objects.get(id=groupId) record = Record.objects.get(id=recordId) transactions = Transaction.objects.filter(record=recordId).all().count() formset = formset_factory(IndividualSplitTransactionForm, extra=transactions) if request.method == 'POST': if record.split == 1: form = EvenSplitTransactionForm(request.POST) if form.is_valid(): cd = form.cleaned_data amount = cd['amount'] description = cd['description'] split_amount = SplitEven(record, amount) for trans in transactions: if trans.record.id == record.id: trans.description = description trans.amount = …