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.
Related
I everyone, I have a problem with a django's view. My goal is to change the 'execute' field into 'True' if newOrder is buy and there is some other sell order with a inferior price. And reverse for sell newOrders. I want to change the 'execute' field for the newOrder and also for the other order (in pairs). That's my code:
views.py
def order(request):
form = OrderForm()
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
new_order = form.save()
if new_order.buy is True:
sellOrder = Order.objects.filter(sell=True, execute=False,
price__lte=new_order.price).first().update(execute=True)
new_order.execute = True
sellOrder.save()
else:
buyOrder = Order.objects.filter(buy=True,
execute=False,price__gte=new_order.price).first().update(execute=True)
new_order.execute = True
buyOrder.save()
new_order.profile = request.user
new_order.save()
return redirect('home')
else:
form = OrderForm()
contex = {'form': form}
return render(request, 'app/new_order.html', contex)
models.py
class Profile(models.Model):
_id = ObjectIdField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
wallet = models.FloatField()
class Order(models.Model):
_id = ObjectIdField()
profile = models.ForeignKey(User, on_delete=models.CASCADE)
datetime = models.DateTimeField(auto_now_add=True)
buy = models.BooleanField(blank=True)
sell = models.BooleanField(blank=True)
price = models.FloatField()
quantity = models.FloatField()
execute = models.BooleanField(blank=True)
But something goes wrong. This is the error:
AttributeError at /new_order/
'NoneType' object has no attribute 'update'
sellOrder returns a count of updated rows, not the object updated
sellOrder = Order.objects.filter(sell=True, execute=False,
price__lte=new_order.price).first().update(execute=True)
instead try
sellOrder = Order.objects.filter(sell=True, execute=False,
price__lte=new_order.price).first()
new_order.execute = True
sellOrder.execute = True
sellOrder.save()
this is views.py
def registerItem(request):
print(request)
try:
print("====111", request.method)
if request.method == 'POST':
print("=========222", request.POST)
form = ItemForm(request.POST)
print("====333", form.is_bound)
print("====444", form)
print("====555", form.cleaned_data['mart_id']())
print("====666", form.is_valid())
if form.is_valid():
mart = MartModel.objects.get(id__exact=form.cleaned_data['mart_id'])
print("====666", mart)
seq = ItemModel.objects.filter(mart_id__exact=mart).values('seq').order_by('-seq')[:1]
if seq:
seq = seq[0]['seq']+1
else:
seq = 1
# form.save()
item = ItemModel(mart_id=mart, seq=seq, name=form.cleaned_data['name'], price=form.cleaned_data['price'], expirationDate=form.cleaned_data['expirationDate'], stockYn=form.cleaned_data['stockYn'])
item.save()
form = ItemForm()
return render(request, 'mobileWeb/admin/register_item.html', {'form':form})
else:
form = ItemForm()
return render(request, 'mobileWeb/admin/register_item.html', {'form':form})
except Exception as ex:
print('====777 : Error occured : ', ex)
request.POST value is correct. you can confirm it by log No.2.
form is bound correctly. you can confirm it by log No.3.
but the form failed to receive values. you can confirm it by log No.4.
this is forms.py
class MartForm(forms.ModelForm):
class Meta:
model = MartModel
fields = ['name', 'address', 'tell', 'phone', 'xPosition', 'yPosition']
class ItemForm(forms.ModelForm):
choicesQueryset = MartModel.objects.all().values('id', 'name')
choicesDic = []
for choice in choicesQueryset:
choicesDic.append((choice['id'], choice['name']))
mart_id = forms.CharField(label='mart', widget=forms.Select(choices=choicesDic))
class Meta:
model = ItemModel
fields = ['mart_id', 'name', 'price', 'expirationDate', 'stockYn']
this is models.py
class MartModel(models.Model):
name = models.CharField(max_length=20, blank=False)
address = models.TextField(blank=False)
tell = models.CharField(blank=True, max_length=12)
phone = models.CharField(blank=True, max_length=11)
imageFileNo = models.CharField(blank=True, max_length=3)
xPosition = models.FloatField(blank=False)
yPosition = models.FloatField(blank=False)
delete_yn = models.CharField(blank=False, default="N", max_length=1)
ins_dttm = models.DateTimeField(blank=False, auto_now_add=True)
ins_user = models.CharField(blank=False, max_length=20, default='ADMIN')
upt_dttm = models.DateTimeField(blank=False, auto_now=True)
upt_user = models.CharField(blank=False, max_length=20, default='ADMIN')
class ItemModel(models.Model):
mart_id = models.ForeignKey('martModel', models.DO_NOTHING)
seq = models.IntegerField(blank=False)
name = models.CharField(blank=False, max_length=20)
price = models.IntegerField(blank=False)
expirationDate = models.DateField(blank=False)
stockYn = models.CharField(blank=False, max_length=1, default='Y')
delete_yn = models.CharField(blank=False, default="N", max_length=1)
ins_dttm = models.DateTimeField(blank=False, auto_now_add=True)
ins_user = models.CharField(blank=False, max_length=20, default='ADMIN')
upt_dttm = models.DateTimeField(blank=False, auto_now=True)
upt_user = models.CharField(blank=False, max_length=20, default='ADMIN')
class Meta:
unique_together = (
('mart_id', 'seq')
)
I know about that it must be a instance not a value when deal with the foreignKey.
but the error occured on binding time.
is this concerend with foreignKey??
================
after advice
no mart name is here.
this is forms.py
class ItemForm(forms.ModelForm):
mart = forms.ModelChoiceField(queryset=MartModel.objects.all(), to_field_name='name')
class Meta:
model = ItemModel
fields = ['mart', 'name', 'price', 'expirationDate', 'stockYn']
this is views.py
from django.shortcuts import render
from .forms import *
# Create your views here.
def index(request):
try:
marts = MartModel.objects.all().values('id', 'name', 'imageFileNo', 'xPosition', 'yPosition')
items = ItemModel.objects.filter(stockYn__exact='Y').values('mart', 'name', 'price', 'expirationDate').order_by('mart_id', 'seq')
return render(request, 'mobileWeb/index/index.html', {'marts':marts, 'items':items})
except Exception as ex:
print('Error occured : ', ex)
def registerMart(request):
try:
if request.method == 'POST' :
form = MartForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'mobileWeb/index/index.html')
else :
form = MartForm()
return render(request, 'mobileWeb/admin/register_mart.html', {'form':form})
except Exception as ex:
print('Error occured : ', ex)
def registerItem(request):
print(request)
try:
print("====111", request.method)
if request.method == 'POST':
print("=========222", request.POST)
form = ItemForm(request.POST)
print("====333", form.is_bound)
print("====444", form)
if form.is_valid():
mart = MartModel.objects.get(id__exact=form.cleaned_data['mart'])
print("====666", mart)
seq = ItemModel.objects.filter(mart__exact=mart).values('seq').order_by('-seq')[:1]
if seq:
seq = seq[0]['seq']+1
else:
seq = 1
# form.save()
item = ItemModel(mart=mart, seq=seq, name=form.cleaned_data['name'], price=form.cleaned_data['price'], expirationDate=form.cleaned_data['expirationDate'], stockYn=form.cleaned_data['stockYn'])
item.save()
form = ItemForm()
return render(request, 'mobileWeb/admin/register_item.html', {'form':form})
else:
form = ItemForm()
return render(request, 'mobileWeb/admin/register_item.html', {'form':form})
except Exception as ex:
print('====777 : Error occured : ', ex)
this is debug variable when make Item Form
this is debug variable about queryset
this is debug variable about 1st member of queryset
ofcourse I did makemigrations, migrate.
I don't know why are you trying to approach like this. ModelForm has very nice way to handle FK, and if you want to show name of the MartModel object, then you can use ModelChoiceField's to_field_name option. For example:
class ItemForm(forms.ModelForm):
mart_id = forms.ModelChoiceField(queryset=MartModel.objects.all(), to_field_name='name')
class Meta:
model = ItemModel
fields = ['mart_id', 'name', 'price', 'expirationDate', 'stockYn']
Also, please change the name of the field mart_id to mart, because underneath django creates a field name mart_id, if you assign the field name to mart.
Finally, in the view, you should not call cleaned_data[...] before calling form.is_valid(). Unless the form is validated, the data won't be available in cleaned_data.
Update
(from comments) Add a __str__ method at the bottom of MartModel class:
class MartModel(models.Model):
...
def __str__(self):
return self.name
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>})
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
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 !