How to delete data from database inline using Symfony - html

I'm new with Symfony and I'm trying to delete some data from the database using an html table, something that looks like this but I don't know where to start:
Any help is appreciated :)

There are basically 3 choices, whether using symphony or not:
A link to a page (look at Symfony "routes") including the information which entry to delete.
A nice trick is to use the same page and add a query parameter.
This would look something like this in twig:
{% for row in table %}
delete
{% endfor %}
And in symfony:
if($request->get->has('delete'))
{
//delete it from the database
}
//the code that displays your table
This is the easiest way but has a few disadvantages. It is slow as the whole page has to be loaded again. The browsers back-button might not behave as the user might expect.
A html form doing basically the same as 1. but with post
{% for row in table %}
<form action="" method="POST">
<input type="hidden" name="delete" value="{{row.id}}">
<input type="submit" value="delete">
</form>
{% endfor %}
And in symfony use $request->request
Ajax triggered by an onclick event
A javascript deleterow function would send the id via ajax to a special symphony route that returns an JSONResponse and when successful delete the DOM Element with the row.
This is much more complicated and would need a lot more research on your part, but it is the modern way.

Related

Django Admin: How to use the button to move to the selected URL?

I am very new to Django and trying to make my first project. I find it difficult to use the buttons I created to move to the selected URL.
Let's say my app is called TestForms and my models are: Patients, General, PST and ERBT. I would like to create two buttons - 'Previous' and 'Next' - which will be used to go to previous/next forms respectively. I try to do so using admin templates in django.
NOTE: I know changing built-in templates are not a very good idea, I will create new html file to extend this templates before doing changes on the server. For now I am doing it locally on my computer.
In submit_line.html I created two new buttons and they are like so:
{% if show_save_and_go_to_next_form %}<input type="submit" value="{% translate 'Next' %}" class="default" name="_gotonextform">{% endif %}
{% if show_save_and_go_to_previous_form %}<input type="submit" value="{% translate 'Previous' %}" class="default" name="_gotopreviousform">{% endif %}
This gives me two good-looking buttons on the site.
But these are just saving the results (working like 'Save' button), but not redirecting me to the next form as I would like to. When I am adding a new patient (admin/TestForms/patient/add/), after clicking on 'Next' I would like the server to save this patient and redirect me to admin/TestForms/general/add/ to be able to fullfil the next form, then save the changes and move on to admin/TestForms/PST/add/and so on.
I know I have to add the anchor, but I tried multiple times with different approaches and nothing worked. When I try to use <a href ...>, the button disappears. Also it is difficult for me to figure out how to move from one form to another and to disable the 'Previous' button on the first form and the 'Next' button on the last form.
Any suggestions how to achieve it?
The redirect needs to be done in your view, not in the template.
def your_view(request, *args, **kwargs):
# your code ...
if request.POST.get('_gotonextform'):
return redirect('admin/TestForms/general/add/')
else:
# do whatever you like if any other button was clicked
pass

Create "static" HTML Pages For Each Product

I have 10k+ products that need their HTML Page and the stuff within is to be static (thus searchable). I am trying to find a way to do the following using django:
Loop over all the items.
Get the matching information.
Fill a model template.
Save such template with the information now static.
As much as I tried looking here on Stack Overflow and in the web, I did not find any instructions to do so.
Build a standard template that has variables for the products. Then on the backend you can search for the products you want and populate the template with their information. Something like this for a concept:
search.html
<form action="{% url 'your_url' %}" method="POST">
{% csrf_token %}
<input type=text name=input value="" />
<input type="submit" value="Submit">
product.html
<html>
<div>Hello {{name}}!</div>
</html>
models.py
class Names:
user_name = models.CharField(max_length=200)
def __str__(self):
return self.user_name
views.py
input = request.POST['input']
name = Names.objects.get(user_name=input)
return render_to_response('product.html', {'name': name})
This will allow your user to search something, pull up the record searched, and place it in the template.
You can use that system for any number of variables.

CSRF error django 1.8 i18n internationalization

