How do I change a form value in Django? - django

We are using Django 1.4.3 with django-cities-light 2.1.5 to create our website. We are using the form's __init__ method to update the lists of regions and cities. The problem is that if the user selected a city and the form doesn't validate, I want to change the region selection to the region of the selected city. Here is the code:
def __init__(self, instance, *args, **kwargs):
super(ContentItemModelForm, self).__init__(*args, instance=instance, **kwargs)
....
....
....
country_id = None
if ((hasattr(self, "initial")) and ("country_id" in self.initial)):
country_id = int(self.initial['country_id']) if self.initial['country_id'] else None
elif ((hasattr(self, "data")) and (u'country_id' in self.data)):
country_id = int(self.data[u'country_id']) if self.data[u'country_id'] else None
region_id = None
if ((hasattr(self, "initial")) and ("region_id" in self.initial)):
region_id = int(self.initial['region_id']) if self.initial['region_id'] else None
elif ((hasattr(self, "data")) and (u'region_id' in self.data)):
region_id = int(self.data[u'region_id']) if self.data[u'region_id'] else None
city_id = None
if ((hasattr(self, "initial")) and ("city_id" in self.initial)):
city_id = int(self.initial['city_id']) if self.initial['city_id'] else None
elif ((hasattr(self, "data")) and (u'city_id' in self.data)):
city_id = int(self.data[u'city_id']) if self.data[u'city_id'] else None
if (city_id):
city_obj = City.objects.get(geoname_id=city_id)
country_id = city_obj.country_id
region_id = city_obj.region_id
# Set current values of country_id and region_id - commented (not working).
#self.fields['country_id'].initial = country_id
#self.fields['region_id'].initial = region_id
self.fields['region_id'].choices = [("", "(None)", ),]+[(obj.id, obj.name) for obj in Region.objects.filter(country_id=country_id).order_by("name")]
if (region_id):
self.fields['city_id'].choices = [("", "(None)", ),]+[(obj.geoname_id, obj.name) for obj in City.objects.filter(country_id=country_id, region_id=region_id).order_by("name")]
else:
self.fields['city_id'].choices = [("", "(None)", ),]+[(obj.geoname_id, obj.name) for obj in City.objects.filter(country_id=country_id).order_by("name")]
The code that checks the current values of city_id, region_id and country_id is too long and I didn't find a way to shorten it. And the commented lines (self.fields['country_id'].initial = country_id and self.fields['region_id'].initial = region_id) don't work if they are not commented - if only country and city are selected then the selected region is "(None)" (if the form does not validate). If the form validates then we assign the country_id and region_id values according to the selected city (the country and region are not saved to the database).
Here is the city validation:
def clean_city_id(self):
cleaned_data = self.cleaned_data
country_id = cleaned_data['country_id'] if (cleaned_data.has_key('country_id')) else None
region_id = cleaned_data['region_id'] if (cleaned_data.has_key('region_id')) else None
city_id = cleaned_data['city_id'] if (cleaned_data.has_key('city_id')) else None
if (not(city_id)):
if (region_id):
error_message = "If you select a country and a state/region, you must select a city."
self._errors["city_id"] = self.error_class([error_message])
raise forms.ValidationError(error_message)
elif (country_id):
error_message = "If you select a country, you must select a city."
self._errors["city_id"] = self.error_class([error_message])
raise forms.ValidationError(error_message)
return city_id
Do you know how do we assign the correct values to the country and region?
(Edit): We want to have selected="selected" in the HTML in the correct region after a city is selected, and not in the first "(None)" region (also if the user didn't select a region). We use AJAX to update the lists after the user selects a new country or region, but we don't want to use AJAX immediately after loading the form.
Thanks,
Uri.

I would suggest alternative way to solve the problem. Alternative to "manually" setting values for user - let user do it itself. Like this:
1) Trigger form GET on select change event
2) in those event callbacks pass form data to view - just like you do with POST. Just do GET request not POST request.
3) In view just pass request.GET as first parameter to form instead of request.POST
4) Let your existing logic do the magic in form init method.
5) Return form template with correct and valid choices from view
6) switch existing form with new form.
Thats how i would do it anyway. No need to assign anything. Let user do the choices they can after refreshing the form.

Related

django admin 'Form' has no field named 'field_name' when resaving a record

