django delete model entry from selected form option - django

I have the following form displaying entries of a model for user settings. When selected, I would like that a button catches its pk and send it to a Delete view.Here is the current code but I am missing this part.
user_detail template html
<form id="SettingsListForm"><label>&nbsp Settings List : &nbsp &nbsp &nbsp</label>
{% if user.usersetting.first %}
<select class="form-control" name="settingslist" id = "settingslist" form="SettingsListForm" >
{% for settings in user.usersetting.all %}
<option value="{{ settings.file.url }}">{{ settings }}
</option>
{% endfor %}
</select>
{% else %}
<li class="list-group-item">NO SETTINGS YET</li>
{% endif %}
<button class="btn btn-outline-light btn-circle"><i class="glyphicon glyphicon-minus" href="{% url 'my_app:setting_delete' pk=user.usersetting.last.id %}"></i></button>
{% block delete_setting_confirm_block %}
{% endblock %}
</form>
setting_confirm_delete html template with delete_setting_confirm_block
{% extends 'login_app/user_detail.html' %}
{% block delete_setting_confirm_block %}
<h4>
ARE YOU <b>REALLY</b> SURE YOU WANT TO <b>DELETE</b> THIS SETTING ?
<form method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-outline-light btn-danger" value="Delete">YES</button>
<a class="btn btn-outline-light btn-default" href="{% url 'login_app:user_detail' pk=user.id %}"><b>NO</b></a>
</form>
</h4>
{% endblock %}
my_app urls
url(r'^setting/(?P<pk>\d+)/$',views.UserSettingDeleteView.as_view(),name='setting_delete'),
UserSettingDeleteView in my_app views
class UserSettingDeleteView(DeleteView):
model = models.UserSetting
template_name = 'my_app/setting_confirm_delete.html'
def get_success_url(self):
return reverse('my_app:user_detail', kwargs={'pk': self.object.user.pk})
Somehow, a similar technique works fine when using listgroups:
working sample in user_detail html
<ul class="list-group">
{% if user.userdata.first %}
{% for data in user.userdata.all %}
<li class="list-group-item">{{ data }}<a class="btn btn-outline-light btn-circle" href="{% url 'my_app:data_delete' pk=data.pk %}"><i class="glyphicon glyphicon-remove"></i></a></i></li>
{% endfor %}
{% block delete_data_confirm_block %}
{% endblock %}
{% else %}
<li class="list-group-item">NOTHING RECORDED YET</li>
{% endif %}
</ul>

In your template.html, you should create a form for deletion, like this:
<form action="{% url 'my_app:setting_delete' pk=user.usersetting.last.id %}" method="post">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-outline-light btn-circle">
</form>
Because in HTML you can not send directly PUT or DELETE, you should fake it via a POST request. It will be useful to read this, it is explained well.
Your UserSettingDeleteView can be as simple as that:
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy
class UserSettingDeleteView(DeleteView):
model = MyModel
# Replace with the model you want to delete (User)
success_url = reverse_lazy('my_app:setting_list')
# After deletion, possibly you will want to redirect the user to the list view
The built-in DeleteView cares itself to find your model by the pk parameter you pass through your url and delete it, you just have to configure the model and success_url fields.
Now if you click on your Delete button, you should expect your desired entry to be deleted and the user to be redirected to the list view.
EDIT:
I forgot that you want to get this entry via options. Here you will have to use some JavaScript in order to find the currently selected element and send it's pk to your DeleteView.
At first, add id's to your option tags, like this:
<select class="form-control" name="settingslist" id="settingslist" form="SettingsListForm">
{% for settings in user.usersetting.all %}
<option value="{{ settings.file.url }}" id="{{ settings.id }}">{{ settings }}</option>
{% endfor %}
</select>
And then add some jQuery:
var settingId = $('#SettingsListName').find(":selected").attr('id');
In the end, you need to send settingId to the corresponding url, but I am not very familiar with JavaScript.

