I have a form elements in my html.
<form action="" method="GET">
<input type="text" name="start_date" placeholder="From" value="{{ request.GET.start_date }}">
<input type="text" name="end_date" placeholder="To" value="{{ request.GET.end_date }}">
</form>
I want to access to the start_date and end_date inside one of my view.py methods, but Im getting None all the time.
So far I have tried:
temp = request.GET.get('start_date', None)
temp = request.GET['start_date']
What might be the problem? How can I access start_date and end_date?
EDIT: Im tring to access it in this method:
def download_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s' % 'invoice.pdf'
books = books.objects.all()
date = request.GET.get('start_date', None)
books.filter(order__date = temp)
c = canvas.Canvas(response)
c.drawText(date)
c.showPage()
c.save()
return response
You can get the start_date and end_date once you submit that form. Like POST method GET form also expect you to submit from the frontend.
<form action="." method="GET">
<input type="text" name="start_date" placeholder="From" value="{{ request.GET.start_date }}">
<input type="text" name="end_date" placeholder="To" value="{{ request.GET.end_date }}">
<input type="submit" value="submit">
</form>
Or forget the form method just append the parameter in the url is enough. Like this...
http://localhost:8000/?start_date=test_start_date&end_date=test_end_date
Edit:
You have to check the GET dictionary before accessing. Because start_date will be not be present in the every GET request. Once the user submitted the GET request then we can access the GET parameter....
start_date = request.GET.get('start_date')
if start_date:
print(start_date)
Edit 2:
# Create your views here.
def index(request):
start_date = request.GET.get('start_date')
if start_date:
print(start_date)
return render(request, 'base.html')
# base.html
<form action="." method="GET">
<input type="text" name="start_date" placeholder="From" value="testing">
<input type="text" name="end_date" placeholder="To" value="testing">
<input type="submit" value="submit">
</form>
Related
Django form is saved but "result" field is showing empty in database.
Even after populating the filed from admin panel, it is saved but it still shows empty.
Models.py
class Result(models.Model):
class Choises(models.TextChoices):
POSITIVE = "POSITIVE", "Positive"
NEGATIVE = "NEGATIVE", "Negative"
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50, default=None)
result = models.CharField(max_length = 100, choices=Choises.choices, blank=False
)
resultDoc = models.ImageField(upload_to='testResults', height_field=None, width_field=None,)
def __str__(self):
return self.user.username
Forms.py
class resultForm(forms.ModelForm):
class Meta:
model = Result
fields = ['name', 'result', 'resultDoc']
views.py
def inputResult(request, pk):
user = User.objects.filter(id=pk).first()
profile = newProfile.objects.filter(user=user).first()
if profile == None:
profile = oldProfile.objects.filter(user=user).first()
rForm = resultForm(request.POST, request.FILES)
if request.method == 'POST':
rForm = resultForm(request.POST, request.FILES)
if rForm.is_valid():
order = rForm.save(commit=False)
order.user_id = pk
order.save()
return redirect('stored_records')
else:
rForm = resultForm()
context = {'user' : user, 'profile':profile, 'rForm': rForm}
return render(request, 'Testing booth End/input-result-customer-info.html', context)
input-result-customer-info.html
<form action="" method = "POST" enctype= "multipart/form-data">
{% csrf_token %}
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Uploaded By/Doctor Name">
</div>
<div class="mb-3">
<label for="result" class="form-label">Result</label>
<select class="form-select" id="result" name="result" class="form-control">
<option value="POSITIVE">Positive</option>
<option value="NEGATIVE">Negative</option>
</select>
</div>
<div class="mb-3">
<label>Upload Scan File</label>
<div class="upload d-flex justify-content-between">
<div class="file-placeholder">Upload Scan File</div>
<input type="file" class="form-control d-none" id="resultDoc" name="resultDoc" >
<label for="resultDoc" class="form-label cam-img"> <img src="{% static 'user/images/Camera.png' %}"> </label>
</div>
</div>
<button class="btn btn-primary w-50 ms-auto d-block h-100" type="submit">Upload</button>
</form>
enter image description here
I think that the reason this doesnt work is that you created a form (rForm) in the backend but then you don't use it in the frontend.
This is how you should render your form in the the frontend:
<form method="post">
{{ rForm.as_p }} # This is the easiest possible implementation
<button type="submit">Submit</button>
</form>
If you want to take control of how the form is rendered, then you have to make sure that the input fields are named in the way that your backend expects. You can do it entirely manually or semi-manually, but your field names have to be set correctly or nothing will work.
Example of typical approach, say in case you have several similar text inputs
{% for field in rForm %}
<label for="{{ field.auto_id }}">{{ field.name }}</label>
<input type="text" name="{{ field.html_name }}" id="{{ field.auto_id }}" />
{% endfor %}
Example of fully hands-on approach
<select class="form-select" id="{{ rForm.result.auto_id }}" name="{{ rForm.result.html_name }}" class="form-control">
<option value="POSITIVE">Positive</option>
<option value="NEGATIVE">Negative</option>
</select>
In order to make sure that the inputs are being parsed correctly, add a print statement in your view to print the POST request:
print("Post Request : ", request.POST)
From there you will be able to see if the result field is being picked up correctly or if it's being ignored. Usually when fields get ignored is because they are not named correctly or sometimes it's because they fail validation.
If the rest of the data is saved correctly and just result is being left out then it's almost for sure an issue with the field name because if the form failed validation it would have aborted the entire operation.
P.S. I just noticed that you select input has the class attribute declared twice
I am trying to achieve a load-up process in my system where the user will input the load amount and add it to a user's current load.
How can I get the amount entered in my view function?
Here's my function in my views.py
def LoadWallet(request, pk):
user = get_object_or_404(User, id=request.POST.get('user_id'))
user_wallet = user.wallet
if request.method == 'POST':
form = LoadForm(request.POST)
if form.is_valid():
user_wallet = user_wallet+form.instance.load_amount
User.objects.filter(id=pk).update(wallet=user_wallet)
return HttpResponseRedirect(reverse('user-details', args=[str(pk)]))
and the form in my template file
<form action="{% url 'load-wallet' user.pk %}" method="POST">
{% csrf_token %}
<label for="load_amount">Load amount</label>
<input type="text" class="form-control" id="load_amount" onkeyup="replaceNoneNumeric('load_amount')">
<button type="submit" name="user_id" value="{{ user.id }}" class="btn btn-md btn-success" style="float: right; margin: 10px 5px;">Load</button>
</form>
Right now I tried this but it's returning "name 'LoadForm' is not defined". Should I declare the LoadForm first?
Is there a better way to implement this? Thank you!
You might have an easier time using something like this, than LoadForm:
def LoadWallet(request, pk):
user = get_object_or_404(User, id=request.POST.get('user_id'))
user_wallet = user.wallet
if request.method == "POST":
user_id = request.POST["user_id"]
# Other logic here
return ...
And in template
<form class="load-wallet" action="" method="POST">
{% csrf_token %}
<input type="text" name="user_id" placeholder="What is the user id?">
<button type="submit" class="submit-btn"> Submit </button>
</form>
models.py
from django.db import models
class booking(models.Model):
fname=models.CharField( max_length=50)
lname=models.CharField( max_length=50)
email=models.EmailField(max_length=254)
city=models.CharField(max_length=50)
state=models.CharField(max_length=50)
pin=models.IntegerField()
def __str__(self):
return self.fname
class approved(models.Model):
fname=models.CharField( max_length=50)
lname=models.CharField( max_length=50)
email=models.EmailField(max_length=254)
city=models.CharField(max_length=50)
state=models.CharField(max_length=50)
pin=models.IntegerField()
def __str__(self):
return self.fname
views.py
def adminp(request):
if 'form_rejected' in request.POST and request.method=="POST":
print("Went into reject")
p=booking.objects.filter(id=request.POST.get('object_id','')).delete()
print(p)
elif 'form_approved' in request.POST and request.method=="POST":
print("went in approve")
fname= booking.objects.filter(fname=request.POST.get('object_fname','')).values_list('fname')
lname= booking.objects.filter(lname=request.POST.get('object_lname','')).values_list('lname')
email= booking.objects.filter(email=request.POST.get('object_email','')).values_list('email')
city= booking.objects.filter(city=request.POST.get('object_city','')).values_list('city')
state= booking.objects.filter(state=request.POST.get('object_state','')).values_list('state')
pin= booking.objects.filter(pin=request.POST.get('object_pin','')).values_list('pin')
app= approved(fname=fname,lname=lname,email=email,city=city,state=state,pin=pin)
app.save()
print(fname,pin)
x=booking.objects.all()
params={'pro': x}
return render(request,'dbms/adminpanel.html',params)
template
<form action="" method="POST">
{% csrf_token %}
<div class="col"><p>Firstname: {{i.fname}}</p></div>
<div class="col"><p>Lastname: {{i.lname}}</p></div>
<div class="col"><p>Email: {{i.email}}</p></div>
<div class="col"><p>City: {{i.city}}</p></div>
<div class="col"><p>Pin: {{i.pin}}</p></div>
<input type="hidden" name="object_fname" value="{{ i.fname }}">
<input type="hidden" name="object_lname" value="{{ i.lname }}">
<input type="hidden" name="object_email" value="{{ i.email }}">
<input type="hidden" name="object_city" value="{{ i.city }}">
<input type="hidden" name="object_state" value="{{ i.state }}">
<input type="hidden" name="object_pin" value="{{ i.pin }}">
<input class="btn btn-success mx-2" name="form_approved" type="submit" value="Approve">
<input type="hidden" name="object_id" value="{{ i.id }}">
<input class="btn btn-danger mx-2" name="form_rejected" type="submit" value="Reject"> <!--Added attribute name="form_rejected"-->
OUTPUT after printing output of fname and pin:
went in approve
<QuerySet [('snaTYE',)]> <QuerySet [(939393,)]>
when I print fname just to check it gives me a queryset which can't be inserted, so how do either insert the following in approved database or how do get only value in the queryset.
Use the value of the hidden field object_id to get the booking instance. You don't need the other hidden fields. As you discovered, booking.objects.filter() gives you a queryset. Use booking.objects.get() to get a single instance. Not that this raises an exception if no database entry matching your query exists. Then use the values from the booking instance to create the approved instance.
try:
booking_obj = booking.objects.get(id=request.POST.get('object_id')
approved_obj = approved.objects.create(
fname=booking_obj.fname,
lname=booking_obj.lname,
email=booking_obj.email,city=booking_obj.
city,
state=booking_obj.state,
pin=booking_obj.pin
)
except booking.DoesNotExist:
# handle error somehow
Two remarks:
check out the documentation on form handling it can make live much easier.
it is a common convention to capitalize model names (like all class names), e.g. class Booking. I'd suggest you stick to this convention, unless you have a good reason not to.
I am trying to implement a simple search function in django but somehow I can't pass the argument from my template to my view function. I've got a key error: KeyError at /artdb/search/ because kwargs is empty:
url.py:
path('search/',views.Search.as_view(),name='search'),
base,.html:
<form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" {{ form.as_p }} method="get">{% csrf_token %}
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{seastr}}">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="{{seastr}}">Search</button>
</form>
views.py:
class Search(ListView):
print("class Search")
model=Person
template_name='artdb/search.html'
context_object_name='ans'
def get_queryset(self):
Pdb().set_trace()
self.seastr=get_object_or_404(Person,name=self.kwargs['seastr'])
return Person.objects.filter(seastr=self.seastr)
You did not attach the name seastr to your <input> field:
<form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" {{ form.as_p }} method="get">{% csrf_token %}
<input name="seastr" class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{seastr}}">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
Notice the name="seastr" in the <input> tag.
GET parameters are not stored in self.kwargs, but in self.request.GET, so we can obtain the parameter with self.request.GET['seastr'].
Typically the page with the search bar, is the same as the one with the request, therefore the search request if frequently optional. So it might be useful to make filtering optional here:
class Search(ListView):
model=Person
template_name='artdb/search.html'
context_object_name='ans'
def get_queryset(self):
q = self.request.GET.get('seastr')
if q is not None:
return Person.objects.filter(seastr=q)
else:
return Person.objects.all()
Finally note that the seastr parameter is not part of the context data. You can make this part of the context data, by patching it:
class Search(ListView):
model=Person
template_name='artdb/search.html'
context_object_name='ans'
def get_queryset(self):
q = self.request.GET.get('seastr')
if q is not None:
return Person.objects.filter(seastr=q)
else:
return Person.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['seastr'] = self.request.GET.get('seastr')
return context
Hi i am Newbie in django i read django documentation but i had made a url with parameteres i want to book a car . for booking i need car id and driver id . after redirect to my booking page . my book now button is not sending the driver id and car id . please help me.
for example.
i am having a John as a Driver , and he click on Audi To book . after getting his url i want to save it to my booking database . after click on button in my html "book now" it doesnt render to next page book a car and dont get the car id and driver id.
please help me.
Sorry for my english . if didnt understand please let me know in comments ill more explain to you and share more content . i am just beginner in field so just learning .
Views
#csrf_protect
def rentacar_car(request, car_id,driver_id):
try:
args['car'] = Car.objects.get(id__exact=car_id)
args['driver_id'] = driver_id
except:
args['car'] = None
args['driver_id'] = None
if args['car'] is not None:
template = Template.objects.get(template_default__exact=1)
return render(request, template_page, args)
else:
return HttpResponseRedirect('/rentacar/list/')
def rentacar_booking(request):
template = Template.objects.get(template_default__exact=1)
template_page = template.template_alias + str("/rentacar/rentacar_booking_form.html")
menu_config_list = MenuItemRentacarList.objects.all()[0]
menu_config = MenuItemRentacarList.objects.get(id=menu_config_list.id)
args['main_menu'] = MenuMenu.objects.get(id__exact=template.template_main_menu_id)
args['menu_items'] = MenuItem.objects.filter(
menu_item_menu=args['main_menu'],
menu_item_published=1,
)
args['current_menu_item'] = menu_config.menu_item_rentacar_list_menu_item
all_modules = Module.objects.filter(
module_show_option__exact='all',
module_published=1
)
selected_modules = Module.objects.filter(
module_show_option__exact='selected',
module_published=1,
module_menu_item=args['current_menu_item']
)
excluded_modules = Module.objects.filter(
module_show_option__exact='except',
module_published=1,
).exclude(
module_menu_item=args['current_menu_item']
)
args['modules'] = list(chain(all_modules, selected_modules, excluded_modules))
try:
args['car'] = Car.objects.get(id__exact=request.POST.get('car_id'))
args['driver'] = Driver.objects.get(id__exact=request.POST.get('driver_id'))
except:
args['car'] = None
args['driver'] = None
if args['car'] is not None:
return render(request, template_page, args)
else:
return HttpResponseRedirect('/rentacar/list/')
else:
return HttpResponseRedirect('/')
Templates
rentacar_book_form
<div class="row">
<div class="medium-6 small-12 columns">
<label>
Book Start Date <br>
<input type="date" name="book_booking_start_date" required>
</label>
</div>
<div class="medium-6 small-12 columns">
<label>
Book End Date <br>
<input type="date" name="book_booking_end_date" required>
</label>
</div>
</div>
<hr>
<input type="submit" class='button large primary' value="Book {{ car.car_brand.brand_name }} {{ car.car_name }}">
</div>
</div>
<input type="text" name="book_booking_car_car" value="{{ car.id }}" class="hidden">
<input type="text" name="book_booking_driver_driver" value="{{ driver.id }}" class="hidden">
rentacar_car_car
<form action="/rentacar/book-a-car/" method="post">
{% csrf_token %}
<input name="car_id" type="text" value="{{ car.id }}" class="hidden" required>
<input name="driver_id" type = 'text' value="{{ driver.id }}" class = 'hidden' required>
<button type="submit" class="button primary uppercase centered full-width">
Book now!
</button>
</form>
urls.py
url(r'^rentacar/book-a-car/$', extension_views.rentacar_booking),
url(r'^rentacar/list/(\d+)/$', extension_views.rentacar_list),
url(r'^rentacar/car/(\d+)/driver/(\d+)/$', extension_views.rentacar_car),
If you just want to get the values from hidden inputs just do this.
In method rentacar_car type:
car_id = request.GET.get('car_id')
driver_id = request.GET.get('driver_id')
print(car_id)
print(driver_id)
And since you are getting the values from those inputs you have to change method of form to GET.