As the title goes, when I was resaving a record, I'm getting an error saying
ValueError: 'EmployeeLeaveForm' has no field named 'start_date'.
which should be impossible because I got a check to ensure that it's filled up in clean(). Initial save works fine, but when I try to resave it, the error I mentioned earlier appears
Here's my complete form:
class EmployeeLeaveForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'initial' not in kwargs:
kwargs['initial'] = {}
request = self.request
is_hr = request.user.groups.all().filter(name__icontains="HR").exists()
is_superuser= request.user.is_superuser
#set initial values to fields when user is not authorized to change the employee field
if not is_hr and not is_superuser:
kwargs['initial'].update({'employee': self.employee})
kwargs['initial'].update({'employee_paid_leave': self.employee_paid_leave})
super(EmployeeLeaveForm, self).__init__(*args, **kwargs)
self.fields['employee_paid_leave'].required = False
self.fields['employee_paid_leave'].disabled = True
if not is_hr and not is_superuser:
#for making employee readonly
self.fields['employee'].required = False
self.fields['employee'].disabled = True
self.fields['employee'].widget = LeaveEmployeeReadOnlyWidget()
def clean(self):
start_date = self.cleaned_data.get('start_date')
end_date = self.cleaned_data.get('end_date')
type = self.cleaned_data.get('type')
employee = self.cleaned_data.get('employee')
#for some reason, I think read only makes a field seem None
if self.instance.pk is None and employee.paid_leave_balance <= 0:
raise forms.ValidationError("Insufficient paid leave balance")
if start_date is None:
raise forms.ValidationError({'start_date': ["Start date is empty",]})
elif end_date is None:
raise forms.ValidationError({'end_date': ["End date is empty",]})
elif type is None:
raise forms.ValidationError({'type': ["Leave type is empty",]})
employee_paid_leave = forms.FloatField(label = 'Remaining Paid Leave', required = False)
class Meta:
model = models.EmployeeLeave
exclude = []
fields = [
"employee",
"start_date",
"start_date_half_day",
"end_date",
"end_date_half_day",
"type",
"approved_by_supervisor",
"approved_by_department",
"reason",
"deducted",
]
#for adding the custom field
fields = fields[:1] + ['employee_paid_leave',] + fields[1:]
class Media:
js = ('/static/js/jquery.js', '/static/js/custom_admin_validate.js')
I'm also suspecting that making the field readonly somehow made them seem None because when I tried to remove start_date from the readonly_fields, it doesn't throw an error for that field.
Could this be an internal django issue?
As I suspected, Django doesn't give a readonly_field the same field as a normal field. The field given to readonlys doesn't have the functionalities a non-readonly field have which includes the functionality to read the contents of it.
https://code.djangoproject.com/ticket/30373

Can i have help on how i can save a foreignkey in a model?