Try putting a hidden input in your form. Right now, nothing is passing through the form.
<input type="hidden" name="del_setting" value="{{user.usersetting.last.id}}">
So your form would look like this
<form method="POST">
{% csrf_token %}
<input type="hidden" name="del_setting" value="{{user.usersetting.last.id}}">
<button type="submit" class="btn btn-outline-light btn-danger" value="Delete">YES</button>
<a class="btn btn-outline-light btn-default" href="{% url 'login_app:user_detail' pk=user.id %}"><b>NO</b></a>
</form>
You also probably should move this out of the current form in your user detail template so that you're not putting a form within a form:
{% block delete_setting_confirm_block %}
{% endblock %}

None of the previously mentioned solutions would work so I guess the problem is the nested bootstrap select item which is supposed to display the pk of the setting.
For simplicity I then removed the problem by using list-group instead
<ul class="list-group">
{% if user.usersetting.first %}
{% for settings in user.usersetting.all %}
<li class="list-group-item">{{ settings }}<a class="btn btn-outline-light btn-circle" href="{% url 'my_app:setting_delete' pk=settings.pk %}"><i class="glyphicon glyphicon-remove"></i></a></li>
{% endfor %}
<label>Create a new setting...</label>
<a class="btn btn-outline-light btn-circle"><i class="glyphicon glyphicon-plus"></i></a>
{% else %}
<li class="list-group-item">Create a new setting...<a class="btn btn-outline-light btn-circle"><i class="glyphicon glyphicon-plus"></i></a></li>
{% endif %}
{% block delete_setting_confirm_block %}
{% endblock %}
</ul>
As a workaround,this works well.

Related

Customized django all-auth form not submitting

I am using the django all-auth login form. I wanted to customize the look of the form fields so I changed login.html within the account folder to look like this:
<form class="login" method="POST" action="{% url 'account_login' %}">
{% csrf_token %}
{% for field in form.visible_fields|slice:'2' %}
<div class="row form-group">
{% if field.name == 'login' %}
<input type="text" placeholder="Email"><i class="fas fa-at"></i>
{% else %}
<input type="password" placeholder="Password"><i class="la la-lock"></i>
{% endif %}
</div>
{% endfor %}
Forgot Password?
<button type="submit">Sign In</button>
</form>
The form renders exactly how I would like it to, however nothing happens when I click on submit. What is strange to me is that the form submits perfectly fine if in place of my for loop I simply type {{ form.as_p }}, it just doesn't look how I want. Can anyone see an error in my loop, or is there something else wrong here. I have been looking for a solution online but so far been unsuccessful
You need to specify the names of the fields in your input tags otherwise the POST dictionary will be empty. You are using {% if field.name == 'login' %} but you forgot to specify the name attribute. Same applies for the password input.
<form class="login" method="POST" action="{% url 'account_login' %}">
{% csrf_token %}
{% for field in form.visible_fields|slice:'2' %}
<div class="row form-group">
{% if field.name == 'login' %}
<input name='login' type="text" placeholder="Email"><i class="fas fa-at"></i>
{% else %}
<input name='password' type="password" placeholder="Password"><i class="la la-lock"></i>
{% endif %}
</div>
{% endfor %}
Forgot Password?
<button type="submit">Sign In</button>
</form>

Django login not showing errors

