'list' object has no attribute '_meta'? - django

I am working on a CRUD for a medical company, im trying to display the specialties form a certain physician but when they have more than one i am trying to get the object as a list (and i got it)
but when i try to pass it to the template, it fails, what can i do?
this is my view
def UpdatePhysician(request,id):
physician = get_object_or_404(Physician, id=id)
employee = get_object_or_404(Employee, id=physician.employee.id)
person = get_object_or_404(Person, id=employee.person.id)
try:
address = get_object_or_404(Address, id=return_id(str(person.addresses.values('id'))))
except:
address = None
try:
email = get_object_or_404(Email, id=return_id(str(person.emails.values('id'))))
except:
email = None
try:
phone = get_object_or_404(PhoneNumber, id=return_id(str(person.phone_numbers.values('id'))))
except:
phone = None
try:
academic_degree = get_object_or_404(AcademicDegree, id=return_id(str(employee.academic_degrees.values('id'))))
university = get_object_or_404(University, id=return_id(str(employee.academic_degrees.values('university'))))
except:
academic_degree = None
university = None
physician_specialties = get_list_or_404(PhysicianSpecialties, employee_academic_degree__employee__pk=physician.employee.id)
for item in physician_specialties:
print(unicode(item.specialty))
physician_specialties_form = PhysicianSpecialtiesForm(request.POST or None, instance=physician_specialties)
specialties = Specialty.objects.all()
specialty = PhysicianSpecialties.objects.filter(employee_academic_degree__employee__physician__pk=id)
academic_degree = EmployeeAcademicDegree.objects.filter(employee__physician__pk=id)
person_form = PersonForm(request.POST or None, instance=person)
employee_form = EmployeeForm(request.POST or None, instance=employee)
physician_form = PhysicianForm(request.POST or None, instance=physician)
email_form = EmailForm(request.POST or None, instance=email)
address_form = AddressForm(request.POST or None, instance=address)
phone_form = PhoneForm(request.POST or None, instance=phone)
academic_degree_form = AcademicDegreeForm(request.POST or None, instance= academic_degree)
university_form = UniversityForm(request.POST or None, instance=university)
if (person_form.is_valid() and employee_form.is_valid() and physician_form.is_valid() and email_form.is_valid() and
address_form.is_valid() and phone_form.is_valid and physician_form.is_valid() and university_form.is_valid and
academic_degree_form.is_valid()):
person_form.save()
physician_form.save()
academic_degree_form.save()
new_address = address_form.save()
new_email = email_form.save()
new_phone = phone_form.save()
university_form.save()
if address == None:
PersonAddress.objects.create(person=person, address=new_address)
if email == None:
PersonEmail.object.create(person=person, email=new_email)
if phone == None:
PersonPhoneNumber.objects.create(person=person, hone_number=new_phone)
return HttpResponse('yesh')
return render(request, 'UpdatePhysician.html', {'person_form': person_form,
'employee_form': employee_form,
'email_form': email_form,
'phone_form': phone_form,
'address_form': address_form,
'physician_form': physician_form,
'specialty': specialty,
'academic_degree_form': academic_degree_form,
'academic_degree': academic_degree,
'university_form':university_form,
'specialties': specialties,
'physician_specialties_form': physician_specialties_form,
})
the problem lives in
physician_specialties = get_list_or_404(PhysicianSpecialties, employee_academic_degree__employee__pk=physician.employee.id)
for item in physician_specialties:
print(unicode(item.specialty))
physician_specialties_form = PhysicianSpecialtiesForm(request.POST or None, instance=physician_specialties)

Related

Django form won't bind to POST data