I have two models Order and OrderItem.
The process to make an order starts with the OrderItem model.
class OrderItem(SmartModel):
shopping_id = models.CharField(max_length=50,db_index=True)
quantity = models.IntegerField(default=0)
item = models.ForeignKey(Item)
order = models.ForeignKey(Order,null=True,blank=True)
OrderItem represents an item and is a modelform with one field being quantity others are excluded
i validate the form and create the item like so,
def show_item(request,id):
# need to evaluate the HTTP method
if request.method == 'POST':
a = Item.objects.get(pk=id)
form = PartialOrderItemForm(request.POST,instance=a)
# check validation of posted data
if form.is_valid():
order.add_to_order(request,a)
# if test cookie worked, get rid of it
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
url =urlresolvers.reverse('order_index')
# redirect to order page
return HttpResponseRedirect(url)
else:
form = PartialOrderItemForm()
request.session.set_test_cookie()
context={
'form':form,
}
return render_to_response('item.html',context,context_instance=RequestContext(request))
the function called after is_valid i.e order.add_to_order creates and saves an item.
def add_to_order(request,obj):
postdata = request.POST.copy()
#get quantity added, return 0 if empty
quantity = postdata.get('quantity',0)
# fetch the item or return missing page error_message
i = get_object_or_404(Item,pk=obj.id)
# get items in order
order_items = get_order_items(request)
item_in_orders = False
# check to see if item is already in order
for order_item in order_items:
if order_item.item.id == i.id:
#update the quantity if found
order_item.augment_quantity(quantity)
item_in_orders = True
if not item_in_orders:
# creat and save a new order item
anon_user = User.objects.get(id=settings.ANONYMOUS_USER_ID)
oi=OrderItem.objects.create(shopping_id=_shopping_id(request),
quantity=quantity,
item=i,
created_by=anon_user,
modified_by=anon_user)
oi.save()
when a customer is done creating an item(in the database), they fill in a form which is Order
class Order(SmartModel):
#each individual status
SUBMITTED = 1 # the credit card was valid or mobilemoney was recieved.It is ready for us to process the order
PROCESSED = 2 # After submitted orders are reviewed, we can mark them as processed, letting deliverers know order is ready to be shipped
DELIVERED = 3 # the order has been processed and approved by the adminstrator(in this case us), it is delivered.
PICKED_UP =4 # the order has been processed and is picked up by customer
CANCELLED = 5 # Customer called the company and decided they didnt want to go through with the order either by phone or email.
# SET OF POSSIBLE STATUSES
ORDER_STATUSES = ((SUBMITTED,'Submitted'),(PROCESSED,'Processed'),(DELIVERED,'Delivered'),(PICKED_UP,'picked_up'),(CANCELLED,'Cancelled'),)
#Order info
date = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=ORDER_STATUSES, default=SUBMITTED)
# customer = models.ForeignKey(Customer,null=True,blank=True,help_text="The customer who made this order",default=None,)
restaurant = models.ForeignKey(Restaurant,null=True,blank=True,default = None,help_text="The restaurant the customer order from")
#contact info
email = models.EmailField(max_length=50,help_text="Needed as alternative")
mobile = PhoneNumberField(max_length=20,default='+25078######',help_text="Needed to communicate and confirm payment from mobile money")
#billing information
billing_name= models.CharField(max_length=50,help_text="Needed so we can deliver to the right individual")
billing_address= models.CharField(max_length=50,help_text="Needed for delivery purposes, should be office address.")
billing_city = models.CharField(max_length=50,help_text="F4L services are only in selected cities.")
Order is a modelform that i validate and save like so.
def show_checkout(request):
if order.is_empty(request):
cart_url = urlresolvers.reverse('order_index')
return HttpResponseRedirect(cart_url)
if request.method == 'POST':
postdata = request.POST.copy()
form = forms.CheckoutForm(request.POST,postdata)
if form.is_valid():
anon_user = User.objects.get(id=settings.ANONYMOUS_USER_ID)
obj = form.save(commit=False)
obj.created_by = anon_user
obj.modified_by = anon_user
obj.save()
if postdata['submit'] == 'place order':
reciept_url = urlresolvers.reverse('checkout_reciept')
return HttpResponseRedirect(reciept_url)
else:
form = forms.CheckoutForm
context = {
'form':form,
}
return render_to_response('checkout/checkout.html',context,context_instance=RequestContext(request))
i should point out that OrderItem is called before Order..much of where the confusion is coming from
to return all OrderItem objects related to Order i do as suggested by the django documentation https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
>>> from orders.models import OrderItem,Order
>>> a = Order.objects.get(id=1)
>>> a
<Order: blah blah blahbaah#blahblah.com +250780000000 1 2013-02-26 17:25:23.138738+00:00>
>>> a.orderitem_set.all()
[]
I am thinking its empty because i didnt save the foreignkey, but i am really confused about how to go about that. Any help is appreciated..
You just need to pass in (or somehow obtain) the object for the order.
Assuming the PK of the order is in your POST vars, you could do this:
def add_to_order(request,obj):
postdata = request.POST.copy()
order = Order.objects.get(pk=postdata.get('order_id'))
…
oi=OrderItem.objects.create(order=order, shopping_id=_shopping_id(request), …)
Based on your comment below though, you're creating your order AFTER you create the orderitem, making the code above pointless.
If the order hasn't been created yet, there's absolutely no way for you to tie the order item to the order. At least not without doing something else.
Here's what I'd do.
Add a new field to your OrderItem:
order_uuid = models.CharField(max_length=25, blank=False, null=True)
When you start your order process (wherever you start it), create a UUID using python's uuid package:
import uuid
temporary_order_uuid = uuid.uuid4()
Pass this value through each of your order steps, final saving it to the orderitem when you create it.
oi=OrderItem.objects.create(order_uuid=temporary_order_uuid, …)
After you create your order, go back and update all orderitems that contain that uuid with the order's pk:
order_items = OrderItems.objects.get(order_uuid=temporary_order_uuid)
for oi in order_items:
oi.order = order
oi.save()
A much cleaner solution would be to create your orderitems AFTER you create the order in the database, but I don't know all the various requirements of your app.