I know there are multiple questions like this around, but none of them contain a clear answer. I am using the default authentication from Django, but have trouble displaying something like 'Your username/password combination is incorrect'. Is it possible to fix this without making a custom view function?
My urls.py looks like this:
url(r'^login/$', auth_views.login, {'template_name': 'login.html'},
name='mysite_login')
Then my login.html has the following code:
{% block content %}
<section class="content">
<div class="container block">
<div class="row">
<div class="col-md-12"></div>
<form action="{% url 'mysite_login' %}" class="form-control" method="post" accept-charset="utf-8">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field|addcss:'form-control' }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text|safe }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit" class="btn btn-dark">Login</button>
<input class="form-control" type="hidden" name="next" value="{{ next }}"><br>
</form>
</div>
</div>
</div>
</section>
{% endblock %}
So this all works, except for displaying the error messages. I've seen answers where you can write a custom view function and form to fix this, but I assume it should be also possible while using the build-in login functionality right? Thanks a lot.
The built-in login form doesn't display errors at an individual field level; it's a security risk to say that just the password is wrong, because it confirms the existence of a particular username. So the errors are raised in the general clean() method and are displayed in the template via {{ form.non_field_errors }}.

django form wizard, does not go to second step

I am trying to perform the following using Django :
Wizard containing two formds
First form is a simple form containing some Ajax to compute automatically some fields
Second form is a user registration
The problem is the following :
The first form is displayed correctly and the Ajax within the page is working fine
The second form is never displayed after pushing on the button "submit"
The code is as follows :
urls.py
from forms import InsertPropertyForm1, InsertPropertyForm2
from views import InsertPropertyWizard
urlpatterns = patterns('',
url(r'^addProperty/$', InsertPropertyWizard.as_view([InsertPropertyForm1, InsertPropertyForm2]), name='addProperty'),
)
views.py
FORMS = [("property", InsertPropertyForm1),
("test", InsertPropertyForm2)
]
TEMPLATES = {'0': 'realEstate/addProperty.html',
'1' : 'realEstate/test.html',
}
class InsertPropertyWizard(SessionWizardView):
def get_template_names(self):
print ("next step !!!!! " + str(self.steps.current))
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
print "Wizard done"
#do_something_with_the_form_data(form_list)
return HttpResponseRedirect('http://TO_FILL_IN')
realEstate/addProperty.html
{% extends 'realEstate/base.html' %}
{% load socialaccount %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<h1> Insert an ad </h1>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form class="form-horizontal" role="form" action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
</table>
{{ form.non_field_errors }}
<fieldset>
<legend>Localisation</legend>
<div class="form-group">
{{ form.country.errors }}
<label class="col-lg-1" for="id_country">{{form.country.label}}</label>
<div class="col-lg-1">
{{ form.country }}
</div>
</div>
</fieldset>
</fieldset>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}
</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}
</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
{% endblock %}
Just thought it could help someone.
Problem was that one of the field was not defined in the form and I forgot to include it in the template.
The behaviour of the wizard was correct. It got stuc on the first page but did not display the error on the screen as the field was not displayed.
Got me crazy but it was my fault.
Cheers

Django is not loading template form

I don't know why is not loading the template but every time I click in an url the page auto-reload and not load the template, here is my code:
urls.py
url(r'^pedidos/add',forms.PedidoCreateView.as_view(), name="pedido_add")
forms.py
class PedidoCreateView(CreateView):
template_name = 'ventas/form_pedido.html'
model = Pedido
form_class = PedidoModelForm
success_url = 'ventas/pedidos.html'
def form_valid(self, form):
form.save(commit=True)
return super(PedidoCreateView, self).form_valid(form)
form_pedido.html
{% extends '_layouts/base.html' %}
{% load url from future %}
{% block breadcrumb%}
<li>
Pedidos
<span class="divider">
<i class="icon-angle-right"></i>
</span>
</li>
<li class="active">Nuevo Pedido</li>
{% endblock %}
{% block page_content %}
<form class ="form" id="form" method="POST" action="{{ request.path }}">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Editar Empleado</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form_errors }}
{{form.as_p}}
</div>
<div class="modal-footer">
Cerrar
<input type="submit" class="guardar btn btn-primary" value="Guardar">
</div>
</form>
{% endblock %}
{% block scripts %}
{% endblock %}
link
<a href="{% url 'ventas:pedido_add' %}" class="btn btn-app btn-success">
For sure has to be some error that I'm not able to see now, I prove with other similar views and I don't have any problems, what could it be?