I am really struggling trying to get my POST data to bind to this form. POST data is coming through properly and appears to be in the right form, but it absolutely refuses to bind to the form for validation. I'm new to this so I'm sure I'm missing something obvious, but any help figuring out why this is happening would be greatly appreciated.
views.py
def new_call(request):
if not request.user.is_authenticated():
return redirect(login_view)
if request.method == "POST":
form = RegisterCallForm(request.POST,user=request.user)
#Prints False
print form.is_bound
if form.is_valid():
answered = form.cleaned_data['answered']
left_message = form.cleaned_data['left_message']
contact_pk = form.cleaned_data['contact']
time_called = form.cleaned_data['time_called']
note = form.cleaned_data['note']
staff_person = request.user.userprofile
call = Call(
staff_person=staff_person,
contact=contact,
answered=answered,
left_message=left_message,
time=time_called,
note=note,
)
call.save()
if request.POST.get('submit') == 'continue':
return redirect(user_profile_view)
else:
return redirect(new_call)
else:
form = RegisterCallForm(user=request.user,)
return render(request, 'supporttracker/register_call.html',{'form':form})
And here's the form...
forms.py
class RegisterCallForm(forms.Form):
def __init__(self,*args,**kwargs):
self.user = kwargs.pop('user',User)
super (RegisterCallForm, self).__init__(*args,**kwargs)
self.fields['contact'] = forms.TypedChoiceField(
choices = get_contact_list(self.user),
label = 'Call with',
)
new_fields = OrderedDict()
new_fields['contact'] = self.fields['contact']
new_fields['answered'] = self.fields['answered']
new_fields['left_message'] = self.fields['left_message']
new_fields['time_called'] = self.fields['time_called']
new_fields['note'] = self.fields['note']
self.fields = new_fields
answered = forms.TypedChoiceField(
label='Answered:',
coerce=lambda x: x == 'Yes',
choices=((False, 'No'), (True, 'Yes')),
widget=forms.RadioSelect
)
left_message = forms.TypedChoiceField(
label='Left a message:',
coerce=lambda x: x == 'Yes',
choices=((False, 'No'), (True, 'Yes')),
widget=forms.RadioSelect
)
time_called = forms.DateTimeField(
label = 'Time of call',
initial = datetime.datetime.now,
required = False,
)
note = forms.CharField(
max_length=500,
widget=forms.Textarea,
required=False,
)
It seems you forget to call super init. How do you expect form class do it's normal job when you override the init function?

How to set initial value based on current model instance

