Pass parameters defined “in the buttons”(template) to CRUD-view - python

I have a table, where I add in the last column of every row the buttons “delete” and “edit”. I do this with the url + parameters in the href in the template (see below). I wrote a function for every href + parameter and the scripts work.
<form method="post">
{% csrf_token %}
<input type="hidden" name="projekt_id" value="{{objekt.id}}" />
<a class="btn btn-outline-secondary btn-sm" href="{% url 'check:remove_project' objekt.id %}" role="button">delete</a>
<a class="btn btn-outline-secondary btn-sm" href="{% url 'check:edit_project' objekt.id %}" role="button">edit</a>
</form>
Since i need such tables very often I want to handle the entire functionality (view the data/edit/delete/create) in one single view (I already have this in one template). My idea/wish is to pass the name= and value= from inside the buttons to the view. There I can distinguish for the appropriate functions - by if-statements- between edit/delete/view/create…
How can the parameters be passed from the BUTTONS in template to the view? Where is the documentation?
I wonder if there is a more elegant way to solve this? (maybe a combination of class based views?)

You can access a button like any other field in the POST data.
<button type="submit" name="delete">Delete</button>
<button type="submit" name="edit"> /Edit</button>
if "edit" in request POST:
...
elif "delete" in request.POST:
...

Related

How handle a Tag field in JS together with Flask Form?

Intro: I can receive the values from input fields in Flask by
var = request.form['description']
and the following HTML:
<form method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="description">Beschreibung</label>
<textarea name="description" placeholder="Post description"
class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Question: Any idea how to handle a tag field, like e.g. Link , together with Flask Form? How to handle Flask Form and $.Ajax Post request simultaneously? Any hint would be highly appriciated. I did my research but found nothing online.
I found now an easy solution for me. Don´t know if it is very clean but what I did was basically create a hidden field and pass the var from JS to the hidden field inside <form so that i can grab it with request in Flask. I also did this the other way around, passing the variable from Flask to JS. In this way I can use the CSS,JS in the link above outside of <form, i.e. I can press Enter
HTML:
<!-- from JS to Flask -->
<input type="hidden" name="hidden_tags" id="hidden_tags" value="" />
<!-- from Flask to JS -->
<input type="hidden" name="hidden_tags2" id="hidden_tags2" value="{{ post['tags'] }}"/>
in JS:
tags = document.getElementById("hidden_tags2").value.split('/');
document.getElementById("hidden_tags").value = tags
in Flask:
request.form['hidden_tags']

Get Data from Bootstrap Modal via POST request

I need to get data from a bootstrap modal input. I'am using the following code :
#app.route('/rejets_modeles', methods=("POST","GET"))
def rejets_modeles():
{code}
if request.method == 'POST':
uname = request.form['uname']
print("----")
print(uname)
return render_template ('rejets_modeles.html', tables=[df.to_html(table_id = 'rejets_modeles')], titles=df.columns.values, header="true")
And here is my HTML code
<form action="POST">
<div class="modal-body-modifs">
<p>Gestion du rejet : </p>
<label><b>NOM</b></label>
<input type="text" name="uname"></br>
<label><b>PRENOM</b></label>
<input type="text" name="uprenom"></br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default" data-dismiss="modal"> OK</button>
</div>
</form>
I don't even have the ("---") printed, that means that my 'POST' request isnt' interpreted. How can I fix that ? Thank you
It has to be method instead of action
<form method="POST">
In action you can set url to which it has to send form data - ie.
<form method="POST" action="/rejets_modeles">
but if you want to send to the same url then you don't have to set it.
Solved. The problem was data-dismiss="modal" in my input tag. If you delete this the modal will close and the form will be sent via POST request.

Python/Django pass user input as keyword arguments?

I am trying to pass what ever the user inputs into the url as keyword arguments (even if its not a real entry). When I try to assign the input name as the keyword arguments it fails.
HTML:
<p class="search">
<form method="GET" action="{% url 'job' %}" class="sidebar-form">
<div class="ogsearchbar input-group">
<input class="searchbarz" type="text" name="user_input" id="user_input" placeholder="Enter Job Number" autocomplete="off" />
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</p>
Django:
def get_job(request):
if request.method == 'GET':
formvar = request.GET['user_input']
return HttpResponseRedirect('/jobs/' + formvar)
What you want doesn't make sense. The {{ }} signs denote a context variable which is passed into the template from the server, before the template is rendered. But you're trying to use a value which is only defined when the user actually types something into the rendered page itself.
You could probably do this with some Javascript, but there doesn't seem to be much point. Drop the parameter from the URL and let the form send it in the query params, which you can access in your view as request.GET.
I decided to just go with javascript since my django code was not working with a request method when refreshing the page.

Why am I getting 404 error in python , blueprint?

I defined a blueprint route like this:
#mod_patient_directory.route('/delete-patient/<string:doc_id>', methods = ['GET'])
def delete_record(self, doc_id):
mongo.db.patient.remove({'_id': doc_id})
return redirect(url_for('main-page'))
And on the form I called the method that is:
<form action="{{ url_for('patient_directory.delete_record',doc_id= doc_id )}}" method="post">
<input type="hidden" name="docId" id="docId" value="{{ patient_doc._id }}" />
<input type="hidden" name="action" id="action" value="delete" />
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-remove"></span>
</button>
</form>
Can anybody tell me why I'm getting a 404 error?
One problem is that you have methods = ['GET'] on the route, but method="post" on the form tag. You should not use GET for dangerous actions like deleting records, so you should change the methods accepted to ['POST'].
As #Makoto pointed out that will give you a 405 error, but you are getting a 404 error, so there must be another problem. You've posted how you're registering the blueprint, but where within your code are you doing that? One thing to be careful of with blueprints is that you need to register all of the routes before you register the blueprint.

django, normal post form is not sending file data to server,

I'm wondering why this is happening:
I'm sending file data with form in POST, but all the time it says:
Key 'file' not found in <QueryDict:
{
u'datum': [u'aaa'],
u'csrfmiddlewaretoken': [u'USAbRrgU92yj7KFpZHuxf9bWufgnwC4N'],
u'anzeige': [u' aaaa'],
u'titel': [u' aaa']
}
This is my html:
<form id="myform" action="/anzeige_save/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<textarea style="width: 450px" id="titel" name="titel"> </textarea>
<textarea name="anzeige" id="anzeige"
style="height: 180px; width: 450px"> </textarea>
<input type="text" id="datum" name="datum" >
<input type="file" id="file" name="file" size="40" maxlength="100000">
<input type="button" value="speichern"
onclick="javascript:submitform()" />
</form>
<script>
function submitform(){
document.forms["myform"].submit();
}
</script>
and part my view is this:
anzeige=Anzeige(titel=request.POST['titel'],
anzeige=end_anzeige,
date=datetime.datetime.now(),
datum=request.POST['datum'],
file=request.FILES['file'])
anzeige.save()
I'm actually submitting correctly, the form should also submit the file in QueryDict like other queries. Can someone help me to figure out what I'm missing here?
Thanks
Use a ModelForm instead of a form, unless you have a good reason not to.
Your HTML will display a blank form if the form doesn't validate, without mentioning the errors nor previously entered values, see customizing a form template for correct usage.
It is normal that request.POST['file'] does not exist, it's in request.FILES['file'], but it must be saved before it can be used in a model. If you use a ModelForm, it is automatic. Else, see handling uploaded files with a model.

Categories

Resources