show dynamic data from form value change in template - python

I'm new to django, i'm used to angular. i'm trying to do something that make sense to me in angular and I can't achieve in django.
I'm working with python 3.9 and django 4.1
I simplified my case to this..
I have a form that I created and and a view for it, i have a select element, whenever i select something, i want to show what i selected.
so I created a LocationForm form class:
class LocationForm(forms.Form):
apartment_type = forms.ModelChoiceField(queryset=ApartmentType.objects.all())
apartment type is just a list of apartment types (building, apartment, garden and so on)
i past the form to the view:
def location(request):
context = {'form': LocationForm}
return render(request, 'prospects/location.html', context)
and the code for the view:
{% load static %}
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
CCC{{ form.apartment_type.value }}DDD<br/>
the problem is that no matter what I select, form.apartment_type.value still shows None, it's not being updated.
i guess i'm used to angular too much but this issue is really alarming for me if django only parses things statically, i guess i'm not used to it and i have no idea how to resolve it otherwise.
in my full code i want to reflect different type of items based of what chosen in the form but i can't do that if nothing gets updated.
any ideas how to resolve this?
any information regarding this issue would be greatly appreciated, i'm really lost here.
#update
it looks like i wasn't clear.
I want to understand the django template updates when variables are changed inside of it without refreshing the page.
only when i change the selection, without clicking save and sending the form i want to see the new value printed between CCC and DDD. currently i'm using {{ form.apartment_type.value }} but it stays None when i select an item.
if not.. how can i resolve this with django ?
i just said that i moved from angular and there it's like that out of the box and if here it's not, i hope there is a solution.

It seems that Django only compiles the pages when I render them first, if want to change anything in realtime I need to a javascript framework.
Found that at: https://stackoverflow.com/a/50189643/

Related

Editing the details view of a model in flask admin

Is there a way to edit the details view model in flask-admin? I have searched the very bad docs and I couldn't find a way with which I would be able to display the model's details in a customized way!
Is there any reference to how the "details_view" should be used, assuming this is how I modify the details view?
If not, can anyone please explain to me how can I modify the way the info is displayed in that list? I have a "list of tags" column, and I wanna show tags separately based on certain criteria, I wanna apply some filters for example before showing them. How would I do that?
custom detail view can be acheived by :
1) setting the template of the modelView you are trying to customize :
class MyModelView(AdminModelView):
details_template = "admin/details.html"
2) Edit your custom template admin/details.html by totally overiding it with a whole new page. I guess you want to add additional information or custom fields most of the time, so you can start with a admin/details.html page that looks like :
{% extends 'admin/model/details.html' %}
{% block tail %}
{{ super() }}
<h1>My custom content.</h1>
{% endblock %}
By inheriting from parent template, you should have environment variable available in the template.
You may find more about available override options and such there : http://flask-admin.readthedocs.io/en/latest/api/mod_model/#flask_admin.model.BaseModelView.details_template

Rendering Django Template Blocks in Specific Places on Page