I am trying to create an edit form to edit current objects using Django. I am having trouble trying to get the current id of the object in order to set the initial value to the current values of the object.
I want to create an edit form that will already show the current data before the user edits a field. How do I go about doing this?
Thanks.
my forms.py:
class AddfooditemForm(forms.Form):
quantity = forms.CharField(label="Quantity")
price_per_pound = forms.CharField(label="price_per_pound")
expiration_date = forms.CharField(label="expiration_date")
price_per_item = forms.CharField(label="price_per_item")
class AddNonFooditemForm(forms.Form):
quantity = forms.CharField(label="Quantity")
price_per_item = forms.CharField(label="price_per_item")
class EditfooditemForm(ModelForm):
quantity = forms.CharField(label="Quantity")
price_per_pound = forms.CharField(label="price_per_pound")
expiration_date = forms.CharField(label="expiration_date")
price_per_item = forms.CharField(label="price_per_item")
def __init__(self, *args, **kwargs):
super(EditfooditemForm, self).__init__(*args, **kwargs)
class Meta:
model = tasks
fields = ['quantity', 'price_per_item', 'expiration_date', 'price_per_pound']
class Edit_non_food_itemForm(ModelForm):
quantity = forms.CharField(label="Quantity")
price_per_item = forms.CharField(label="price_per_item")
def __init__(self, *args, **kwargs):
super(Edit_non_food_itemForm, self).__init__(*args, **kwargs)
class Meta:
model = tasks
fields = ['quantity', 'price_per_item']
my views.py:
#csrf_exempt
def add_item(request):
if request.method == 'POST' and 'add_food_form' in request.POST:
add_food_form = AddfooditemForm(request.POST)
if add_food_form.is_valid():
# Cleaned_data
input_type = 'food'
quantity = add_food_form.cleaned_data['quantity']
price_per_pound = add_food_form.cleaned_data['price_per_pound']
expiration_date = add_food_form.cleaned_data['expiration_date']
price_per_item = add_food_form.cleaned_data['price_per_item']
foodDict = {'price_per_item': price_per_item,
'quantity': quantity,
'price_per_pound': price_per_pound,
'expiration_date': expiration_date}
foodData = pickle.dumps(foodDict)
item = items(input_type=input_type, foodData=foodData)
item.save()
return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
if request.method == 'POST' and 'add_non_food_form' in request.POST:
add_non_food_form = AddNonFooditemForm(request.POST)
if add_non_food_form.is_valid():
# Cleaned_data
input_type = 'non_food'
quantity = add_non_food_form.cleaned_data['quantity']
price_per_item = add_non_food_form.cleaned_data['price_per_item']
non_foodDict = {'quantity': quantity,
'price_per_item': price_per_item}
non_foodData = pickle.dumps(non_foodDict)
item = items(input_type=input_type, non_foodData=non_foodData)
item.save()
return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
else:
'add_food_form': AddfooditemForm()
'add_non_food_form': AddNonFooditemForm()
return render(request, 'backup_app/items_listing.html', {'add_food_form': add_food_form,'add_non_food_form': add_non_food_form})
#csrf_exempt
def edit_item(request, item_id):
item = items.objects.get(id=item_id)
if request.method == 'POST' and 'edit_food_form' in request.POST:
edit_food_form = EditfooditemForm(request.POST, instance=item)
if edit_food_form.is_valid():
print "valid"
# Cleaned_data
item.input_type = 'food'
quantity = edit_food_form.cleaned_data['quantity']
price_per_pound = edit_food_form.cleaned_data['price_per_pound']
expiration_date = edit_food_form.cleaned_data['expiration_date']
price_per_item = edit_food_form.cleaned_data['price_per_item']
foodDict = {'price_per_item': price_per_item,
'quantity': quantity,
'price_per_pound': price_per_pound,
'expiration_date': expiration_date}
item.foodData = pickle.dumps(foodDict)
item.save()
return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
if request.method == 'POST' and 'edit_non_food_form' in request.POST:
edit_non_food_form = Edit_non_food_itemForm(request.POST, instance=item)
if edit_non_food_form.is_valid():
# Cleaned_data
item.input_type = 'non_food'
quantity = edit_non_food_form.cleaned_data['quantity']
price_per_item = edit_non_food_form.cleaned_data['price_per_item']
non_foodDict = {'quantity': quantity,
'price_per_item': price_per_item}
item.non_foodData = pickle.dumps(non_foodDict)
item.save()
return HttpResponseRedirect(reverse('backup_app.views.items_listing'))
else:
context = {
'edit_food_form': EditfooditemForm(instance=item),
'edit_non_food_form': Edit_non_food_itemForm(instance=item)
}
return render(request, 'backup_app/items_listing.html', context)
Try something like this:
forms.py:
class ChangeForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['field1', 'field2']
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ChangeForm, self).__init__(*args, **kwargs)
views.py:
# To render multiple forms, repeat the process
def account_settings(request):
change_form = ChangeForm(request.POST or None,
instance=request.user, user=request.user)
change_form_2 = ChangeForm2(request.POST or None)
if request.method == 'POST':
if change_form.is_valid():
change_form.save()
if change_form_2.is_valid():
change_form_2.save()
context = {
'change_form': change_form,
'change_form_2': change_form_2
}
return render(request, 'change_form.html', context)
That should give you the current data.
Note: Change the attributes to your needs. If you post your code, I can help you with that. However, I don't know what you're working with, but the above should be a good template to follow.
EDIT:
views.py:
#csrf_exempt
def add_item(request):
add_food_form = AddfooditemForm(request.POST or None)
add_non_food_form = AddNonFooditemForm(request.POST or None)
if request.method == 'POST':
if add_food_form.is_valid():
input_type = 'food'
quantity = add_food_form.cleaned_data['quantity']
price_per_pound = add_food_form.cleaned_data['price_per_pound']
expiration_date = add_food_form.cleaned_data['expiration_date']
price_per_item = add_food_form.cleaned_data['price_per_item']
foodDict = {'price_per_item': price_per_item,
'quantity': quantity,
'price_per_pound': price_per_pound,
'expiration_date': expiration_date}
foodData = pickle.dumps(foodDict)
item = items(input_type=input_type, foodData=foodData)
if add_non_food_form.is_valid():
input_type = 'non_food'
quantity = add_non_food_form.cleaned_data['quantity']
price_per_item = add_non_food_form.cleaned_data['price_per_item']
non_foodDict = {'quantity': quantity,
'price_per_item': price_per_item}
non_foodData = pickle.dumps(non_foodDict)
item = items(input_type=input_type, non_foodData=non_foodData)
item.save()
# This needs to be a url name
return HttpResponseRedirect(reverse('url_name_here'))
context = {
'add_food_form': add_food_form,
'add_non_food_form': add_non_food_form
}
# Make this its own template
return render(request, 'backup_app/items_add.html', context)
#csrf_exempt
def edit_item(request, item_id):
item = items.objects.get(id=item_id)
edit_food_form = EditfooditemForm(request.POST or None,
instance=item)
edit_non_food_form = Edit_non_food_itemForm(request.POST or None,
instance=item)
if request.method == 'POST':
if edit_food_form.is_valid():
item.input_type = 'food'
quantity = edit_food_form.cleaned_data['quantity']
price_per_pound = edit_food_form.cleaned_data['price_per_pound']
expiration_date = edit_food_form.cleaned_data['expiration_date']
price_per_item = edit_food_form.cleaned_data['price_per_item']
foodDict = {'price_per_item': price_per_item,
'quantity': quantity,
'price_per_pound': price_per_pound,
'expiration_date': expiration_date}
item.foodData = pickle.dumps(foodDict)
if edit_non_food_form.is_valid():
item.input_type = 'non_food'
quantity = edit_non_food_form.cleaned_data['quantity']
price_per_item = edit_non_food_form.cleaned_data['price_per_item']
non_foodDict = {'quantity': quantity,
'price_per_item': price_per_item}
item.non_foodData = pickle.dumps(non_foodDict)
item.save()
# This needs to be a url name
return HttpResponseRedirect(reverse('url_name_here'))
else:
context = {
'edit_food_form': EditfooditemForm(instance=item),
'edit_non_food_form': Edit_non_food_itemForm(instance=item)
}
# Make this its own template
return render(request, 'backup_app/items_edit.html', context)
def items_listing(request):
# Any data you want to post about the listed items
return render(request, 'backup_app/items_listing.html', {})

