modelform "object not callable" error - django

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})

Related

'QueryDict' object has no attribute 'first_name'

Have AttributeError 'QueryDict' object has no attribute 'first_name' Get examples from here. I'm don't understand what is the problem
models.py
class Employee(models.Model):
first_name = models.CharField(max_length=30)
second_name = models.CharField(max_length=30)
patronymic = models.CharField(max_length=30)
birth_date = models.DateField()
views.py
def edit_employee_action(request, employee_id):
if request.method == "POST":
form = AddEmployeeForm(request.POST)
if form.is_valid():
edited = Employee.objects.filter(pk=employee_id)
edited.update(
first_name = request.POST.first_name,
second_name = request.POST.second_name,
patronymic = request.POST.patronymic,
birth_date = request.POST.birth_date
)
else:
form = AddEmployeeForm()
form = AddEmployeeForm()
return render(
request,
'edit_employee.html',
context={'form': form}
)
The parameter employee_id is correct (debugged).
you need to get the value from request.POST like this:
request.POST['first_name']
(this approach will raise KeyError if first_name is not available in request.POST)
or
request.POST.get('first_name')
You are using incorrectly the request.POST. It is actually a `dictionary. Try the following.
def edit_employee_action(request, employee_id):
if request.method == "POST":
form = AddEmployeeForm(request.POST)
if form.is_valid():
edited = Employee.objects.filter(pk=employee_id)
edited.update(
first_name = request.POST.get('first_name'),
second_name = request.POST.get('second_name'),
patronymic = request.POST.get('patronymic'),
birth_date = request.POST.get('birth_date')
)
else:
form = AddEmployeeForm()
form = AddEmployeeForm()
return render(
request,
'edit_employee.html',
context={'form': form}
)
This way even if the key does not exist you'll get a None value instead of an exception. Also be sure that the key values are the same in your template.

How to set initial value in the form

Hey guys how can i set initial value in my form field, let say the user click "BidForm" in the search form, i want the BidForm value will be the value of ProjectName in the other form...
here's my code in my search views
def search_views(request):
project_list = ProjectNameInviToBid.objects.all()
query = request.GET.get('query')
if query:
project_list = project_list.filter(ProjectName__icontains=query)
context = {
'project_list': project_list
}
return render(request, 'content/search_views.html', context)
and my other views
def project_name_details(request, sid):
majordetails = ProjectNameInviToBid.objects.get(id=sid)
if request.method == 'POST':
form = invitoBidForm(request.POST, request.FILES)
form.fields['ProjectName'].initial = majordetails
if form.is_valid():
form.save()
messages.success(request, 'File has been Uploaded')
else:
form = invitoBidForm()
args = {
'majordetails': majordetails,
'form': form
}
return render(request,'content/invitoBid/bacadmininvitoBid.html', args)
my form.py
class invitoBidForm(ModelForm):
class Meta:
model = InviToBid
fields = ('ProjectName','NameOfFile', 'Contract_No', 'Bid_Opening',
'Pre_Bid_Conference', 'Non_Refundable_Bidder_Fee',
'Delivery_Period',
'Pdf_fileinvi',)
and my models.py
class ProjectNameInviToBid(models.Model):
ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True)
DateCreated = models.DateField(auto_now=True)
def __str__(self):
return self.ProjectName
class InviToBid(models.Model):
today = date.today()
ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE)
NameOfFile = models.CharField(max_length=255, verbose_name='Name of File')
Contract_No = models.IntegerField(verbose_name='Contract No')
def __str__(self):
return self.NameOfFile
First, I shall praise your documentation. Most people fail to provide the important code.
You can add something like this to your code here that will do what you require.
An example from my own code
if request.method == 'GET' and request.user.is_authenticated:
study = Study.objects.get(pk=studyID)
form = ContactForm(initial={'from_email': request.user.email, 'subject': "Study: " + study.name ,'message': study_message.format(request.user.get_short_name(), request.user.get_full_name())})
How you should change your code
Change your code in your other views from this:
else:
form = invitoBidForm()
to
else:
form = invitoBidForm(initial={'ProjectName': <wherever your project name comes from>})

How can I save an string pk into int pk?

I have a problem with a submit form when I want to save the profile ID the form have an error, i dont understand why because in the console all is ok but the form_valis is false, so think because the ModelChoiseField send a pk in sting format so how can i convert the string pk to int pk ?
My Form
class UsuarioForm(forms.ModelForm):
id_perfil = forms.ModelChoiceField(queryset=Perfil.objects.filter(status='1'), label="Perfil" ,empty_label="Seleciona perfil", widget=forms.Select(attrs={'class':'form-control'}))
My Models
class Usuario(models.Model):
id_usuario = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=255)
id_perfil = models.IntegerField()
status = models.CharField(max_length=50)
class Perfil(models.Model):
id_perfil = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=255)
status = models.CharField(max_length=50)
The save method
def save_usuario_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
usuario = form.save(commit=False)
if usuario.status == '':
usuario.status = '1'
usuario.id_usuario_alt = '1'
elif usuario.status == '1':
usuario.status = '2'
form.save()
data['form_is_valid']= True
usuarios = Usuario.objects.filter(status='1').order_by('id_usuario')[:5]
data['html_usuario_list'] = render_to_string('back/Modulo_usuarios/usuarios_list.html',{
'usuarios':usuarios
})
else:
data['form_is_valid']= False
context = {'form':form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
The error
All fields are fill and post method is OK

can't change model instance

views.py
def patient_num(request):
if request.method == 'POST':
form = EditToBeSaveForm(request.POST)
if form.is_valid():
num = form.cleaned_data['病人编号']
new_p = Patient.objects.get(p_number=num)
if new_p:
new_p.p_name = form.cleaned_data['姓名']
new_p.p_sex = form.cleaned_data['性别']
new_p.p_age = form.cleaned_data['年龄']
new_p.p_tel_number = form.cleaned_data['电话号码']
new_p.save()
return render(request, 'polls/patient_edit.html')
else:
form = EditToBeSaveForm()
return render(request, 'polls/patient_num.html', {'form': form})
models.py
class Patient(models.Model):
sex_choice = (
('男', '男'),
('女', '女'),
)
p_name = models.CharField(max_length=100, default='template')
p_age = models.IntegerField(default=0)
p_number = models.IntegerField(default=0)
p_tel_number = models.IntegerField(default=0)
p_sex = models.CharField(choices=sex_choice, max_length=2, default='男')
forms.py
class EditForm(forms.Form):
病人编号 = forms.IntegerField()
class EditToBeSaveForm(forms.Form):
sex_choice = (
('male', '男'),
('female', '女'),
)
病人编号 = forms.IntegerField(label='你要修改的病人编号')
姓名 = forms.CharField(max_length=100)
年龄 = forms.IntegerField()
电话号码 = forms.IntegerField()
性别 = forms.ChoiceField(choices=sex_choice)
after i populate the form and submit it, the view didn't update the database instance,why?
i can do it one by one in shell as below.
new confuse!when i populate the form with invalid value,for example, an inexistent id of Patient object,it will still render the template,why?
It seems to me your problem is that you never reach the code under the if form.is_valid() of your patient_num view. Try to add some prints after the if form.is_valid() clause and make sure your form is valid. It is expected that your model will not be updated if your form is not valid.
Your problem here that you are passing request to form instead request.POST
form = EditToBeSaveForm(request.POST)
i put some 'print stuff' in my view and disvocer sth:
def patient_num(request):
print(111)
if request.method == 'POST':
print(2222)
form = EditToBeSaveForm(request.POST)
if form.is_valid():
print(3333)
num = form.cleaned_data['病人编号']
new_p = Patient.objects.get(p_number=num)
if new_p:
print(4444)
new_p.p_name = form.cleaned_data['姓名']
new_p.p_sex = form.cleaned_data['性别']
new_p.p_age = form.cleaned_data['年龄']
new_p.p_tel_number = form.cleaned_data['电话号码']
new_p.save()
return render(request, 'polls/patient_edit.html')
else:
form = EditToBeSaveForm()
return render(request, 'polls/patient_num.html', {'form': form})
i can only see 111 in the shell output.it seems that the view even didn't receive the post request.and i check my html file and find the problem.the form's destination direct to another view function…… it's so stupid, i'm sorry for waste your time !

django updating user profile form

forms.py
class UserProfileForm(forms.ModelForm):
phone = forms.CharField(max_length = 15,widget = forms.TextInput(attrs = {'placeholder':'Enter mobile no. ','class':''}))
profession = forms.CharField(max_length= 50,widget = forms.Select(choices = PROFESSION_CHOICES,attrs = {'class':''}))
#email = forms.EmailField(label='Email address',max_length = 75,widget = forms.TextInput(attrs={'placeholder':'Email address.','class':''}))
sex = forms.CharField(max_length = 20,label="I am :",widget=forms.Select(choices=SEX_CHOICES,attrs = {'class':''}))
first_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Please enter your real name.','class':''}))
last_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter last name.','class':''}))
location = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter your current location','class':''}))
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
if first_name == '':
raise forms.ValidationError("This field is required.")
return first_name
def save(self,*args,**kw):
self.instance.first_name = self.cleaned_data.get("first_name")
self.instance.last_name = self.cleaned_data.get("last_name")
self.instance.sex = self.cleaned_data.get("sex")
self.instance.location = self.cleaned_data.get("location")
self.instance.profession = self.cleaned_data.get("profession")
self.instance.phone = self.cleaned_data.get("phone")
self.instance.save()
return self.instance
class Meta:
model = User
fields = ('username','first_name','last_name','phone','sex','profession','location')
views.py
def profile(request,nav="profile",template="profile.html",context = {},extra_context = None):
if request.POST:
if 'profileFormSubmit' in request.POST:
pform = UserProfileForm(request.POST,instance = request.user)
if pform.is_valid():
try:
user = pform.save()
return redirect(profile,nav="profile")
except RuntimeError as e:
return HttpResponse(e)
error
The User could not be changed because the data didn't validate.
line
user = super(UserProfileForm,self).save(*args,**kw)
doubt
what changes am i supposed to make to get rid of this error
how am i supposed to change the , i have tried removing all the clean_field form methods , but still getting the same error , please help , thanks in advance.
You are calling save on your form before you clean. And you are calling save twice. Once at the start of the form save. And once at the end.
pform.is_valid() returns a boolean that you never check.
docs on modelforms
The form wasn't validating because I was using 'username' in my meta class of the UserProfileForm, which wasn't supposed to be there.