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()
Related
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
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.
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 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()
I've this in my views and trying to get new truck_name assigned to a new Product.
When user with truck_name as None and no instance of Product, the script goes to
try:
truck_name = Product.objects.get(user=request.user)
and skips to the except:
#login_required
def profile_edit(request):
owner = TruckOwnerStatus.objects.get(user=request.user)
truck_form = RegisterTruckForm()
i = owner.id
print i
try:
truck_name = Product.objects.get(user=request.user)
if request.method == 'GET':
if truck_name is not None:
truck_form = RegisterTruckForm(instance=truck_name)
else:
truck_form = RegisterTruckForm()
context = {
'truck_form': truck_form,
'truck_name': truck_name,
}
return render(request, 'accounts/profile_edit.html', context)
elif request.method == 'POST':
if truck_name is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES, instance=truck_name)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
#once clicked save
if truck_form.is_valid():
truck_name = truck_form.save(commit=False)
truck_name.product = Product.objects.get(user=request.user)
truck_form.save_m2m()
truck_name.save()
messages.success(request, "Successfully Saved!!")
return HttpResponseRedirect('/')
return render_to_response('accounts/profile_edit.html', {'truck_form': truck_form}, context_instance=RequestContext(request))
except:
print "hii"
if request.method == 'POST':
truck_form = RegisterTruckForm(request.POST, request.FILES)
truck_owner = request.user
if truck_owner is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES, instance=truck_owner)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
if truck_form.is_valid():
truck_owner = truck_form.save(commit=False)
truck_owner.profile = Product.objects.create(user=request.user)
truck_form.save_m2m()
truck_owner.profile.save()
messages.success(request, "Successfully Saved!!")
return HttpResponseRedirect('/')
else:
messages.error(request, "Please recheck")
# return render(request, context, 'accounts/profile_edit.html',)
context = {"truck_form": truck_form}
return render(request, 'accounts/profile_edit.html', context)
It does the job of saving the form but does not assign the truck_name from the form to the request user. Hence nothing gets assigned to the new Product
I tried putting
truck_name = Product.objects.get(user=request.user) in the except but it returns an error because there is no instance of Product for this user and therefore no truck_name.
I can see the entry in admin but can't view it because there is no truck_name. But if I were to run the entire profile_edit for the same user and fill the the form, the truck_name gets assigned.
How do I get it assigned?
Below is my Product model.
class Product(models.Model):
user = models.OneToOneField(User)
owner_name = models.CharField(max_length=120)
email = models.EmailField(max_length=120)
contact_number = models.IntegerField(max_length=15, null=True, blank=True)
foodtruck_name = models.CharField(max_length=120)
logo = models.ImageField(upload_to='foodtruck/logo/', null=True, blank=True)
slogan = models.TextField(max_length=250, null=True, blank=True)
about_us = models.TextField(max_length=500, null=True, blank=True)
operating_state = models.CharField(max_length=120, choices=STATE_CHOICES)
bsb = models.IntegerField(max_length=15, null=True, blank=True)
account_number = models.IntegerField(max_length=15, null=True, blank=True)
availability_link = models.CharField(max_length=300, null=True, blank=True)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
update_defaults = models.BooleanField(default=False)
def __unicode__(self):
return self.foodtruck_name
class Meta:
unique_together = ('foodtruck_name', 'slug')
def get_price(self):
return self.price
def get_absolute_url(self):
return reverse("single_product", kwargs={"slug": self.slug})