I want something like this in my Django .
enter image description here
Can anyone tell me how should I code in html template and views.py ?
If you want to change the boolean field value status on click, you need to use Jquery.
I created an app named toggle, so you need to replace it with your app's name and is_working with your status button.
here is the full code
urls.py::
from django.urls import path
from toggle.views import home, toggle
urlpatterns = [
path('', home),
path('toggle/', toggle),
]
views.py:
from django.shortcuts import render
def home(request):
w, created = Work_Experience.objects.get_or_create(id=1)
return render(request,'home.html', {'workexperiance': w})
from django.http import HttpResponse
from toggle.models import Work_Experience
def toggle(request):
w = Work_Experience.objects.get(id=request.POST['id'])
w.is_working = request.POST['isworking'] == 'true'
w.save()
return HttpResponse('success')
home.html:
<div style="display:inline-block">
<label>Currently working here?</label>
<label class="switch">
<input type="checkbox" id="checkbox" value="{{workexperiance.is_working}}">
<span class="slider round"></span>
</label>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script> <!-- Import Jquery Here-->
<script type="text/javascript">
$(document).ready(function() {
$('#checkbox').change(function() {
$.post("/toggle/", {
id: '{{workexperiance.id}}',
isworking: this.checked,
csrfmiddlewaretoken: '{{ csrf_token }}'
});
});
});
</script>
run: ./manage.py runserver and visit: http://localhost:8000
when you click the Currently working here? check box, will instantly change the boolean field value "is_working".
reference to originally answered question :
Originally answered link
Related
I want to add a clickable link to admin list_view for a specific app that will redirect me to a html file i created, I have created a view.py like this
from django.shortcuts import render
from . models import *
from django.contrib.auth.decorators import login_required
#login_required
def transaction_print(request, transaction_id):
transaction = Transaction.objects.get(id=transaction_id)
return render(request, 'report.html', {'transaction': transaction})
and my urls.py
from django.urls import path
from . import views
urlpatterns = [
# path('', views.transaction_print, name='transaction_print'),
path('transaction/<int:transaction_id>/', views.transaction_print, name='transaction_print'),
]
I created the report.html at (root_dir/calculator/templates/report.html)
Now im not sure how to make a method at models.py to return maybe my views as a link to be add to list_view, or what is the best approach to achieving that. Thanks!
I guess there is a mistake in your formulation.
From what you describe, you want to add a button on the change_view.
To do so, within your app template folder, create a file extended_changeform.html
in that file:
{% extends 'admin/change_form.html' %}
{% block object-tools-items %}
<li>My button label
</li>
{{ block.super }}
{% endblock %}
and in the admin class where you want to have the buttons:
class TransactionAdmin(ModelAdmin):
change_form_template = "extended_changeform.html"
I am learning Django from clever programmer and have run into an issue.
I am trying to **./manage.py runserver and I run into a type error issue as provided on the below link
i assume there seems to be a problem on the line: return render(request, 'movies/movies_stuff.html' , stuff_for_frontend)
TypeError - Screen Shot
views.py_
from django.shortcuts import render
from .models import movies
# Create your views here.
def Home_page(request):
user_query = str(request.GET.get('query' , ''))
search_result = movies.objects.filter(name__icontains=user_query)
stuff_for_frontend={'Search_result :', search_result}
return render(request, 'movies/movies_stuff.html' , stuff_for_frontend)
urls.py
from django.urls import include, path
from .views import Home_page
urlpatterns= [
path('', Home_page, name='Home _page')
]
Templates-->movies-->movies_stuff.html
<html>
<body>
<form action = "" name="search"
<input type= "text" name="query" value="{{request.GET.query}}"
<input type = "submit" value="Search" />
{%for movies in search_result%}
<p>{{movies.name}}</p>
{% endfor %}
</body>
</html>
The issue here is as it states, it's a type error. This is happening because the render method requires a dictionary and you are sending a set instead.Correct the following
stuff_for_frontend={'Search_result :', search_result} // this will become a set
to this
stuff_for_frontend={'Search_result' : search_result} // now a dictionary
The error occurs when try to access using keys on set. And in the template try to correct the form as I suspect it is incomplete.
Hope that helps! Happy coding!
I would like to have a page in my django application that has a button that search a product and after selecting quantities gets added to the page (without reloading) in a list where the total get calculated (something like that), I am a beginner in programing and I have a week reading and investigated how to do it but I don't found anything.
Is because you need other programming language? Or could you indicate me some documentation or some example that I can read. Mostly because for my inexperience I don't know how to identify the relevant information in the documentation or even what to look for.
This can be done using Ajax call,
check this example:
forms.py
class sampleForm(forms.Form):
input = forms.CharField()
views.py
from django.http import JsonResponse
def sampleview(request):
input = request.POST.get('input', None)
#perform your logic here
#let us say your data is in variable result
result = {'product1' : 'python' ,'product2' : 'django' , 'product3' : 'ajax' }
return JsonResponse(result)
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('sampleview',views.sampleview,name='sampleview'),
]
your HTML
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button id="sampleform-submit" type="submit">submit</button>
</form>
<div id="results"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$("#sampleform-submt").click(function(){
e.preventDefault();
var form = $('#id_input').closest("form")
//id_input is id of input tag generated by form and above line selects the form
$.ajax({
url : "{% url 'sampleview' %}",
type: "POST",
data : form.serialize(),
dataType: 'json',
success: function(data){
#data is 'result' you return in sampleview function
$("#results").append('<p> '+ data.product1 +'</p>');
$("#results").append('<p> '+ data.product2 +'</p>');
$("#results").append('<p> '+ data.product3 +'</p>');
}
});
}
</script>
I hope this helps
I've used reverse before and it's been fine. But now, I don't know why it's not working. It might be because I'm trying to reverse to a class based view and I've never done that before.
Here's my code -- where am I messing it up?
views.py:
class DocumentRequestDetail(NavMixin, TitleMixin, SelectedBrokerage, DetailView):
model = DocumentRequest
mod_nav = 'brokerage_nav.html'
context_object_name = 'doc'
subtitle = 'Document Request Details'
def MarkDocRequestComplete(request, bpk, pk):
d = DocumentRequest.objects.get(pk= pk)
d.is_complete = True
d.save()
return reverse('doc_request_detail', args=[bpk, pk]) #<--- the offending line
urls.py
from django.conf.urls import include, url
from django.views.generic.list import ListView
from brokerage.views import *
urlpatterns = [
url(r'^(?P<pk>[0-9]+)/detail/$', BrokerageDetail.as_view(), name="brokerage_detail"),
url(r'^(?P<pk>[0-9]+)/edit/$', BrokerageEdit.as_view(), name="brokerage_edit"),
url(r'^(?P<bpk>[0-9]+)/doc-request/all/$', DocumentRequestList.as_view(), name="doc_request_list"),
url(r'^(?P<bpk>[0-9]+)/doc-request/(?P<pk>[0-9]+)/$', DocumentRequestDetail.as_view(), name="doc_request_detail"),
url(r'^(?P<bpk>[0-9]+)/mark-doc-request-complete/(?P<pk>[0-9]+)/$', MarkDocRequestComplete, name="mark_doc_request_complete"),
]
HTML Link that calls MarkDocRequestComplete:
<a href="{% url 'brokerage:mark_doc_request_complete' brokerage.pk doc.pk %}" class='btn btn-lg btn-wide btn-success'>
<i class='ti-check'></i>
Mark Complete
</a>
Error When Clicking HTML Link:
Reverse for 'doc_request_detail' with arguments '(u'1', u'19')' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I don't get it... what am I doing wrong?
Edit I should say that, in the error, the 1 and 19 are the correct values for bpk and pk.
Edit 2 Added full URLs.py
The reason your url tag isn't working, is because you are namespacing it by adding brokerage: to it), when there is no namespace setup in your urls. See the documentation on how to properly setup namespaces.
The correct tag should be:
{% url 'mark_doc_request_complete' bpk=brokerage.pk pk=doc.pk %}
You have to change:
return reverse('doc_request_detail', args=[bpk, pk])
to
return reverse('doc_request_detail', kwargs={'bpk': bpk, 'pk': pk})
You must also change your template tag from:
<a href="{% url 'brokerage:mark_doc_request_complete' brokerage.pk doc.pk %}" class='btn btn-lg btn-wide btn-success'>
to:
<a href="{% url 'brokerage:mark_doc_request_complete' bpk=brokerage.pk pk=doc.pk %}" class='btn btn-lg btn-wide btn-success'>
The reason for these changes is because you have names in your regular expression groups.
Using django-tinymce I have successfully embedded TinyMCE in the Admin before. Embedding it in a front-end form does not seem to work for me however.
I have a form which is a modelForm. It doesn't add any extra fields ('comment' and 'statement' are the only fields used and they exist in the model). On the textarea field, 'comment', of that form I would like to use TinyMCE. I have tried the following:
class EntryForm(forms.ModelForm):
comment = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}, mce_attrs=TINYMCE_USER_CONFIG))
class Meta:
model = Entry
fields = ['statement','comment',]
and
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['statement','comment',]
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.fields['comment'].widget = TinyMCE(attrs={'cols': 80, 'rows': 15}, mce_attrs=TINYMCE_USER_CONFIG,)
and
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['statement','comment',]
class Media:
js = ('/media/tinymce/jscripts/tiny_mce/tiny_mce.js',
'/sitemedia/js/tinymce_setup.js',)
In the HEAD html tags I have put {{ form.media }} (the form is called form in the views and template). I am also using Grappelli and Filebrowser for the Admin.
Could someone please explain what I'm missing or the process of getting this to work?
Thanks very much!
To answer my own question:the last option works.
The problem was that `/sitemdia/js/tinymce_setup.js' was a Grappelli setup file. This should only be used by the Admin. I removed that bit so I ended up with:
class Media:
js = ('/media/tinymce/jscripts/tiny_mce/tiny_mce.js',
'',)
And in the header I added
<script type="text/javascript">
tinyMCE.init({
mode: "textareas",
theme: "simple"
});
</script>
You can also instead of removing the setup file insert another file that does work (with for example the tinyMCE.init bit of code in it).
That should do the trick :).
After a full day searching and trying I found it much easier to use a frontend version of tinyMCE on a Django App, delivered through TinyMCE's CDN
Content is saved with the HTML tags and can be displayed to the user with html tags.
I've tried to keep the solution as generic as possible, ie, the javascript should be moved and referenced. If the frontend wysiwyg will be used by more people than you, you should change the |safe in the index to a cleaning function to ensure security/prevent unwanted code hacks.
Being a frontend CDN to render TinyMCE doesn't 'require' backend installation, the viewspy and urls.py are included to show us providing the user with a view of what they enter.
Link to CDN
https://www.tinymce.com/download/
Index.html
{% load staticfiles %}
<!-- <link rel="stylesheet" type="text/css" href="{% static 'wys/style.css' %}" /> -->
<!DOCTYPE html>
<html>
<head>
<!-- Load TinyMCE from CDN -->
<script src="//cdn.tinymce.com/4/tinymce.js"></script>
<!-- Set preference of what should be visible on init -->
<script>tinymce.init({
selector: '#foo',
height: 200,
theme: 'modern',
plugins: [
'advlist autolink lists link image charmap print preview hr anchor pagebreak',
'searchreplace wordcount visualblocks visualchars code fullscreen',
'insertdatetime media nonbreaking save table contextmenu directionality',
'emoticons template paste textcolor colorpicker textpattern imagetools codesample toc'
],
toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
toolbar2: 'print preview media | forecolor backcolor emoticons | codesample',
image_advtab: true,
templates: [
{ title: 'Test template 1', content: 'Test 1' },
{ title: 'Test template 2', content: 'Test 2' }
],
content_css: [
'//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
'//www.tinymce.com/css/codepen.min.css'
]
});
</script>
</head>
<body>
<h1>This is the homepage</h1>
<h1>Below Are 2 Form Areas</h1>
<form method="GET">
Question: <input type="text" id="foo" name="search"><br/><br/><br/><br/><br/>
Name: <input type="text" id="bar" name="name"><br/><br/><br/><br/><br/><br/>
<input type="submit" value="Submit" />
</form><br/><br/>
<h3>Display of question</h3>
{% for question in questions %}
<p>{{ question.query|safe}}</p>
<p>{{ question.user_id|safe}}</p>
{% endfor %}
</body>
views.py
from django.shortcuts import render
from .models import Queries
def MainHomePage(request):
questions=None
if request.GET.get('search'):
search = request.GET.get('search')
questions = Queries.objects.filter(query__icontains=search)
name = request.GET.get('name')
query = Queries.objects.create(query=search, user_id=name)
query.save()
return render(request, 'wys/index.html',{
'questions': questions,
})
urls.py in the App
from django.conf.urls import url
from . import views
app_name = 'wys'
urlpatterns = [
url(r'^', views.MainHomePage, name='index'),
# url(r'^', views.MainHomePage, name='index'),
]