Can any one please help me i want to search my expenses income which is in my models.py using date wise dynamic search where user will input date and he will see the result in template i dont know how to code that template ..I tried form but not working.. :(
my views.py
def date_page(request):
f_date = '2018-12-05'
t_date = '2019-09-12'
from_date = datetime.datetime.strptime(f_date, "%Y-%m-%d").date()
to_date = datetime.datetime.strptime(t_date, "%Y-%m-%d").date()
date_queryset = Add.objects.filter(date__range=(from_date, to_date))
print (date_queryset)
return render (request , 'date_page.html',)
Pass the date value as URL parameter and fetch it using request.GET as,
def date_page(request):
f_date = request.GET.get("f_date")
t_date = request.GET.get("t_date")
date_queryset = Add.objects.filter(date__range=(f_date, t_date))
print(date_queryset)
return render(request, 'date_page.html', )
Example URL : /api/end-point/expenses/?f_date=2018-12-05&t_date=2019-09-12
Related
I want to implement search on my django project. On my following queryset, with else condition its passing correct data. But with if condition whatever I search, it shows nothing.
def get_queryset(self):
category = self.request.GET['category']
query = self.request.GET['q']
if category == 'all':
products = Products.objects.filter(Q(name__icontains=query) | Q(category__name__icontains=query)).all()
else:
products = Products.objects.filter(Q(category__slug=category), Q(category__slug__icontains=self.request.GET['q']) | Q(name__icontains=self.request.GET['q']))
I have two models prodcut_prices and WrongPrice.
In WrongPrice the user can correct report wrong prices - when the price is reported it should also be updated in product_price.
My problem is, even though I instantiate product_price at the very beginning as instance_productprice, all of its required fields returns the "this field has to be filled out" error.
How come those field are not set when im using the instance instance_productprice = product_prices.objects.filter(id=pk)[0] ? Note, that all fields in product_prices are always non-empty since they are being pulled from the product_price model, which is handled in another view, thus that is not the issue.
def wrong_price(request,pk):
#Get the current price object
instance_productprice = product_prices.objects.filter(id=pk)[0]
#Get different values
wrong_link = instance_productprice.link
img_url = instance_productprice.image_url
wrong_price = instance_productprice.last_price
domain = instance_productprice.domain
# Create instances
instance_wrongprice = WrongPrice(
link=wrong_link,
correct_price=wrong_price,
domain = domain)
if request.method == "POST":
form_wrong_price = wrong_price_form(request.POST,instance=instance_wrongprice)
# Update values in product_prices
form_product_price = product_prices_form(request.POST,instance=instance_productprice)
form_product_price.instance.start_price = form_wrong_price.instance.correct_price
form_product_price.instance.last_price = form_wrong_price.instance.correct_price
if form_wrong_price.is_valid() & form_product_price.is_valid():
form_wrong_price.save()
form_product_price.save()
messages.success(request, "Thanks")
return redirect("my_page")
else:
messages.error(request, form_product_price.errors) # Throws empty-field errors,
messages.error(request, form_wrong_price.errors)
return redirect("wrong-price", pk=pk)
else:
form_wrong_price = wrong_price_form(instance=instance_wrongprice)
return render(request, "my_app/wrong_price.html",context={"form":form_wrong_price,"info":{"image_url":img_url}})
I am bit confused about how you implemented it. You have passed a instance of WrongPrice price through the form, which is unnecessary, you could have used initial:
wrong_values = dict(
link=wrong_link,
correct_price=wrong_price,
domain = domain
)
form_wrong_price = wrong_price_form(initial= wrong_values)
Then you are adding values to product_prices_form from instance of form_wrong_price. I don't see why you need a form again here. You can simple use:
form_wrong_price = wrong_price_form(request.POST, initial= wrong_values)
if form_wrong_price.is_valid():
instance = form_wrong_price.save()
instance_productprice.start_price = instance.correct_price
instance_productprice.last_price = instance.correct_price
instance_productprice.save()
Finally, please use PascalCase when defining class names. And you can get the product prices by product_prices.objects.get(id=pk)(instead of filter()[0]).
I've been searching for an answer for hours. I apologise if I missed something.
I'm using the same form multiple times in order to add rows to my database.
Every time I check an excel file to pre-fill some of the wtforms StringFields with known information that the user may want to change.
The thing is: I change the form.whatever.data and when printing it, it shows the new value. But when I render the template it keeps showing the old value.
I tried to do form.hours_estimate.data = "" before assigning it a new value just in case but it didn't work.
I will attach here the route I'm talking about. The important bit is after # Get form ready for next service. If there's more info needed please let me know.
Thank you very much.
#coordinator_bp.route("/coordinator/generate-order/<string:pev>", methods=['GET', 'POST'])
#login_required
def generate_order_services(pev):
if not (current_user.is_coordinator or current_user.is_manager):
return redirect(url_for('public.home'))
# Get the excel URL
f = open("./app/database/datafile", 'r')
filepath = f.read()
f.close()
error = None
if GenerateServicesForm().submit1.data and GenerateServicesForm().validate():
# First screen submit (validate the data -> first Service introduction)
form = FillServiceForm()
next_service_row = get_next_service_row(filepath)
if next_service_row is None:
excel_info = excel_get_pev(filepath)
error = "Excel error. Service code not found. If you get this error please report the exact way you did it."
return render_template('coordinator/get_pev_form.html', form=GetPevForm(), error=error, info=excel_info)
service_info = get_service_info(filepath, next_service_row)
service_code = service_info[0]
start_date = service_info[1]
time_estimate = service_info[2]
objects = AssemblyType.get_all()
assembly_types = []
for assembly_type in objects:
assembly_types.append(assembly_type.type)
form.service_code.data = service_code
form.start_date.data = start_date
form.hours_estimate.data = time_estimate
return render_template('coordinator/fill_service_form.html', form=form, error=error, assembly_types=assembly_types)
if FillServiceForm().submit2.data:
if not FillServiceForm().validate():
objects = AssemblyType.get_all()
assembly_types = []
for assembly_type in objects:
assembly_types.append(assembly_type.type)
return render_template('coordinator/fill_service_form.html', form=FillServiceForm(), error=error,
assembly_types=assembly_types)
# Service screen submits
# Here we save the data of the last submit and ready the next one or end the generation process
# Ready the form
form = FillServiceForm()
next_service_row = get_next_service_row(filepath)
if next_service_row is None:
excel_info = excel_get_pev(filepath)
error = "Excel error. Service code not found. If you get this error please report the exact way you did it."
return render_template('coordinator/get_pev_form.html', form=GetPevForm(), error=error, info=excel_info)
service_info = get_service_info(filepath, next_service_row)
service_code = service_info[0]
form.service_code.data = service_code
# create the service (this deletes the service code from the excel)
service = create_service(form, filepath)
if isinstance(service,str):
return render_template('coordinator/fill_service_form.html', form=form, error=service)
# Get next service
next_service_row = get_next_service_row(filepath)
if next_service_row is None:
# This means there is no more services pending
return "ALL DONE"
else:
# Get form ready for next service
service_info = get_service_info(filepath, next_service_row)
service_code = service_info[0]
start_date = service_info[1]
time_estimate = service_info[2]
print("time_estimate")
print(time_estimate) # I get the new value.
objects = AssemblyType.get_all()
assembly_types = []
for assembly_type in objects:
assembly_types.append(assembly_type.type)
form.service_code.data = service_code
form.start_date.data = start_date
form.hours_estimate.data = time_estimate
print(form.hours_estimate.data) # Here I get the new value. Everything should be fine.
# In the html, the old value keeps on popping.
return render_template('coordinator/fill_service_form.html', form=form, error=error,
assembly_types=assembly_types)
number_of_services = excel_get_services(filepath=filepath, selected_pev=pev)
# Get the number of the first excel row of the selected pev
first_row = excel_get_row(filepath, pev)
if first_row is None:
excel_info = excel_get_pev(filepath)
error = "Excel error. PEV not found. If you get this error please report the exact way you did it."
return render_template('coordinator/get_pev_form.html', form=GetPevForm(), error=error, info=excel_info)
service_code = []
start_date = []
time_estimate_code = []
quantity = []
# Open the excel
wb = load_workbook(filepath)
# grab the active worksheet
ws = wb.active
for idx in range(number_of_services):
# Append the data to the lists
service_code.append(ws.cell(row=first_row+idx, column=12).value)
start_date.append(str(ws.cell(row=first_row + idx, column=5).value)[:10])
time_estimate_code.append(ws.cell(row=first_row+idx, column=7).value)
quantity.append(ws.cell(row=first_row + idx, column=9).value)
wb.close()
return render_template('coordinator/generate_services_form.html',
form=GenerateServicesForm(),
pev=pev,
service_code=service_code,
start_date=start_date,
time_estimate_code=time_estimate_code,
quantity=quantity)
Well I found a workarround: I send the data outside the form like this:
return render_template('coordinator/fill_service_form.html', form=form, error=error,
assembly_types=assembly_types,
service_code=service_code,
start_date=start_date,
time_estimate=time_estimate)
And replace the jinja form for this:
<input class="form-control" placeholder="2021-04-23" name="start_date" type="text" value="{{start_date}}">
I'm still using the form (name= the form field name) and at the same time I input the value externally.
I hope this helps somebody.
I've got a function which sends an email with expenses. Everything works fine, but I have no idea how to implement a small part of the code into a template and give for the user an option to choose a period of time.
For example: user should choose a year and month from the template.
def mail_from_web(request):
email = EmailMessage('Your expenses', 'Hello there. Some text', 'email#from',
['email#to'])
attachment_csv_file = StringIO()
writer = csv.writer(attachment_csv_file, delimiter=',')
writer.writerow(['Date', 'Customer', 'Car park'])
for call in Call.objects.filter(date__year='2019', date__month='04').order_by('date'):
writer.writerow([call.date_start.strftime("%Y-%m-%d"), call.customer, call.expenses])
email.attach('expenses.csv', attachment_csv_file.getvalue(), 'text/csv')
email.send(fail_silently=False)
return render(request, 'calls/mail_sent.html')
Instead of this:
objects.filter(date__year='2019', date__month='04')
create a form
class MyForm(forms.Form)
year = forms.IntegerField(
widget = forms.NumberInput(min=2019)
)
month = forms.IntegerField(
widget = forms.NumberInput(min=1, max=12))
Add it to your context to pass to the template.
Show in the template
...
{{form}}
...
In the view
year = int(request.POST['year'])
month = int(request.POST['month'])
Change Call.objects.filter(date__year='2019', date__month='04') to Call.objects.filter(date__year=year, date__month=month)
I've just realised you're not using int for the year and month so you'll need to modify accordingly.
I am attempting to create a promo code for a shopping cart that I already have. I want it to be simple, such as typing 100off to get $100 off, I am getting a error saying "global name 'PromoCode' is not defined".
models.py
class PromoCode(ModelForm):
code = models.FloatField(max_length=15)
discount = models.FloatField(max_length=15)
views.py
def addtocart(request, prod_id):
if (request.method == 'POST'):
form = CartForm(request.POST)
if form.is_valid():
newComment = form.save()
newComment.session = request.session.session_key[:20]
newComment.save()
return HttpResponseRedirect('/products/' + str(newComment.product.id))
else:
form = CartForm( {'name':'Your Name', 'session':'message', 'product':prod_id} )
return render_to_response('Products/comment.html', {'form': form, 'prod_id': prod_id})
def delItem(request, prod_id):
addtocart = get_object_or_404(Cart, pk = prod_id)
prod_id = addtocart.product.id
addtocart.delete()
return HttpResponseRedirect('/userHistory/')
def userHistory(request):
promo = PromoCode.objects.filter(code = code_from_the_form)
userCart = Cart.objects.filter(session = request.session.session_key[:20])
totalCost = 0
for item in userCart:
print item
totalCost += item.quantity * item.product.prodPrice * 1.06
return render_to_response('Products/history.html', {'userCart':userCart, 'totalCost' : totalCost})
Add a PromoCode model with two fields: code and discount. You can then add a couple of promo codes in the admin.
In the form, just add a promo code field and upon submit, check if the code matches any of your PromoCode objects and apply the discount.
(And perhaps a bit of javascript to check the code on the fly. And I'd add some checks here and there to make sure your discount is well between 0 and 1 ("0.5") if you just want to multiply and well between 0 and 100 if it is a percentage. Just make sure you cannot make a mistake with it, that would be my fear if I'd have to implement it :-)