I'm trying to make a view in Django, in where if the edit button is pressed on that page it is passed on to another view as a session.
def page(request,user_input):
entry = util.get_entry(user_input)
name = user_input.capitalize()
request.session['name'] = name
request.session['entry'] = entry
if request.GET.get("edit"): # **<- This is not working for some reason.**
request.session['edit'] = True
else:
request.session['edit'] = False
return render(request, "homepage/page.html", {
"entry":entry,
"title":name,
})
Here is my page.html file
{% block body %}
{% if entry %}
<h1>{{title}}</h1>
{{ entry }}
{% endif %}
<form action="{% url 'create' %}" name='edit'>
<input type="submit" value='edit' class="button">
</form>
{% endblock %}
This is the view where I want to use the session
def create(request):
change =request.session['edit']
if request.GET.get('submit'):
title = str(title).lower()
if change:
util.save_entry(title,content)
return HttpResponseRedirect('/index')
You can specify a key-value pair by making use of the <button> tag, so then the form should look like:
<form action="{% url 'create' %}">
<button name="submit" value="edit" type="submit" class="button">edit</button>
</form>
Related
I have a button in my template and I need to post the value of the button to my views. Unfortunately, my request.POST returns 'None'. How can I retrieve the information from my HTML template?
Thank you.
My template:
{% extends 'vocab/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form action="{% url 'card' %}" method="POST">
{% for document in documents %}
<button type ='submit' value="{{ document.file }}" class='btn btn-outline-info' >
{{document.file}} </button>
{% endfor %}
</form>
{% endblock content %}
My view:
def card_view(request):
if request.method == 'POST':
context = {'request.POST':request.POST}
return render(request, 'vocab/card.html', context)
add name as attribute in button. name is like Key in python dictionary while value is the value of the Key.
Therefore, by using name you can obtain the ```value``
context = {'request.POST' : request.POST['name']}
I am trying to create form using FilteredSelectMultiple widget. I managed to get it showing on my page, but faced difficulties receiving user input from it. For now, after I click submit button page just refresh and shows same form again instead of going to designated page. What I am doing wrong?
My code so far:
forms.py
class DrgSkaiciuokle(forms.Form):
drg_pasirinkimas = forms.ModelMultipleChoiceField(queryset=DRGkodas.objects.all(),
label="Pasirinkite atvejį sudarančius DRG",
widget=FilteredSelectMultiple("DRG kodai", is_stacked=False),
required=True)
class Media:
css = {
'all': ('/static/admin/css/widgets.css',),
}
js = ('/admin/jsi18n',)
#I have no idea if this part is right:
def clean_drg_pasirinkimas(self):
drg_pasirinkimas = self.cleaned_data['drg_pasirinkimas']
return drg_pasirinkimas
views.py
def DRG_skaiciuokle(request):
if request.method == 'POST':
form = DrgSkaiciuokle(request.POST)
pasirinkti_DRG = form.cleaned_data['drg_pasirinkimas']
context = {
'pasirinktiDRG': pasirinktiDRG,
}
#This page should be opened after submitting form instead of refresh
return render(request, 'DRGskaiciuokle_valid.html', context)
else:
form = DrgSkaiciuokle()
context = {
'form': form,
}
return render(request, 'DRGskaiciuokle.html', context)
my html file:
{% extends "base_generic.html" %}
{% block content %}
<div id='frame'>
<div id='sk_head'>
<h3>Kaštų konvertavimo skaičiuoklė</h3>
<h4>Pagal DRG metodiką</h4>
</div>
<form>
<div id='sk_body'>
<fieldset>
<legend>Įveskite duomenis</legend>
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.media }}
{{ form.as_table }}
<script type="text/javascript" src="{% url 'jsi18n' %}"></script>
</table>
<input type="submit" value="Skaičiuoti">
</form>
</fieldset>
</div>
</form>
</div>
{% endblock %}
You need to update your code as follow
Update html file.
There is a form inside a form. You need to remove the inner form and update the outer form as suggested below.
{% extends "base_generic.html" %}
{% block content %}
<div id='frame'>
<div id='sk_head'>
<h3>Kaštų konvertavimo skaičiuoklė</h3>
<h4>Pagal DRG metodiką</h4>
</div>
<form action="" method="post"> # <-----------------add action and method here
<div id='sk_body'>
<fieldset>
<legend>Įveskite duomenis</legend>
<form>
{% csrf_token %}
<table>
{{ form.media }}
{{ form.as_table }}
<script type="text/javascript" src="{% url 'jsi18n' %}"></script>
</table>
<input type="submit" value="Skaičiuoti">
</form>
</fieldset>
</div>
</form>
</div>
{% endblock %}
Inside views.py
Add form.is_valid() the method call to check whether the form is valid or not.
def DRG_skaiciuokle(request):
if request.method == 'POST':
form = DrgSkaiciuokle(request.POST)
if form.is_valid():
pasirinkti_DRG = form.cleaned_data['drg_pasirinkimas']
context = {
'pasirinktiDRG': pasirinktiDRG,
}
#This page should be opened after submitting form instead of refresh
return redirect('redirect_to_view') # <------------ redirect ot url on success
context = {
'form': form,
}
return render(request, 'DRGskaiciuokle.html', context)
else:
form = DrgSkaiciuokle()
context = {
'form': form,
}
return render(request, 'DRGskaiciuokle.html', context)
I think this would help. For clarification DM.
When I render the form in HTML, I use this view. the patient_id is used to denote what patient the check in is for and for name display and such.
def Checkin(request, patient_id):
patient = get_object_or_404(PatientInfo, pk=patient_id)
form = forms.PatientCheckinForm()
return render(request, 'patientRecords/checkin.html', {'patient': patient, 'form':form})
When I submit the patient form filled out as a POST method, I still need access to the patient_id. Currently this is the view that accepts the filled form:
def CheckinSubmit(request):
if request.method == 'POST':
form = forms.PatientCheckinForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.date_time_of_checkin = dt.now()
instance.patient = patient.patient_id
instance.save()
return redirect('patientRecords/index.html')
I want to set the instance.patient to the patient_id that was part of patient from the Checkin view. Is there a way to pass the patient data back along with the POST method or is there another way this can be done?
For reference, here is my template and I am using ModelForm not form.
{% block content %}
<div class="container">
<h1>Patient Checkin</h1>
<h2>{{patient.first_name}} {{patient.last_name}}</h2>
</div>
<div class="container">
<form action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
Thanks in advance!
You should be able to simply add a hidden input to your form to capture the patient ID:
{% block content %}
<div class="container">
<h1>Patient Checkin</h1>
<h2>{{patient.first_name}} {{patient.last_name}}</h2>
</div>
<div class="container">
<form action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form">
<input type="hidden" name="patient_id" value="{{patient.patient_id}}" />
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
(Note this assumes that the patient ID is accessible from the patient_id property of the patient object.)
Then, in your CheckinSubmit method, you can access this value via request.POST.get('patient_id')
Alternatively, it appears that your check in form loads with the patient ID in the URL. In your CheckinSubmit method, you should be able to access this URL through the request.META.HTTP_REFERER property. You could then parse the URL (e.g., using request.META.HTTP_REFERER.split('/')[len(request.META.HTTP_REFERER.split('/')) - 1] to pull out the patient ID.
Example
<form method="post" action = "{% url 'user_search_from_group' %}">
<div class="module-option clearfix">
<div class="input-append pull-left">
<input type="hidden" name="groupname" value="{{ gpname }}" />
{% csrf_token %}
<input type="text" class="span3" placeholder="Filter by name" id="username3" name="username3" required>
<button type="submit" class="btn" name="submit">
<i class="icon-search"></i>
</button>
</div>
</div>
</form>
Here a hidden field is used to pass a value along form.
def user_search_from_group(request):
if request.method == 'POST':
username3 = request.POST.get('username3')
gname = request.POST.get('groupname')
Using request we are use the value inside view
My apologies if the question is stupid, I am a newbie to this. I am creating a django web application. I have created a form inside it. When I submit the form, it says 'url' not found even though the same URL loads fine for the first time when opening the form. This is whats confusing me. Here is my code:
#forms.py
class Recipe_ruleForm(forms.ModelForm):
class Meta:
model = Recipe_rule
fields = ('content',)
#urls.py
url(r"^create_recipe_rule/(?P<recipe_pk>[0-9]+)/$",views.create_recipe_rule, name="create_recipe_rule"),
#views.py
def create_recipe_rule(request, recipe_pk):
form = Knowledgebase_ruleForm
selected_recipe = Recipe.objects.get(pk = recipe_pk)
if request.method == 'POST':
form = Recipe_ruleForm(request.POST)
if form.is_valid():
#current_user = request.user
data = form.cleaned_data
recipe_rule_data=Recipe_rule.objects.create(recipe=selected_recipe, content=data['content'])
recipe_rule_data.save()
recipe_rule = Recipe_rule.objects.get(pk = recipe_rule_data.pk)
recipe=selected_recipe
recipe = Recipe.objects.get(pk = recipe.pk)
return redirect('recipe_detail', pk=recipe.pk)
else:
messages.error(request, "Error")
return render(request, 'create_recipe_rule.html' , {'form': form})
Here is the error when I submit the form:
Page not found (404) Request Method: POST Request
URL: http://[ip_adress]:[port]/create_recipe_rule/
UPDATE:
Here is my template:
{% extends "account/base.html" %}
{% load i18n %}
{% load bootstrap %}
{% block body_class %}applications{% endblock %}
{% block head_title %}{% trans "Create recipe" %}{% endblock %}
{% block body %}
<form action="/create_recipe_rule/" method="post">
{% csrf_token %}
<div class="form-group">
<label for="{{ form.content.label }}">{{ form.content.label }}:</label>
<textarea type="{{ form.content.type }}" name="{{ form.content.name }}" max_length="500" class="form-control" id="{{ form.content.id }}"></textarea>
</div>
<input class="btn btn-default" type="submit" value="submit">
</form>
{% endblock %}
You have action="/create_recipe_rule/", which is missing the recipe id.
One option is to simply remove the action from the form, then your browser will submit the request to the current url.
<form method="post">
If you do want to include the form action, then first you need to update your view so that it includes the recipe id in the template context.
return render(request, 'create_recipe_rule.html' , {'form': form, recipe_id: recipe_id })
Then you can update the form action to include the recipe id.
action="/create_recipe_rule/{{ recipe_id }}"
It's good practice to use the {% url %} tag, so that you are not hardcoding urls in the template:
action="{% url 'create_recipe_rule' recipe_id %}"
I'm fairly new to Django, and am working on a project where I use forms to get a user to enter a stock symbol and then using urllib I pull the data from Yahoo and return it. However, I'm not sure how to do this.
Here is my forms.py:
class Search(forms.Form):
search = forms.CharField()
Here is my views.py:
def search(request):
context = RequestContext(request)
if request.method == 'POST':
search = Search(data=request.POST)
if search.is_valid():
success = True
subject = search.cleaned_data['search']
sourceCode = urllib2.urlopen("http://finance.yahoo.com/q/ks?s="+subject).read()
pbr = sourceCode.split('Price/Book (mrq):</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]
else:
print search.errors
else:
search = Search()
return render_to_response('ui/search.html', {"search":search}, context)
This is the form I use to get users input (it has some bootstrap styling):
<form class="navbar-form navbar-right" role="search" action="/search/" method="POST">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter stock symbol" name="search">
</div>
<button type="submit" value="Save" class="btn btn-primary">Submit</button>
</form>
And finally here is my search.html file where I'd like to display the data:
{% extends 'ui/base.html' %}
{% block title %} {{ search.search.value|upper }} {% endblock %}
{% block body_block %}
<div class="container">
<h2>{{ search.search.value|upper }}</h2>
<h2>{{ I'd like to display 'pbr' (as definied in my views.py) here }}</h2>
{% endif %}
</div>
{% endblock %}
What I's like to do is take the pbr from my views.py and display it in my templates. Anyone know if I can do this? Thanks.
Build a result dictionary in your view as:
result = {}
if search.is_valid():
success = True
subject = search.cleaned_data['search']
sourceCode = urllib2.urlopen("http://finance.yahoo.com/q/ks?s="+subject).read()
pbr = sourceCode.split('Price/Book (mrq):</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]
result['pbr'] = pbr
result['search'] = search
and return this result as:
return render_to_response('ui/search.html', {"result":result}, context)
In your template now you can access the pbr as:
<h2>{{ result.search.value|upper }}</h2>
<h2>{{ result.pbr }}</h2>