How can I save an string pk into int pk? - django

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

Related

Django changing models field into views

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

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

Flask date not set at creation but is set at update

views.py
#app.route('/new', methods = ['POST', 'GET'])
#login_required
def new():
form = StudentForm()
if request.method == 'POST':
if form.validate_on_submit():
flash('All fields are required.')
return render_template('form.html', action = 'new', form = form)
else:
student = students(
request.form['first_name'], request.form['last_name'], \
request.form['date_of_birth'], \
request.form['date_of_join'], request.form['address']
db.session.add(student)
db.session.commit()
return redirect(url_for('show_all'))
return render_template('form.html', action = url_for('new'), form = form)
#app.route('/edit/<int:id>', methods = ['POST', 'GET'])
#login_required
def edit(id):
item = students.query.get(id)
form = StudentForm(obj=item)
if request.method == 'POST':
if form.validate_on_submit():
item = students.query.get(id)
form = StudentForm(obj=item)
return render_template('form.html', action = url_for('edit',id = id), form = form)
else:
form.populate_obj(item)
db.session.add(item)
db.session.commit()
return redirect(url_for('show_all'))
return render_template('form.html', action = url_for('edit',id = id), form = form)
models.py
class students(db.Model):
__tablename__ = "students"
id = db.Column('id', db.Integer, primary_key = True)
first_name = db.Column(db.String(25))
last_name = db.Column(db.String(25))
date_of_birth = db.Column(db.Date)
date_of_join = db.Column(db.Date)
address = db.Column(db.String(200))
forms.py
class StudentForm(Form):
first_name = TextField("First Name:")
last_name = TextField("Last Name:")
date_of_birth = DateField("Date of Birth:", format='%m/%d/%Y')
date_of_join = DateField("Date of Joining:", format='%m/%d-%Y')
address = TextAreaField("Address:")
submit = SubmitField("Submit")
All other fields are added to the database while adding new item, but the date is not stored. I cant find what the problem actually is. The date field is stored during edit if i use form.validate() for form validation. And if i use form.validate_on_submit() the date field is not stored while adding or editing...

Django 1.8: add user to Modelform in views: not null constraint failed

I know there are a lot of similar questions here, but none of them seem to be working with my view in Django 1.8 with a ModelForm.
I have a user profile form that works as long as I have each required field in the template context, but I only want each logged in user to fill out their own form.
I'm doing something wrong here, and I'm not sure what the problem is. Can someone correct me? I've spent hours looking at other posts and trying various suggestions from SO. I'm getting "NOT NULL constraint failed: camp_userprofile.user_id"
Here's my models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
picture = models.ImageField(upload_to='profile_images', blank=True)
city = models.CharField(max_length = 20)
needs_camp_bike = models.BooleanField(default=False)
diet_lifestyle = models.CharField(max_length = 200, choices=What_are_you, null=True, blank=True)
meal_restrictions = models.CharField(max_length = 200, blank= True)
other_restrictions = models.CharField(max_length=100, blank=True)
arrival_day = models.IntegerField(choices=Days)
departure_day = models.IntegerField(choices=Days)
date = models.DateTimeField(auto_now_add=True, blank=True)
def __str__(self):
return '%s %s %s %s %s %s %s %s %s' %(
self.user, self.picture, self.city,
self.needs_camp_bike,
self.diet_lifestyle, self.meal_restrictions, self.other_restrictions,
self.arrival_day, self.departure_day
)
My forms.py
class UserProfileForm(ModelForm):
class Meta:
Fish = "Fish"
Mammal = "Mammal"
Vegetarian = "Vegetarian"
Omnivore = "Omnivore"
Onions = "Onions"
Cucumber = "Cucumber"
Peppers = "Peppers"
Gluten_free = "Gluten_free"
Vegan = "Vegan"
Shellfish = "Shellfish"
Olives = "Olives"
Pork = "Pork"
Soy = "Soy"
Dairy = "Dairy"
Cilantro = "Cilantro"
Quinoa = "Quinoa"
Nightshades = "Nightshades"
Nuts = "Nuts"
Pescaterian = "Pescaterian"
Restrictions = (
(Mammal, "Mammal"),
(Onions, "Onions"),
(Cilantro, "Cilantro"),
(Soy, "Soy"),
(Dairy, "Dairy"),
(Quinoa, "Quinoa"),
(Pork, "Pork"),
(Olives, "Olives"),
(Dairy, "Dairy"),
(Peppers, "Peppers"),
(Cucumber, "Cucumber"),
(Nightshades, "Nightshades"),
(Nuts, "Nuts")
)
model = UserProfile
fields = ('picture', 'city',
'needs_camp_bike', 'diet_lifestyle',
'other_restrictions', 'arrival_day',
'departure_day', 'meal_restrictions')
widgets = {
'meal_restrictions': forms.widgets.CheckboxSelectMultiple(choices=Restrictions),
}
and my views.py
#login_required
def profile(request):
form = UserProfileForm(request.POST)
print(request.user)
if request.method == 'POST':
if form.is_valid():
form.save(commit=False)
form.user =request.user.username
form.save(commit=True)
else:
print(messages.error(request, "Error"))
return render(request, "profile.html", RequestContext(request, {'form': form, 'profile': profile,}))
You shouldn't do form.user = request.user.username, because form.user won't add the user to the form. You should capture the object that form.save(commit=false) returns, then assign the user to that object and save it.
Also you cannot assign a user field with username, username is only a string not User object. You should do this instead:
if form.is_valid():
userprofile = form.save(commit=False)
userprofile.user = request.user
userprofile.save()