Hi I have django internationalization working on my django site. That is if i browse ".../en/foo/bar" and ".../nb/foo/bar" they work fine. But i am trying to get a drop down menu to automatically change the language but i get csrf error.
base.html
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}"/>
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"
{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go"/>
</form>
I however have another form in the same html but I do not but {% csrf_token %} in it. I rather place#csrf_exempt` on the view that handles the form.
I dont know whether having both froms on on html is what is causing the problem.
So what id did was that i created my own set_language view just like in django.veiws.i18n and places the #csrf_exempt on it.
#csrf_exempt
def set_language(request):
"""
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
redirect to the page in the request (the 'next' parameter) without changing
any state.
"""
print 'I am in setlang'
next = request.POST.get('next', request.GET.get('next'))
if not is_safe_url(url=next, host=request.get_host()):
print 'not safe'
next = request.META.get('HTTP_REFERER')
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
lang_code = request.POST.get('language', None)
if lang_code and check_for_language(lang_code):
if hasattr(request, 'session'):
request.session[LANGUAGE_SESSION_KEY] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN)
return response
Though the CSRF validation error is solved the form has no effect when i change the language and submit. it just stays on the same page. it appears that if not is_safe_url(url=next, host=request.get_host()) is always true. I am not sure what i am doing wrong now
I just realised that my form sends a GET request to the view instead of a post so request.method is GET how and why is this so? The form data does not get to the view at all in this case but they submit when i leave the action attribute of the form blank. The the form submits to the view that called the page. Submitting to a specific view is not working as the request somehow becomes a get request
With first problem - csrf error, there is no simple solution (if you want csrf working, not bypassed) because we can't tell what is happening here - maybe some cookie-related issue.
But second problem is simple to solve. There is bug in django. In simple words, django won't translate url (change prefix in front of URL or translate whole URL) when user is changing language, so user will be redirected to old, not translated URL with old language prefix. That will cause to switch back to old language after redirection.
Solution to that problem is already submitted to django and will be available in django 1.9, but you can get code of that view from github and put it instead of your current language switching view.
Here is full commit for that fix, there is new function called translate_url in urlresolvers that is used in fixed view.

Preferred way to POST with params from a listing template in Django

I was looking for some input on the preferred way of making a post request from a list template in Django. The way I'm currently using doesn't quite seem right to me, even though it works.
Let's say I have a table of data from my model, SomeModel, which I'm outputting in a Django GCBV ListView.
class SomeModelList(ListView):
model = SomeModel
In my template I'm iterating over the list of models and outputting each row in a table with some of the data, and I want two buttons which make a POST to perform some operation on the current row's object.
I can write an entire form for each operation manually. Something like:
{% for object in object_list %}
{{ object.name }}</br>
<form method="POST" action="{{ url 'do_something' {{ object.pk }}"><input type="button" value="Do Something"/></form></br>
<form method="POST" action="{{ url 'do_something_else' {{ object.pk }}"><input type="button" value="Do Something Else"/></form></br>
{% endfor %}
It doesn't seem correct to be writing out these form tags like this.
Is this really the best way? Maybe I should have a single giant form around the whole list and use some properties of the button? Maybe I should be doing something with Django forms? Maybe something else entirely?
Thanks!

Django forloop not indexing correctly

I am populating a table from a python list passed through a django tag:
{% for alt in altList %}
<td align="center">
{{alt.1}}</br>
{{alt.2}}</br>
{{alt.3}}</br>
{{alt.4}}</br>
<input type="hidden" value={{alt.0}}/>
</td>
{% endfor %}
This works correctly, but the list is randomly generated in python and I need to maintain the same list if the user of my form makes an error. I included a hidden field that stores the current list. The trouble is that, when I have an error, it does not run the loop as I expect.
The working input list is shown as:
[(196, u'hydro', u'25', u'735', u'7'), (266, u'coal', u'140', u'0', u'63'), (372, u'hydro', u'260', u'990', u'63'), (383, u'solar', u'510', u'990', u'63')]
When I have a list from the previous post I would like to use, it is also shown as follows in the console:
[(196, u'hydro', u'25', u'735', u'7'), (266, u'coal', u'140', u'0', u'63'), (372, u'hydro', u'260', u'990', u'63'), (383, u'solar', u'510', u'990', u'63')]
It appears to have the same formatting, so I'm not sure what the issue could be; however, in the second case it parses very differently and gives me a long list that includes things like ''/' as elements.
You could save the list's random order in user's session or I think it's a better choice to shuffle in the client side through javascript.