Django Multiselect, how to override choices properly

this is my forms.py
CHOICES = []
class salDeptChartForm(forms.Form):
company = forms.CharField(max_length=2,label = 'Firma',help_text='A valid email address, please.')
date_validfrom = forms.DateField(label = 'Bu Tarihten',required=False)
date_validuntil = forms.DateField(label = 'Bu Tarihe Kadar',required=False)
saldept = forms.MultipleChoiceField(label = 'Satış Departmanları',choices=CHOICES, widget=forms.CheckboxSelectMultiple())
this is where I override the choices in my view.
form = salDeptChartForm(initial={'company':'01'})
saldeptlist = saleinstance.fetchSalDept()
form.fields['saldept'].choices = saldeptlist <this is where I override>
problem occurs when I select one of the options. form doesnt get validate.
Select a valid choice. * is not one of the available choices.
I think, even I override the choices in my view django still checks with previous choices itially I created. I get the correct html output tough.
How to overcome this?
thx
complete view code is there.
form initiates twice one for get and one for post, I dont know if its best either.
def salDept(request):
member_id = request.session['member_id']
saleinstance = sale(member_id)
chartinstance = charts(member_id)
if request.method == 'GET':
form = salDeptChartForm(initial={'company':'01'}) <first init>
saldeptlist = saleinstance.fetchSalDept() <its a list>
form.fields['saldept'].choices = saldeptlist <override choices>
print 'get worked'
return render(request, 'chart/sale/salDept.html',locals())
if request.method == 'POST':
form = salDeptChartForm(request.POST) <second init>
print 'post worked'
if form.is_valid(): <fails>
print 'valid'
company = form.cleaned_data['company']
vfr = form.cleaned_data['date_validfrom']
vun = form.cleaned_data['date_validuntil']
validfrom = formatDate(vfr)
validuntil = formatDate(vun)
selectedSalDepts = request.POST.getlist('saldept')
else:
print 'not valid'
print form.errors
resultdict = chartinstance.salesBySaldept(company,selectedSalDepts,validfrom, validuntil)
form = salDeptChartForm(initial={'company':company,'date_validfrom':request.POST['date_validfrom'], 'date_validuntil':request.POST['date_validuntil']})
domcache = 'true'
return render(request, 'chart/sale/salDept.html',locals())
Okay, you need override the init() of the form to do accomplish this.
class SomeForm(forms.Form):
email = forms.EmailField(label=(u'Email Address'))
users = forms.MultipleChoiceField(choices=[(x, x) for x in User.objects.all()]
)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(SomeForm, self).__init__(*args, **kwargs)
self.fields['users'].choices = [(x, x) for x in User.objects.filter(name__contains='Patel')]
def clean(self):
return self.cleaned_datas
Here in line number (3) you can see that I have provided all the possible choices and then in the init I have filtered the choices, this is important because Django validates your submitted request from the former and displays the choices from the latter
Your validation fails because you only overwrite the choices on the GET method. You don't do anything for the POST, so as far as Django knows, no choice is valid for the POST. Adding the choices to POST should fix your problem.

how to overide in forms queryset none() attribute and somehow allow to save the field?