I am trying to achieve something in Django Templating Language without knowing whether it is possible (without resorting to JS or something like that).
I have the following code (from Django-Oscar) which renders 3 blocks of promotions on the main page:
{# Render promotions #}
<div id="promotions">
{% for promotion in promotions_page %}
{% render_promotion promotion %}
{% endfor %}
</div>
These three blocks are Single Item, Products and New Arrivals. The code above appears in the layout.html which is essentially responsible for rendering the entire layout of the main page.
The problem is that as soon as soon as Django encounters this code, it renders all of the promotions there one after another. I, however, would like to chose where on the page I place them. What's more, I do not believe that I have much flexibility in how I render them, read - I do not want to change the Oscar e-commerce and rendering code unless absolutely necessary.
Since I have access to individual templates for Single Item, Products and New Arrivals promotions, I tried creating DTL blocks there and then calling those blocks at proper places on the layout.html. However, that does not work.
What is a proper and most efficient way of achieving what I am trying to do?
Django templating system provides features that let you add your custom templates in place of the ones that come with the apps. You don't need to patch django-oscar for this.
Start here: https://docs.djangoproject.com/fr/1.11/howto/overriding-templates/
Hope I added enlightenment.

change submit method in Django Rest Framework filter modal

I have an API built with django-rest-framework, and I'm looking to add filtering to it. I'm following the guide here:
http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend
I'm seeing two issues:
the generated form uses method="post". My API currently supports only GET requests, and applying the filter results in "405 method not allowed" error.
The generated form has no submit button, but the example screenshot does.
my module versions:
Django (1.8)
django-crispy-forms (1.6.0)
django-filter (0.12.0)
django-guardian (1.3.2)
django-mssql (1.7)
django-pyodbc (0.3.0)
django-rest-swagger (0.3.4)
djangorestframework (3.3.2)
I've dug into the templates and it appears theres no easy way to override the form creation. base.html template in rest framework has this at the end
{% if filter_form %}
{{ filter_form }}
{% endif %}
but its contained in the {% block body %}, so to override it with my own template i'd have to also include everything else in the body. This seems lie the wrong solution.
I've also searched through the documentation looking for a place to specify GET instead of POST, and haven't found any mention of this.
I don't want to change the API to handle filters through the POST method. Eventually API will be extended to support a real POST method for actually creating new resources, so applying a filter via POST now would just create other problems down the road.
Is there a way to change the submit method of the modal form? Or a good way to override it with my own modal template without duplicating the rest of the body block?
================
EDIT
I've managed to correct the above issues using some jQuery, but this feels rather hackish. If a better solution is out there I'd still be interested in it.
$(document).ready(function () {
// change filter submit method to GET instead of POST
var form = $('#filtersModal form');
form.attr('method', 'get');
// add a submit button to the filter modal dialog
var cancel = $('<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>');
var submit = $('<button type="submit" class="btn btn-primary">Apply</button>');
var footer = $('<div class="modal-footer"></div>');
footer.append(cancel);
footer.append(submit);
form.append(footer);
});
I guess this is a bit late reply.
Extend your filter class from
django_filters.rest_framework.FilterSet
instead of
django_filters.FilterSet
Solution described here

Django is it better to check user.is_authenticated in views.py or in template?

I have a homepage, which I want to display a login form when user is not logged in or display a list of items belong to that user if he/she already logged in.
So far I came up with 2 methods:
Check whether user is authenticated in views.py and render corresponding view (in my views.py):
if request.user.is_authenticated():
return render(request, 'items.html')
else
return render(request, 'login.html')
Check directly in template and generate corresponding HTML for each case (in my index.html):
{% if user.is_authenticated %}
HTML for my items list
{% else %}
HTML for my login form
{% endif %}
Question
So which method is better for handling this? Are those methods differ much in performance? Is there any standard that we should handling these in views.py or in template itself?
I don't think there is a big performance difference. What's most important is how much you should stick to MVC pattern.
A template is meant to just display some sort of data that the view provides. Any kind of logic like deciding what kind of data to show based on requester's state should always be implemented by the view. Thus, you should move your logic into view function for the cleanness of your design.
TL;DR
Logic should be in your python code, not your template as much as possible. Due to maintenance and future-proof reasons.
Elaborate
Code quality: you can test your business logic when it's in your python not when it's in templates. The former improve your code quality and your value as a developer ;
Future-proof: you don't know which technology your application is going to use in the future, so avoiding tech-mingling will help you when upgrading it (you will be able to upgrade at different pace).
Separation of concerns principles: do you want a code that is a spaghetti plate, where you can't refactor a thing without impacting ten others?
Code legacy: you don't know who is going to work on your code neither which code you're going to work on. Don't make it hard for them (it would probably be your future self) ;
Clean code: that express itself in a single dialect is always better that mixing languages ;
Knowledge scope: front-end is often the responsibility of people with low programming skills (HTML/CSS are declarative) and you don't want them to mess with your business logic.
It depends on your html. If you want to change only a little part of your code based on the condition, check inside a template:
{% if user.is_authenticated %}
<h3>Welcome</h3>
{% else %}
Login
{% endif %}
But if items.html and login.html are different and big templates, you should definitely do the login inside your view.

Django-Tables column templates with django permissions

So, I'm using Django-Tables to generate my project datatables, but now I'm facing a new problem.
I've got this Table Class to generate my Model datatables, using the DjangoTables app. Then I use the TemplateColumn to create a new column for base operations just like Edit, Copy, Delete... This stuff goes into the template that is loaded into the column of each row.
class ReservationTable(tables.Table):
operations = tables.TemplateColumn(template_name='base_table_operations_btn.html', verbose_name= _('Operations'))
So inside the template i've got this:
{% if perms.reservation.add_reservation %}
<span class="glyphicon glyphicon-paperclip"></span>
{% endif %}
So, using the django templates perms tags, is not working here but it does in to the normal django template.
Any tips on how can I handle those perms into this kind of template? I'm kinda losen.
Thanks in advance!
So, its not just like a "perfect answer" for this problem, but here is how I managed to solve this:
Instead of using in Template django permisions, I managed to setup the permissions in the route url config. Just by adding:
permission_required('permision_name',raise_exception=True)
Function in the url.py. So here comes the full url line:
url(r'^reservation/flight/add/$', permission_required('reservation.add_reservation',raise_exception=True)(FlightReservationCreate.as_view()), name='reservation-flight-create'),
This allow me to add perms to the View instead of filtering into the themplate view.
That's not a perfect solution, because its a different way to manage permissions, and the problem with the django-tables2 column template is still there.
By the way, the final result is the same for me, so its OK.

Categories

Resources