i am trying to implement a jsignature plug in to my django appplication via django-jsignature3 , however it seems that i am unable to get it to save to my database.
here is my code:
models.py
class JSignatureModel(JSignatureFieldsMixin):
name = models.CharField(max_length=20)
views.py
def my_view(request):
form = SignatureForm(request.POST or None)
print('in view')
if form.is_valid():
signature = form.cleaned_data.get('signature')
print('form is valid')
if signature:
# as an image
print('found sig')
signature_picture = draw_signature(signature)
# or as a file
signature_file_path = draw_signature(signature, as_file=True)
return render(request, 'cash/jsig.html', {'form': form })
jsig.html
{% extends 'base.html' %}
{% load static %}
{%load crispy_forms_tags%}
{% block content %}
<body>
{{ form.media }}
<form action="." method="POST">
{% for field in form %}
{{ field.label_tag }}
{{ field }}
<span style="color:red">{{ field.errors }}</span>
{% endfor %}
<input type="submit" value="Save"/>
{% csrf_token %}
</form>
</body>
{%endblock content%}
url.py
path('jsig/', views.my_view , name='jsig')
forms.py (this is really iffy to me , i don't understand the documentation , there is no place that my model was called , hence i did this my self but it does not work)
class SignatureForm(forms.Form):
signature = JSignatureField()
class Meta:
model = JSignatureModel
fields = ['name','signature']
exclude = []
here is my console
[04/Apr/2020 01:14:43] "GET /jsig/ HTTP/1.1" 200 5593
in view
form is valid
found sig
[04/Apr/2020 01:14:46] "POST /jsig/ HTTP/1.1" 200 5959
Please help , im really confused!
Related
I am currently struggling with Django forms. Based on the tickets model I generate this formset where users can choose the qty of tickets they want. After they will be redirected to the checkout page.
My problem is, when I use {{ form.ticket }} I get a select field but that's not what I'm looking for. I just want to print out the tickets as seen in the screenshot below.
Can anyone help me on that?
How it should be:
How it currently looks like:
views.py
from django.forms import formset_factory
from django.shortcuts import redirect, render
from .forms import EntryModelForm
from .models import Ticket
from orders.models import Order, Entry
# Create your views here.
def choose_ticket_and_quantity(request):
tickets = []
for ticket in Ticket.objects.all():
tickets.append({'ticket': ticket})
EntryFormSet = formset_factory(EntryModelForm, extra=0)
formset = EntryFormSet(initial=tickets)
if request.POST:
o = Order.objects.create()
request.session['order_id'] = o.order_id
formset = EntryFormSet(request.POST, initial=tickets)
if formset.is_valid():
for form in formset:
if form.cleaned_data['quantity'] > 0:
entry = form.save(commit=False)
entry.order = o
entry.save()
return redirect('http://127.0.0.1:8000/checkout')
return render(request, "tickets/choose_ticket_and_quantity.html", {'formset': formset})
forms.py
from django import forms
from orders.models import Entry
class EntryModelForm(forms.ModelForm):
class Meta:
model=Entry
fields = ['ticket', 'quantity']
choose_ticket_and_quantity.html
<form method="post" action="">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<ul>
<li>{{ form.ticket }}</li>
<li>{{ form.quantity }}</li>
</ul>
{% endfor %}
<p><input type="submit" value="Checkout"></p>
</form>
What I also tried was this here, but unfortunately, this didn't work either as my form couldn't be validated anymore and all ticket types have been printed together:
{% for choice in form.ticket.field.choices %}
{{choice.1}}
{% endfor %}
Try this
Add a templatetag get_ticket.py in app/templatetags (Add a __init__.py too)
from django import template
register = template.Library()
# import Ticket model
#register.simple_tag
def get_ticket(pk):
ticket = Ticket.objects.get(pk=int(pk))
return ticket.name # is it name?
In your template
{% load get_ticket %}
<form method="post" action="">
{% csrf_token %}
{{ formset.management_form }}
<ul>
{% for form in formset %}
<li>
<strong>{% get_ticket form.ticket.value %}</strong><br>
<input type="hidden" name='{{form.ticket.name}}' value='{{form.ticket.value}}'>
{{ form.quantity }}
</li>
{% endfor %}
</ul>
<p><input type="submit" value="Checkout"></p>
</form>
Looks like you want to display the value of the field:
<li>{{ form.ticket.value }}</li>
I'm kind of puzzled with this task:
I have 2 tables: User, Codes
I want to generate randomly codes in a specific pattern.
I've already written that part as a function, but it's hard to implement the function
in the ModelAdmin.
So I would be very pleased if someone knows a trick to accomplish this.
It would be enough to have a button in the User form to envoke the function, which then creates these codes.
But how do I implement such a button?
Is there a way to to this?
EDIT: typo
SOLUTION:
Since I want to generate vouchers for a particular user I can edit the admin.py like this:
class MyUserAdmin(UserAdmin):
def vouchers(self, obj):
return "<a href='%s'>Generate vouchers</a>" % reverse(gen_voucher_view, kwargs={'user':obj.pk,})
vouchers.allow_tags = True
list_display = (..., 'vouchers')
which represents a clickable link in the admin view of my User model.
Now I connect the link to my view in urls.py by adding
url(r'admin/gen_vouchers/(?P<user>\w+)/$', gen_voucher_view, name='gen_voucher_view')
to urlpatterns.
For creating the vouchers I provide a form in forms.py
class VoucherGeneratorForm(forms.Form):
user = forms.CharField(User, required=True, widget=forms.HiddenInput())
amount = forms.IntegerField(min_value=0, max_value=500, required=True)
readonly = ('user', )
In views.py I'm adding my view function:
#login_required
def gen_voucher_view(request, user):
if request.method == 'POST': # If the form has been submitted...
form = VoucherGeneratorForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# GENERATE vouchers here by using form.cleaned_data['amount']
# and user (generate_vouchers is a self defined function)
vouchers = generate_vouchers(user, form.cleaned_data['amount']
# set error or info message
if len(vouchers) == form.cleaned_data['amount']:
messages.info(request, "Successfully generated %d voucher codes for %s" % (form.cleaned_data['amount'], user))
else:
messages.error(request, "Something went wrong")
u = User.objects.get(pk=user)
form = VoucherGeneratorForm(initial={'user':user}) # An unbound form
return render_to_response('admin/codes.html', {'request': request, 'user':user, 'form':form, 'userobj': u}, context_instance=RequestContext(request))
else:
form = VoucherGeneratorForm(initial={'user':user}) # An unbound form
Last but not least create a template admin/codes.html where my form is displayed:
{% extends "admin/base_site.html" %}
{% load i18n admin_static static %}
{% block breadcrumbs %}
<div class="breadcrumbs">
{% trans 'Home' %}
›
{% trans 'Users' %}
›
{% trans 'Vouchercodes' %}
›
Voucher Generator
</div>
{% endblock %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}" />{% endblock %}
{% block content %}
<div id="content-main">
{% if request.user.is_active and request.user.is_staff or userobj and userobj.is_active and userobj.is_staff %}
<h1 id="generator_title">Generate vouchers for {{user}}</h1>
<form id="formular_generator" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<table>{{ form }}</table>
<button id="generatebutton" type="submit" name="action" value="generate">Generate</input>
</form>
{% else %}
<p>{% trans "You don't have permission to access this site." %}</p>
</div>
{% endif %}
{% endblock %}
{% block sidebar %}
{% endblock %}
Done!
To export them in a pdf I used admin actions, as propsed by Sumeet Dhariwal below.
U mean that you need to run a script from within the admin ?
If so check out django-admin-tools
http://django-admin-tools.readthedocs.org/en/latest/dashboard.html
SOLUTION FOUND:
no that was not what i meant, because I want to generate vouchers for 1 particular user and not for more, but that's a good remark.
I use Django Endless Paginator plugin.
I try to change the value of ENDLESS_PAGINATION_PER_PAGE from template side.
As default is 10.
I want to realize some dropbox where the user can change between (Example: 10,20,50,100 Objects).
Thanks for answer, but something not work property.
1. I have view.py
def adv_search(request):
objects = None
if request.GET.get('key'):
form = AdvancedSearchForm(request.GET)
if form.is_valid():
repo = Repository()
objects = list(repo.find_objects('*'+form.cleaned_data['key'] +'*', type=FileObject, chunksize=20))
return render(request, 'templates/adv_search.html', {'form': form, 'objects': objects })
return render(request, 'templates/adv_search.html', {'form': AdvancedSearchForm(), 'objects': objects})
2. Then forms.py
class AdvancedSearchForm(forms.Form):
key = forms.CharField(max_length=500, label="", widget= forms.TextInput(attrs={'class': 'label'}))
show_props = forms.MultipleChoiceField(choices = (("pid", "pid"),("title", "title"),("type","type"),("source","source"),("date","date"),("publisher","publisher"),("subject","subject"),("label","label"),("cDate","cDate"),("mDate","mDate")),required=False, widget=forms.CheckboxSelectMultiple(attrs={'class': 'my-class'}))
paginator = forms.ChoiceField(choices =(('10', '10'),('20','20'), ('50','50'), ('100','100')) ,required=False, )
3. adv_search.html
{% paginate paginator objects %}
{% for obj in objects %}
...
<div class="paginator">
{% get_pages %}
{{ pages.first_as_arrow }}
{% show_pages %}
{{ pages.last_as_arrow }}
<form method="get">
{{ form.paginator }}
<input type="submit" Value="Go">
</form>
{{ pages.total_count }} total objects
</div>
Everything works except select
Thanks Andrey
You can have a form which will set pagination per page and then use that submitted value in template. Here is an example:
View
from django.shortcuts import render
from .models import Entry
def endless_view(request):
pagination_per_page = request.GET.get('per_page', 10)
entries = Entry.objects.all()
return render(request, 'some_template.html', {'pagination_per_page':
pagination_per_page, 'entries': entries})
Template
{% extends 'base.html' %}
{% load endless %}
{% block content %}
{# #}
<form action="" method="get">
<select name="per_page">
<option value="10">10 per page</option>
<option value="20">20 per page</option>
<option value="50">50 per page</option>
<option value="100">100 per page</option>
</select>
<input type="submit" Value="Go">
</form>
{% paginate pagination_per_page entries %}
{% for entry in entries %}
{# your code to show the entry #}
{% endfor %}
{% show_pages %}
{% endblock content %}
Reference
http://django-endless-pagination.readthedocs.org/en/latest/templatetags_reference.html
I have a ModelForm that posts news items to a database, and it uses a javascript textarea to allow the authorized poster to insert certain pieces of HTML to style text, like bold and italics. However, since I have the template output using the "safe" filter, it outputs all the HTML the form widget tries to pass on. This includes a bothersome <br> tag that never goes away, making it so you can submit without form validation reading the field as empty and stopping you. How can I make that I can not only filter the <br> tag, but completely remove it from the data? Here is relevant code:
Models.py:
from django.db import models
from django.forms import ModelForm, forms
from django.contrib.auth.models import User
# Create your models here.
class NewsItem(models.Model):
user = models.ForeignKey(User)
date = models.DateField(auto_now=True)
news = models.TextField(max_length=100000, blank=False, help_text='HELP TEXT')
def __unicode__(self):
return u'%s %s %s' % (self.user, self.date, self.news)
class NewsForm(ModelForm):
class Meta:
model = NewsItem
exclude=('user','date',)
Views.py:
from news.models import NewsForm, NewsItem
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
def news(request):
if request.method == 'POST':
item = NewsItem(user=request.user)
form = NewsForm(request.POST, instance=item)
if form.is_valid():
form.save()
return HttpResponseRedirect('/news/')
else:
form = NewsForm()
news_list = NewsItem.objects.all()
return render(request, 'news_list.html', {'news_list': news_list, 'form': form})
news_list.html:
{% extends "base.html" %}
{% block title %}News in the Corps{% endblock %}
{% block content %}
<h2 id="page_h">News in the Corps</h2>
{% if user.is_authenticated %}
<h3>Post News</h3>
<script src="{{ STATIC_URL }}nicEdit.js" type="text/javascript"></script>
<script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script>
<div id="news_poster">
<form id="news_poster" action="/news/" method="POST">{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
</div>
{% endif %}
<ul id="events_list">
{% if news_list %}
<div id="news_list">
{% for news in news_list %}
{% if news.id == 1 %}
<hr />
{% endif %}
<div id="{{ news.id }}" class="news_item">
<p class="poster">Posted By: {{ news.user }} | Posted On: {{ news.date }} | Link</p>
<div id="news_item">
{{ news.news|safe }}
</div>
</div>
<hr />
{% endfor %}
</div>
{% endif %}
</ul>
{% endblock %}
You can try the removetags template filter:
{{ news.news|removetags:"br"|safe }}
I can't help but thinking that the "removetags" as Timmy O'Mahony suggested might work if it was structured like this:
{{ news.news|safe|removetags:"br"}}
Give it a shot and see if it works. I would reply, but my karma's not height enough to directly reply to an answer with a suggestion.
def broadcast_display_and_form(request):
if request.method == 'POST' :
form = PostForm(request.POST)
if form.is_valid():
post = form.cleaned_data['post']
obj = form.save(commit=False)
obj.person = request.user
obj.post = post
obj.save()
readers = User.objects.all()
for x in readers:
read_obj = BroadcastReader(person = x)
read_obj.post = obj
read_obj.save()
return HttpResponseRedirect('/broadcast')
else :
form = PostForm()
posts = BroadcastReader.objects.filter(person = request.user)
return render_to_response('broadcast/index.html', { 'form' : form , 'posts' : posts ,} )
My template
{% extends "base.html" %}
{% load comments %}
{% block content %}
<form action='.' method='POST'>
{{ form.as_p }}
<p>
<input type="submit" value ="send it" /></input>
</p>
</form>
{% get_comment_count for posts.post as comment_count %}
{% render_comment_list for posts.post %}
{% for x in posts %}
<p>
{{ x.post.person }} - {{ x.post.post }}
</p>
{% endfor %}
{% endblock %}
What is posts.post supposed to be? posts is a BroadcastReader QuerySet, and probably doesn't have such an attribute? I'm guessing the comment rendering tags are causing your error? Try removing them, or using posts.0 or similar to debug.
Which "post" do you actually want to display comments for? Your view logic is unclear.