Form cleaning and processing not working - Django

Alright, this is probably a really obvious problem and I'm just not seeing it, but I need help:
In the following view, I process a formset.
If the user fills the form, I want to save EventRecord and ArticleHistory, if the user leaves the form empty, I want to save only the ArticleHistory.
def process_form(formset, request, current_page, paginator):
if formset.is_valid():
for form in formset.forms:
form = form.cleaned_data
##### Check if user filled the form
if form["relevance"] == False:
pass
elif form["relevance"] == True:
##### If user filled the form, save EventRecord
event_form = EventRecordForm()
event = event_form.save(commit=False)
event.article = paginator.page(current_page).object_list[0]
event.coder = request.user.coder
event.last_updated = datetime.datetime.today()
event.event_date = form["event_date"]
event.location = form["location"]
event.actors = form["actors"]
event.num_participants = form["num_participants"]
event.issue = form["issue"]
event.side = form["side"]
event.scope = form["scope"]
event.part_violence = form["part_violence"]
event.sec_engagement = form["sec_engagement"]
event.save()
##### Add info on who worked on the article when
history_form = ArticleHistoryForm()
article_history = history_form.save(commit=False)
article_history.article = paginator.page(current_page).object_list[0]
article_history.coder = request.user.coder
article_history.last_updated = datetime.datetime.now()
article_history.save()
I try to do that by cleaning the form like so:
class CodingForm(forms.Form):
event_date = forms.DateField(required=False)
location = forms.ModelChoiceField(queryset=Location.objects.all(), required=False)
actors = forms.CharField(max_length=100, required=False)
num_participants = forms.CharField(max_length=200, required=False)
issue = forms.CharField(max_length=200, required=False)
side = forms.NullBooleanField('Side')
scope = forms.TypedChoiceField(choices=SCOPE_CHOICES, coerce=int, empty_value=None)
part_violence = forms.TypedChoiceField(choices=PART_VIO, coerce=int, empty_value=None)
sec_engagement = forms.TypedChoiceField(choices=SEC_ENG, coerce=int, empty_value=None)
relevance = forms.NullBooleanField('Relevance')
def clean(self):
cleaned_data = self.cleaned_data
relevance = cleaned_data.get("relevance")
event_date = cleaned_data.get("event_date")
location = cleaned_data.get("location")
if event_date and location:
relevance = True
else:
relevance = False
return cleaned_data
However, if I do it like this - no matter what I do - only ArticleHistory gets saved, and no EventRecord.
What am I missing?
In your clean method, you're setting a local variable called relevance but not doing anything with it. I expect you want to set cleaned_data['relevance'] to True or False instead.