I have models.py
class Visit(Model):
reference_visit = models.ForeignKey('self',
help_text="Visit needs a refrence to Prior Visits",
null=True, blank=True)
show_prior_responses = models.BooleanField(default=False,
help_text="Show PriorResponses")
# has many field but i am making it short.
def __unicode__(self):
result = """Visit id:%s pt:%s""" % (self.id, self.patient.id)
return result
forms.py
class VisitSetupForm(Form):
list_visit_ids = ModelChoiceField(
queryset=Visit.objects.none(),
empty_label='Select Revisit ID',required=False)
show_prior_visit = ModelChoiceField(
queryset=User.objects.all(),
empty_label="Select User for Revisit",required = False)
has many but question is on list_visit_ids.
views.py
def setup(request):
"""
Allow an Admin user the ability to setup a patient & visit all at once.
"""
if request.user.is_superuser:
form_class = AdminVisitSetupForm
all_topics = True
else:
form_class = VisitSetupForm
all_topics = False
f = form_class()
# Get a list of topics for each report.
report_topics = {}
for r in Interview.objects.all():
report_topics[r.id] = [t['ad'] for t in r.topics.values('ad')]
data = {
'superuser':request.user.is_superuser,
'report_topics':simplejson.dumps(report_topics)
}
try:
request.user.reviewer
data['reviewer'] = True
except:
pass
if request.method == "POST":
f = form_class(request.POST)
if f.is_valid():
# Create the patient, generate a password, and send them on their way.
cd = f.cleaned_data
patient = None
if cd['revisit']:
# Check for an existing user first.
try:
patient = Patient.objects.get(username=cd['username'])
except Patient.DoesNotExist, e:
data['form'] = f
data['msg'] = 'There is no user with this username.'
return render_to_response('visit/setup.html', data, context_instance=RequestContext(request))
admin_user = get_user(request)
organization = None
if admin_user:
organization = admin_user.organization
if patient and not request.user.is_superuser:
# Make sure the patient they've selected is one of their own.
if patient.organization != organization:
return HttpResponseForbidden('You are not allowed to see this page.')
if not patient:
password = generate_password()
user = User.objects.create_user(cd['username'], cd['contact_email'], password)
user.first_name = cd['first_name']
user.last_name = cd['last_name']
user.save()
patient = Patient(
user=user,
username=user.username,
contact_phone=cd['contact_phone'],
date_of_birth=cd['date_of_birth'],
email=user.email,
first_name=user.first_name,
gender=cd['gender'],
last_name=user.last_name,
maiden_name=cd['maiden_name'],
organization=organization,
patient_type=cd['patient_type'],
security_answer=cd['security_answer'],
security_question=cd['security_question'],
)
patient.save()
# Send them an email.
t = loader.get_template('www/new_account.txt')
c = Context({
'password':'%s-%s-%s' % (password[:3], password[3:5], password[5:]),
'patient':patient
})
msg = t.render(c)
try:
send_mail(
'A request by your physician to do an online medical history before your appointment.',
msg,
'support#careprep.com',
[user.email]
)
except Exception, e:
log.error('Could not send email for new account %s because: [%s]' % (user.username, e))
request.session['password'] = password
# Create the Visit, too.
interview = cd['interview']
list_visit_ids = cd['list_visit_ids']
print list_visit_ids
visit = Visit(
reference_visit = cd['list_visit_ids'],
show_prior_responses = cd['show_prior_responses'],
patient=patient
)
if request.user.is_superuser:
topics = cd['topics']
else:
topics = set(list(interview.topics.all()) + list(cd['topics']))
reviewer_mode = cd.get('reviewer_mode') or patient.patient_type == 'Reviewer'
url, visit = initialize_visit(
request,
patient=patient,
starting_section=interview.starting_section,
visit_title='%s %s' % (patient, interview.title),
topics=topics,
reviewer_mode=reviewer_mode,
chief_complaint=cd['chief_complaint'],
location=cd['interview_site'],
reference_visit = cd['list_visit_ids'],
show_prior_responses = cd['show_prior_responses'],
)
next_url = "/visit/confirmation/%s/%s/?next=%s" % (patient.user.id, interview.id, url)
else:
v = Visit.objects.get(pk=request.POST['list_visit_ids'])
print v
return HttpResponseRedirect(next_url)
# all the fields that are not given pls ignore.
The template is fine.
Now watch forms.py when i do list_visit_ids = ModelChoiceField(queryset=Visit.objects.all(), empty_label='Select Revisit ID',required=False) It works perfectly fine on my local machine.But on my server it has around 6000 visit objects so this page hangs or i should say keep on loading.
So initially i changed it to list_visit_ids = ModelChoiceField(queryset=Visit.objects.none(), empty_label='Select Revisit ID',required=False)
Now i know that by this the form becomes invalid and should go to the else part Now my question how do i make reference_visit=cd['list_visit_ids'] in else (form is invalid)
case save().How do i override the none() attribute.
Thanks in advance i will really appreciate.
If your goal is to save your html page load by removing the 6000 choices (which I've done too: 10000+ <option> fields wrapped by misc html will absolutely choke a page), you shouldn't be using a ChoiceField at all. By setting queryset=Visit.objects.none() you're allowing zero choices and nothing passed in will validate.
You either show 6000 select item drop downs, radio boxes, etc., or find a way to /not/ have a giant select drop down (such as a hidden input or charfield), not fake around a ModelChoiceField who's main purpose is to populate that select drop down and validate.
In short: don't use a ModelChoiceField if you're not going to be using the html choices generated by it. Use something else and do the validation / model pulling yourself via the clean_FOO methods.
class MyForm(forms.Form):
my_input = forms.CharField()
def clean_my_input(self):
input = self.cleaned_data.get('my_input')
try:
return MyModel.objects.get(pk=input) # add a filter here if you want
# (whatever filters you were using in the queryset argument)
except MyModel.DoesNotExist:
raise forms.ValidationError("Doesn't exist / is invalid")
return input

Django - Limit select field to queryset of foreign table?

I have two models as follows:
System_Contact
first_name
last_name
isOwner = CharField ('Y'/'N')
isMainContact = CharField ('Y'/'N')
System
mainContact = ForeignKey(System_Contact)
owner = ForeignKey(System_Contact)
billTo = ForeignKey(System_Contact)
So, when I show the System form in a web page, the user can select the mainContact owner and billTo contacts from a drop down menu to save to the System model. However, I want to filter the select fields in the System form so that they are like this:
mainContact Select box: -- only show System_Contacts that have isMainContact = 'Y'
owner Select Box: -- only show Syste_Contacts that have isOwner = 'Y'
As it is now, I know how to limit a select box by filtering the queryset, but I don't know how to filter the related Foreign Key querySet. Since the mainContact and owner fields are Foreign Keys, I need to filter the Foreign Table (System_Contact), not the table on which the form is built (System)
I know how to filter a normal, non Foreign Key type select box as follows:
form.fields["some_field"].queryset = Some_Model.objects.filter(some_field="Foo")
How would I 'extend' this so that it filters the Foreign table?
This is what I am trying currently, without success:
form.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact = 'Y')
Thanks
This is what I am trying currently, without success:
form.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact = 'Y')
Can you include your model form and view? That looks OK to me.
Another approach is to override the __init__ method of your model form and set the queryset there.
class SystemForm(ModelForm):
def __init__(self, *args, **kwargs):
super(SystemForm, self).__init__(*args, **kwargs)
self.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact = 'Y')
class Meta:
model = System
As an aside, I would recommend using a BooleanField instead of a CharField with 'Y' and 'N' as choices.
That syntax looks correct. Are you receiving an error or is it just not filtering and showing everybody? Try the System_Contact.objects.get(id=<some valid id>) to see if it gets only one or more. If it gets more, perhaps it is being populated from a different call than the one intended.
Well this is embarrassing...
As I was pasting in my view and model form as per Alasdair's request, I noticed my error. Here is my (incorrect) view:
def system_contacts(request, systemID):
sys = System.objects.get(pk=systemID)
if request.method == 'POST':
form = System_Contacts_Form(request.POST, instance=sys)
form.fields["systemOwner"].queryset = System_Contact.objects.filter(systemOwner__exact='Y')
form.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact__exact = 'Y')
if form.is_valid():
form.save()
return HttpResponseRedirect('/systems/')
else:
conts = Contact_List.objects.filter(systemID = sys.pk)
form = System_Contacts_Form(instance=sys)
return render_to_response('pages/systems/system_pages/contacts.html', {'sys':sys, 'form':form, 'conts':conts}, context_instance=RequestContext(request))
I had put the form.fields["systemOwner"]... part in the POST section of the view, not the GET section of the view.
Here is my corrected view:
def system_contacts(request, systemID):
sys = System.objects.get(pk=systemID)
if request.method == 'POST':
form = System_Contacts_Form(request.POST, instance=sys)
if form.is_valid():
form.save()
return HttpResponseRedirect('/systems/')
else:
conts = Contact_List.objects.filter(systemID = sys.pk)
form = System_Contacts_Form(instance=sys)
form.fields["systemOwner"].queryset = System_Contact.objects.filter(systemOwner__exact='Y')
form.fields["mainContact"].queryset = System_Contact.objects.filter(isMainContact__exact = 'Y')
return render_to_response('pages/systems/system_pages/contacts.html', {'sys':sys, 'form':form, 'conts':conts}, context_instance=RequestContext(request))
Now my corrected view works and the filtering works on the select inputs on the form. I would not have thought to look at that without your help.
Cheers :-)