django-cms-search not displaying any results

Hey I have been plugging away trying to get haystack working with whoosh to implement a search backend for a django cms project i have been working on. After figuring out some really weird permissions errors i can almost taste sucess.
I now have haystack creating the indexes correctly and it will even display results for a custom app i have created an index for however i cannot get it to display any results for the cms page stuff. There are results being returned as im not getting the "No Results" message but nothing is being printed out in the results.html template.
bearing in mind that im letting django-cms-search handle the indexing for the cms app i didnt think i would need to add anything extra to get the results to display.
So to outline what i have so far
Haystack installed with a Whoosh backend
my setting.py setting are
HAYSTACK_SITECONF = 'lactoseintolerant.lactose_search.search_sites'
HAYSTACK_SEARCH_ENGINE = 'whoosh'
HAYSTACK_WHOOSH_PATH = '/home/mike/sites/lactosetoloerant/lactoseintolerant/whoosh'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 50
my search_sites.ph file looks like
import haystack
from cms.models import monkeypatch_reverse
from cms.plugin_pool import plugin_pool
monkeypatch_reverse()
haystack.autodiscover()
i have a custom index for my Topics Model that looks like so (This is working and resturning Reuslts)
from topics.models import Topic
from haystack.indexes import *
from haystack import site
class TopicIndex(SearchIndex):
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""
This is used when the entire index for model is updated, and should only include
public entries
"""
return Topic.objects.filter(active=True)
site.register(Topic, TopicIndex)
My results.html template look like
{% extends "base.html" %}
{% load cache cms_tags menu_tags %}
{% block base_content %}
<div id="panel-left">
{% block nav %}
<ul id="nav-left">
{% show_menu 1 100 100 100 %}
</ul> <!-- #nav-left -->
{% endblock %}
{% block panel_left %}
{% endblock %}
</div>
{% block panel_right %}
<div id="panel-main">
{% ifequal q '' %}
<h1 id="page-head-2">Search Results Page</h1>
<p>Please provide search criteria or keywords</p>
<br />
<form action=".">
<p>
<input type="text" name="q" value="{{ q }}">
<input type="submit" name="search" value="Search">
</p>
</form>
{% else %}
<h1 id="page-head-2">Search Results - page {{ request.GET.page|default:1 }} of {{ paginator.num_pages }}</h1>
<h1 id="page-head-2">Found {{ paginator.count }} for <span id="searchString">'{{ q }}'</span></h1>
<form action=".">
<p>
<input type="text" name="q" value="{{ q }}">
<input type="submit" name="search" value="Search">
</p>
</form>
<ul id="searchResults">
{% for item in current_page.object_list %}
<li class="searchResult">
<h2 class="searchTitle">{{ forloop.counter }}. {{ item.get_title }}</h2>
<a class="searchLink" href="{{ item.get_absolute_url }}">{{ item.get_absolute_url }}</a>
</li> <!-- .searchResult -->
{% endfor %}
</ul>
{% if paginator.num_pages > 1 %}
<div id="pagination">
{% for page_range_item in paginator.page_range %}
{% if not request.GET.page and page_range_item == 1 or request.GET.page == page_range_item|safe %}
<span class="pag-link current" href="/topics/?page={{ page_range_item }}">{{ page_range_item }}</span>
{% else %}
<a class="pag-link" href="/search/?q={{ q }}&page={{ page_range_item }}">{{ page_range_item }}</a>
{% endif %}
{% endfor %}
</div>
{% endif %}
{% endifequal %}
</div>
{% endblock %}
{% endblock %}
Im clearly missing something obvious here any help would be grealt appreciated!!
Cheers
i think you got it almost, try to change {{ item.get_absolute_url }} to {{ item.object.get_absolute_url }} inn your results.html file.