Django: saving into model field

another django question. I have a edit form like this. Look at current_status in the code.
It has been updated:
def edit_item(request, client_id = 0, item_id = 0):
client = None
item = None
status = None
contact = None
status_id = request.POST.get('status_id', None)
contact_id = request.POST.get('contact_id', None)
save_item = request.POST.get('save_item', None)
save_status = request.POST.get('save_status', None)
try:
client = models.Client.objects.get(pk = client_id)
item = models.StorageItem.objects.get(pk = item_id)
except:
return HttpResponseNotFound()
try:
status = models.Status.objects.get(pk = status_id)
contact = models.Contact.objects.get(pk = contact_id)
except:
pass
if request.method == 'POST':
form = forms.ItemForm(request.POST, instance = item)
if form.is_valid() and save_item is not None:
form.save(True)
request.user.message_set.create(message = "Item {0} has been updated successfully.".format(item.tiptop_id))
return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")
if status is not None and contact is not None and save_status is not None:
current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
user = request.user)
item.current_item_status_date = date.today()
item.save()
current_status.save()
request.user.message_set.create(message = "Item status has been updated successfully.")
else:
form = forms.ItemForm(instance = item)
title = str(client) + ' : Edit Item'
status_list = models.Status.objects.all()
return render_to_response('edit_item.html', {'form':form, 'title':title, 'status_list':status_list, 'item':item}, context_instance = RequestContext(request))
current_status save's the latest date of when the form is edited. What I ALSO want to do is to save this value into this models field.
class StorageItem(models.Model):
current_item_status_date = models.DateField()
Is ItemForm a ModelForm (see Django Model Forms)?
If so form.save() will return a model instance. Then you can edit its fields if you need to. For example.
my_obj = form.save()
my_obj.current_item_status_date = datetime.date.today()
my_obj.save()
If not, then simply create a new instance of your model and save the field value.
my_obj = StorageItem(current_item_status_date=datetime.date.today())
my_obj.save()

modelform "object not callable" error

