I am trying to get AreYouAHuman capcha on my website,
I mostly got it working the problem is nothing shows up.
this is part of the render'd html
<label for="id_session_secret">Are You Human</label>
<br>
<div id="AYAH"></div><script type="text/javascript" src="https://ws.areyouahuman.com/ws/script/87e31f12336132203bdde2da8c93269fccdd5f52"></script>
<p></p>
and this is what i see in the browser
> Are You Human <div id="AYAH"></div><script type="text/javascript"
> src="https://ws.areyouahuman.com/ws/script/87e31f12336132203bdde2da8c93269fccdd5f52"></script>
This is my Implementation
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# turtle.forms.py
#
# Copyright 2013 Brian Scott Carpenter <talisman#talisman-Pangolin-Performance>
from django import forms
from django.conf import settings
import ayah
ayah.configure(
settings.AREYOUHUMAN_PUBLISHER_KEY,
settings.AREYOUHUMAN_SCORING_KEY,
)
from django.forms import Field, ValidationError, Form
from django.forms.widgets import Widget
#Create a wdiget that renders the AreYouHuman html
class AreYouHumanWidget(Widget):
def render(self, name, value, attrs=None):
return ayah.get_publisher_html()
#AreYouHuman uses a test field (session_secret) for validation
class AreYouHumanField(Field):
#Use the AreYouHuman HTML
widget = AreYouHumanWidget
#Validate agianst AreYouHuman
def validate(self, value):
if not ayah.score_result(value):
raise ValidationError("You may not be human.")
class Turtle_Form(forms.ModelForm):
''' This is code to make sure the User automatically saves the
user to the database in context.
'''
session_secret = AreYouHumanField(label="Are You Human")
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(Turtle_Form, self).save(*args, **kwargs)
if self.request:
obj.user = self.request.user
obj.save()
return obj #<--- Return saved object to caller.
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(Turtle_Form, self).__init__(*args, **kwargs)
the template looks like
{% extends "base.html" %}
{% load i18n zinnia_tags %}
{% load url from future %}
{% block title %}tempilo.org{% endblock %}
{% block content %}
<form action="" method="post">{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}
<br>
{{ field | safe }}
<p></p>
</div>
{% endfor %}
<p><input type="submit" value="Save" /></p>
</form>
{% endblock %}
You might need to wrap the call to ayah.get_publisher_html() in the widget render method with a call to django.utils.safestring.mark_safe() to prevent it being autoescaped.
Related
I'm trying to create a frontend data entry page for an existing model. However, when clicking the link, I get an error:
crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field
Just to be clear, adding the data from Django Admin works with no issues at all.
Having looked through a number of answered questions here, one did highlight what I believe could be problem, but it was out of context and did not provide much of an explanation.
I am trying to create a frontend entry form for users that corresponds with a foreign key.
models.py
class NewHandoff(models.Model):
handoff_pk = models.AutoField(primary_key=True)
handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date")
shift1_pri = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Primary")
shift1_sec = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Secondary")
def __str__(self):
return f"{self.handoff_date}"
class Meta:
verbose_name_plural = 'Handoffs'
# New Handoff Form
class NewHandoffForm(forms.ModelForm):
class Meta:
model = NewHandoff
fields = ['shift1_pri','shift1_sec']
views.py
from django.shortcuts import redirect, render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import HttpResponse
from django.contrib import messages
from .models import AttentionForm, NewHandoffForm
# Handoff View Page
class NewHandoffView(LoginRequiredMixin,View):
def get(self, request):
greeting = {}
greeting['heading'] = "New Handoff"
greeting['pageview'] = "Handoff"
return render (request,'handoff/handoff-new.html')
def post(self, request):
if request.method == "POST":
if "add-new-handoff-button" in request.POST:
create_new_handoff_form = NewHandoffForm(request.POST)
create_new_handoff_form.save()
return redirect("/handoff/handoff-create")
handoff-new.html
{% extends 'partials/base.html' %}
{% load static %}
{% load humanize %}
{% load crispy_forms_tags %}
{% block extra_css %}
<link href="{% static 'libs/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css' %}" rel="stylesheet">
{% endblock %}
{% block contents %}
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<!-- New Form -->
<form method="POST">
{% csrf_token %}
<div class="row">
<div class="row-fluid pb-1">
<!-- Field 1 -->
<div class="mb-3">
{{ form.shift1_pri|as_crispy_field }}
</div>
<!-- End of Field 1 -->
</div>
</div>
<div class="d-flex flex-wrap gap-2">
<button type="submit" class="btn btn-primary waves-effect waves-light" name="add-new-handoff-button">Create New Handoff</button>
</div>
</form>
<!-- End of New Form -->
</div>
</div>
</div>
</div>
{% endblock %}
{% block extra_javascript %}
{% endblock %}
Someone mentioned in another post that forms should correlate with the declared form name {{ form.shift1_mod|as_crispy_field }} so it should actually be {{ create_new_handoff_form.shift1_mod|as_crispy_field }} but I have tried changing this and still get the same problem, plus, another model form works fine with just form despite the name of the form being attention_form.
Does anyone have any idea or can point me in the right direction? :)
You are not passing the form through the context in the template. As you are inheriting View, Add the following line in the get() and afterwards in the post() method appropriately:
form = NewHandoffForm()
# and then change return
return render(request,'handoff/handoff-new.html', {'form': form })
Also, you have a space after render in the get function. I hope this is a typo here, but not in your code.
I need to iterate through a list of checkboxes and add a link to each of them. However I am not able to do so.
The template shows the complete form as a link istead of an individual checkbox being a list.
Below given is my code:
Here is my forms.py:
class GetTaskDescription(forms.Form):
get_tasks = forms.ModelMultipleChoiceField(
queryset=Task.objects.none(),
widget=forms.CheckboxSelectMultiple,
required=True
)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(GetTaskDescription, self).__init__(*args, **kwargs)
self.fields['get_tasks'].queryset = self.user.task_set.all()
def get_task_description(self):
tasks = self.cleaned_data['get_tasks']
return tasks
Here is my html:
{% extends 'todoapp/base.html' %}
{% block title %}Select a Task{% endblock %}
{% block content %}
<h2>Select tasks to view description</h2>
<form method="get" action="{% url 'view_task_description' %}" name="view_task_description">
{% for tasks in view_tasks %}
{{ tasks }}
{% endfor %}
<br/>
<input type="submit" value="View Description">
<button onclick="location.href='{%url 'dashboard' %}?name=Go back'" type="button">Go back</button>
</form>
{% endblock %}
Here is my views.py:
#login_required(login_url='/login/')
def view_task_description(request):
task_description = GetTaskDescription(data=request.GET, user=request.user)
if task_description.is_valid():
obj = GetTaskDescription.get_task_description(task_description)
print obj
return render(request, 'todoapp/task_desc.html', context={'description': obj})
return render(request, 'todoapp/select_task_description.html', context={'view_tasks': GetTaskDescription(user=request.user)})
You're trying to iterate over a form instance:
'view_tasks': GetTaskDescription(user=request.user)
{% for tasks in view_tasks %}
To access field choices you should use view_tasks.fields.get_tasks.choices in template.
I am new to Django and I am trying to create a form in a template. I think I have accomplished this however I a missing a piece. This is what I currently see:
I think I am missing something from my form class that should display the choices.
forms.py
from django import forms
class TestForm(forms.Form):
one = forms.ChoiceField(choices=('HDFS', 'HDFS'), widget=forms.RadioSelect())
two = forms.ChoiceField(choices=('HIVE', 'HIVE'), widget=forms.RadioSelect())
three = forms.ChoiceField(choices=('BOTH', 'Both of HDFS and HIVE'), widget=forms.RadioSelect())
beatle = [one, two, three]
event_textarea = forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event_textarea'})
views.py
def home(request):
if request == 'POST':
# create a form instane and populate it with data from the request
form = TestForm(request.POST)
if form.is_valid():
# process the data in form.cleaned_data as required
form.cleaned_data()
# redirect to a new URL:
return HttpResponseRedirect('/test/')
# if a GET (or any other method) we'll create a blank form
else:
form = TestForm()
return render(request, 'home/home_page.html', {'form': form})
template:
{% extends 'index/index.html' %}
{% load staticfiles %}
{% block head %}
<script type="text/javascript" src="{{ STATIC_URL }}home/js/home.js" async></script>
<link href="{{ STATIC_URL }}home/css/home.css" rel="stylesheet">
{% endblock head %}
{% block content %}
<div>Welcome to Trinity E2E testing</div>
<form id="test-form" action="/test/" method="post"> {# pass data to /test/ URL #}
{% csrf_token %}
{% for radio in form.beatle %}
<div class="btn btn-default btn-lg">
{{ radio }}
</div>
{% endfor %}
{{ form.event_textarea }}
<input id="submit-test" type="submit" class="btn btn-default btn-lg" value="Submit">
</form>
{% endblock content %}
beatle list contains references to class attributes, not instance attributes.
How about make it a instance method to return instance attributes (form fields):
def beatle(self):
return [self.one, self.two, self.three]
UPDATE
To correctly return bound fields:
def beatle(self):
return [self['one'], self['two'], self['three']]
or
def beatle(self):
return [self[name] for name in ['one', 'two', 'three']]
I wrote a simple app that is a custom DateField widget for mezzanine. Afaik it's, it's a simple case and besides overextending a template it would be the same in pure django or django-cms (feel free to correct me if I'm wrong).
The widget:
class DatePickerInput(forms.DateInput):
def __init__(self, attrs = None, format = None):
super(DatePickerInput, self).__init__(attrs, format)
self.attrs["class"] = "datepicker"
class Media:
css = { "all": ('css/ui-lightness/jquery-ui-1.10.3.custom.min.css',) }
js = (
"mezzanine/js/" + getattr(settings, "JQUERY_UI_FILENAME", "jquery-ui-1.9.1.custom.min.js"),
"js/datepicker_setup.js",)
I overextend base.html template to insert form.media:
{% overextends "base.html" %}
{% load pages_tags mezzanine_tags i18n future staticfiles %}
{% block extra_head %}{{ block.super }}
{{ form.media }}
{% endblock %}
Now, I create a form for my model class.
Here's the class:
class PlayerProfile(models.Model):
user = models.OneToOneField("auth.User")
# Can be later changed to use a setting variable instead of a fixed date
date_of_birth = models.DateField(default=date(1990, 1, 1))
Here's the model form:
from DateWidgets.widgets import DatePickerInput
from PlayerProfiles.models import PlayerProfile
class EditPlayerProfileForm(Html5Mixin, forms.ModelForm):
class Meta:
model = PlayerProfile
fields = ("date_of_birth", )
widgets = { 'date_of_birth': DatePickerInput }
def __init__(self, *args, **kwargs):
super(EditPlayerProfileForm, self).__init__(*args, **kwargs)
Here's the view:
#login_required
def profile_update(request, template="accounts/account_profile_update.html"):
"""
Profile update form.
"""
pform = forms.EditPlayerProfileForm
player_form = pform(request.POST or None, request.FILES or None, instance=request.user.playerprofile)
context = {"pform": player_form, "title": _("Update Profile"), "profile_user": request.user}
return render(request, template, context)
Here's the template:
{% overextends "accounts/account_profile_update.html" %}
{% load i18n mezzanine_tags %}
{% block main %}
<fieldset>
<legend>{{ title }}</legend>
<form method="post"{% if pform.is_multipart %} enctype="multipart/form-data"{% endif %}>
{% fields_for pform %}
<div class="form-actions">
<input class="btn btn-primary btn-large" type="submit" value="{{ title }}">
</div>
</form>
</fieldset>
{% endblock %}
Now if I view the form in a browser, the custom widget is there (I can tell because the input html tag has my custom class attribute value) but it doesn't inject the form media, it's missing. Any idea what's going on here? Thanks in advance! Cheers :-)
form isn't available in the template, because you've called your form variable pform.
Try {{ pform.media }}.
I was googled here with the same problem under different conditions and spotted another error that may appear under other conditions (my case is extending change_form.html in Django 2.1): I had to use extrahead instead of extra_head
{% block extrahead %}{{ block.super }}
{{ form.media }}
{% endblock %}
I have a really weird problem. my index page shows image. There isn't any error, codes are here:
def index(request):
post = Post.objects.get(id=1)
return render_to_response("index.html", {"post":post}, context_instance=RequestContext(request))
but my detail page doesnt display image. codes here:
class PostDetailView(DetailView):
context_object_name = "post"
model = Post
template_name = "post_detail.html"
def get(self, request, *args, **kwargs):
self.next = self.request.get_full_path()
return super(PostDetailView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
context["form"] = CommentForm()
context["next"] = self.next
context["object_id"] = context['post'].id
context["comments"] = Comment.objects.filter(
content_type=ContentType.objects.get_for_model(self.model),
object_id=context['post'].id, is_published=True)
return context
my post_detail.html page:
{{ post.title }} -----here ok!
{{ post.content }} ------here ok!
<div class="img">
{% if post.image %}
<img src="media/{{post.image_thumb}}" /> -----but here not ok.Why?
{% endif %}
</div>
my index.html
{{ post.title }}
{{ post.content }}
<div class="img">
{% if post.image %}
<img src="media/{{post.image_thumb}}" />
{% endif %}
</div>
So what is my problem, thanks for time.
firstly,make sure you have set the media dir in file settings.py conrrectly and then change your image url to:
<img src="/media/{{post.image_thumb}}" />
you missing a slash
You should use {{ post.image_thumb.url }} instead of {{ post.image_thumb }}.
{{ post.image_thumb }} implicitly calls __unicode__ method of post, but what you want is the url attribute of image, you can get the absolute url of image with this.