Ok, so I'm fairly new to Django, but have been reading both the online django book and the djangoproject documentation, but I can't seem to figure this error out:
I've got an 'Orders' model:
class Orders(models.Model):
client_id = models.ForeignKey(Client)
order_date = models.DateField(auto_now_add = True)
due_date = models.DateField()
completion_date = models.DateField(blank=True, null=True)
rush_order = models.BooleanField(default=False)
billing_option = models.ForeignKey(Billing)
patient_first_name = models.CharField(max_length=30)
patient_middle_name = models.CharField(max_length=30, blank=True)
patient_last_name = models.CharField(max_length=30)
client_patient_id = models.CharField(max_length=30, blank=True)
emodel_patient_id = models.CharField(max_length=30)
special_instructions = models.TextField(blank=True)
order_items = models.ManyToManyField(Order_Items)
def __unicode__(self):
return '%s : %s %s O: %s F: %s' % (self.client_id, self.patient_first_name, self.patient_last_name, self.order_date, self.completion_date)
class Meta:
ordering = ['client_id']
I've got a 'SearchOrderForm' modelform:
class SearchOrderForm(ModelForm):
class Meta:
model = Orders
exclude = ('rush_order', 'billing_option', 'client_patient_id', 'special_instructions', 'order_items',)
and I've got an 'order_status' function:
def order_status(request):
error = False
error_searching = False
if request.method == 'POST':
OrderFormSet = SearchOrderForm()
formset = OrderFormSet()
if formset.is_valid():
cd = formset.cleaned_data()
emodels_results = cd()
emodels_results = cd(queryset = Order.objects.filter(Q(patient_first_name=search)|Q(patient_last_name=search)|Q(client_id=search)))
patient_first_name = request.POST('patient_first_name', None)
if patient_first_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_first_name=patient_first_name))
patient_last_name = request.POST('patient_last_name', None)
if patient_last_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_last_name=patient_last_name))
client_id = request.POST('client_id', None)
if client_id:
emodels_results = emodels_results(queryset = Order.objects.filter(client_id=client_id))
return render_to_response('search_results.html', {'models': emodels_results})
else:
emodels_results = "Still messed up!"
return render_to_response('search_results.html', {'models': emodels_results})
else:
error_searching = True
form = SearchOrderForm()
return render_to_response('order_status.html', {'form': form, 'error': error, 'error_searching': error_searching})
I can fill out my form with no problems, but when I submit the form I get back the following error message:
Traceback:
File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "C:\emodel_tracking..\emodel_tracking\tracker\views.py" in order_status
105. formset = OrderFormSet()
Exception Type: TypeError at /accounts/profile/orderstatus/
Exception Value: 'SearchOrderForm' object is not callable
Does anyone know what I'm doing wrong with my SearchOrderForm that's causing Django to say that it is not callable?
I think you want either of these:
OrderFormSet = SearchOrderForm()
if OrderFormSet.is_valid():
formset = SearchOrderForm()
if formset.is_valid()
With the second way being the preferred syntax style. As a matter of nitpicking, Django offers a FormSet type which is different than the Form type so it is convention to refer to instances of Forms as "form":
form = SearchOrderForm()
if form.is_valid():
You are going to have some other problems with your code:
def order_status(request):
error = False
error_searching = False
if request.method == 'POST':
#instead of:
#OrderFormSet = SearchOrderForm()
#formset = OrderFormSet()
#instantiate an instance of your ModelForm
#(I'd normally name it "form")
formset = SearchOrderForm()
if formset.is_valid():
cd = formset.cleaned_data()
#cd is now a Python dictionary
#these next 2 lines don't make sense, what is your intention?
emodels_results = cd()
emodels_results = cd(queryset = Order.objects.filter(Q(patient_first_name=search)|Q(patient_last_name=search)|Q(client_id=search)))
#you've already used your form to process and clean
#the incoming POST data. use the cleaned data instead
#patient_first_name = request.POST('patient_first_name', None)
patient_first_name = cd.get('patient_first_name','')
#use data from the form's cleaned_data as in the line above
#I'm not sure what your intention is with how the emodels_results
#is but you'll need to rework that for it all to work
if patient_first_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_first_name=patient_first_name))
patient_last_name = request.POST('patient_last_name', None)
if patient_last_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_last_name=patient_last_name))
client_id = request.POST('client_id', None)
if client_id:
emodels_results = emodels_results(queryset = Order.objects.filter(client_id=client_id))
return render_to_response('search_results.html', {'models': emodels_results})
else:
emodels_results = "Still messed up!"
return render_to_response('search_results.html', {'models': emodels_results})
else:
error_searching = True
form = SearchOrderForm()
return render_to_response('order_status.html', {'form': form, 'error': error, 'error_searching': error_searching})