I searched all around the web and didn't find an answer so hopefully this is not a duplicate. So I am trying to build a browser app using Django and are using some Jinja code in my html file, but the html file when loaded into a browser doesn't recognize Jinja code and only display raw code. In fact after some experimentation I found out that my browser doesn't display correctly any Jinja code. I checked and I've installed Jinja2 on my computer.
My html file looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Music FFT Visualizer</title>
<style></style>
</head>
{% block content %}
<body>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload a Song</button>
</form>
</body>
{% endblock %}
<html>
and my view.py looks like this:
from django.shortcuts import render
from .forms import MusicVisualizerForm
from .models import MusicVisualizer
def lastSong(request):
MusicVisualizers = MusicVisualizer.objects.all()
MusicVisualizer_last = MusicVisualizers[len(MusicVisualizers)-1]
return render(request, 'MusicVisualizer/templates/MusicVisualizer.html', { 'MusicVisualizer' : MusicVisualizer_last})
def uploadSong(request):
if request.method == 'POST':
form = MusicVisualizerForm(request.POST, request.FILES)
if form.is_valid():
form.save()
else:
form = MusicVisualizerForm()
return render(request, 'MusicVisualizer/templates/MusicVisualizer.html', {'form' : form})
my webpage looks like this:
Related
I have tried to create a minimal working example of FormPreview of Django FormTools, but it did not work.
forms.py
This is a very simple form.
from django.forms import CharField, Form, Textarea
class TextForm(Form):
text = CharField(widget=Textarea)
preview.py
This is with slight adjustments just copied from the documentation. It is of curse incomplete but I did not changed it because I did not even got to a preview page of any kind.
from django.http import HttpResponseRedirect
from formtools.preview import FormPreview
class TextFormPreview(FormPreview):
def done(self, request, cleaned_data):
# Add stuff later, once I get to a preview.
return HttpResponseRedirect('/')
urls.py
Here must be some mistake, but I don't know how it should be correct. Should I remove the first URL? How does FormPreview know what the correct view to use is?
from django.conf.urls import url
from django import forms
from .forms import TextForm
from .preview import TextFormPreview
from . import views
urlpatterns = [
url(r'^$', views.textform),
url(r'^post/$', TextFormPreview(TextForm)),
]
views.py
My simple views.py.
from django.shortcuts import render
from .forms import TextForm
def textform(request):
if request.method == 'POST':
form = TextForm(request.POST)
if form.is_valid():
text = form.cleaned_data['text']
print(text)
if request.method == 'GET':
form = TextForm
context = {
'form': form
}
return render(request, 'text.html', context)
templates/text.html
And a simple template.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.manual_recipients.errors }}
{{ form.text }}
</div>
<input type="submit" value="OK"/>
</form>
</body>
</html>
templates/base.html
base.html is just an empty file. If I go to ^post/$ it says it requires a base.html. Why? I do not know.
As said, I did all the steps from the documentation but it is obviously incomplete. How do I fix it?
The default template for FormPreview extends base.html. and includes a single block content.
In your base.html, you need to include {% block content %}{% endblock %}. A minimal template would be:
<html>
<body>
{% block content %}{% endblock %}
</body>
</html>
See the docs on template inheritance for more info.
I am using django-allauth. I want the login and signup forms both on the home page of my website and not on '/accounts/login' or '/accounts/signup'
I have created a separate app. The following code is in views.py
from allauth.account.views import SignupView
from allauth.account.forms import LoginForm
class CustomSignupView(SignupView):
# here we add some context to the already existing context
template_name = 'index.html'
def get_context_data(self, **kwargs):
# we get context data from original view
context = super(CustomSignupView,
self).get_context_data(**kwargs)
context['login_form'] = LoginForm() # add form to context
return context
the following is in index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="toggleForms">Toggle Forms</button>
<form method='post' action='/accounts/signup/' id='signup'>
{% csrf_token %}
<h1>blah</h1>
{{ form.as_p }}
<input type='submit' value='Sign Up'>
</form>
<form method='post' action='/accounts/login/' id='login'>
{% csrf_token %}
{{ login_form.as_p }}
<input type='submit' value='Log In'>
</form>
</body>
</html>
The forms work when the inputs are correct i.e. the form is valid. The problem is when the validation fails (in case of incorrect credential) the user is redirected to accounts/login and the error message is displayed. How to stop this redirect and show the error messages too on the home page?
It would probably be easier to override the template so that it looks like your index page. You can either specify a template with the name ('account/login.html'), or specify your own version of the URL, with a different template altogether:
from allauth.account.views import LoginView
...
url(r'^my-login/$', LoginView.as_view(template_name="index.html"), name="my-login"),
...
Neither of these are part of the public API for allauth, so use them at your own risk...
As we know, if we want to access user session from context within a inclusion tag, you can use takes_context argument and pass a request context in the view.
But in my project, it is more complicated:
The view is simple:
# views.py
def index(request):
form = PersonForm()
return render(request, 'add.html', {'form': form})
Templates:
# templates/add.html
<html>
<head>
<title>Add Person</title>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
{{ form.as_p }}
</form>
{% render_attachments %}
...
</body>
</html>
# templates/list.html
{% load my_tags %}
<div class="attachments" style="margin:12px 0 12px 0;">
{% for attachment in attachments %}
<a href="{{ attachment.attachment_file.url }}">{{ attachment.filename }}
</a>
{% attachment_delete_link attachment %}
{% endfor %}
</div>
Here is my custom tags:
# my_tags.py
#register.inclusion_tag('attachments/list.html', takes_context=True)
def render_attachments(context):
session = context['request'].session
return {'attachments': session.get('attachments', [])}
#register.inclusion_tag('attachments/delete_link.html', takes_context=True)
def attachment_delete_link(context, attachment):
if context['user'] == attachment.creator:
return {
'delete_url': reverse('delete_attachment',
kwargs={'attachment_pk': attachment.pk})
}
return {'delete_url': None}
When i run my project, i got the following error:
KeyError at /person/
'user'
Request Method: GET
Request URL: http://localhost:8000/person/
Django Version: 1.5.1
Exception Type: KeyError
So, i print context out within two tags to find out what happened, it seemed that the request context does not passed into attachment_delete_link, how can i resolve this problem?
You are overwriting the whole context in render_attachments() you must return
def render_attachments(context):
# some code...
context['attachments'] = session.get('attachments', [])
return context
Same goes for attachment_delete_link().
I'm new to Django and I'm still trying to get to grips with its features. I've created very simple project with Django 1.4.2 which has index page with simple form where you enter something and results page where your input is displayed after submission (the code is below).
After submission, I get error 403 and the following message:
A {% csrf_token %} was used in a template, but the context did not
provide the value. This is usually caused by not using
RequestContext. warnings.warn("A {% csrf_token %} was used in a
template, but the context did not provide the value. This is usually
caused by not using RequestContext.")
index.html
<!DOCTYPE html>
<head>
<title>Index page</title>
</head>
<body>
<div id="header">Welcome to index page</div>
<div id="content">
<p>Enter your name</p>
<form action="/result/" method="post" accept-charset="utf-8">{% csrf_token %}
<input type="text" name="answer">
<input type="submit" value="Send!">
</form>
</div>
</body>
result.html
<!DOCTYPE html>
<head>
<title>Result page</title>
</head>
<body>
<div id="header">Here is the result</div>
<div id="content">
<p>Your name is: {{ answer }}</p>
</div>
</body>
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
return render_to_response('index.html')
def result(request):
p = request.POST['answer']
return render_to_response('result.html', {'answer': p}, context_instance=RequestContext(request))
I've looked into documentation and various examples on the Internet, but I don't understand what I'm doing wrong. If I disable django.middleware.csrf.CsrfViewMiddleware in settings.py, I get exactly what I want, but that's not the answer I'm looking for.
I appreciate help from more experienced Django ninjas :-)
Your index.html is rendered without RequestContext. Try this:
def index(request):
return render_to_response('index.html', context_instance=RequestContext(request))
I also recomend you to use more convenient shortcut render:
from django.shortcuts import render
def index(request):
return render('index.html')
From docs:
render() is the same as a call to render_to_response() with a
context_instance argument that forces the use of a RequestContext.
EDIT:
Thanks #nerdwaller for mentioning, newer versions now needs:
render(request, 'index.html', {params});
I was getting this error using Django 2.1, turned out that it was caused by make an ajax request in the template that was called by another ajax request. So, the solution was to add 'request=request' to my render function:
args = {'someargs': somevalues}
html = render_to_string(
'my_template.html', context=args, request=request)
return HttpResponse(html)
I'm trying to upload a csv file in my view. I included csrf token however I'm directly taking 403 error when I try to upload a file. Here is my view and template:
MY FORM HTML
<div class="file-boxes">
<form enctype="multipart/form-data" action="" encoding="multipart/form-data" id="upload-csv" method="post">
{% csrf_token %}
{{form.csv}}
<!-- <input class="input-file" id="fileInput" type="file" size="14" name="csv_upload" onchange="this.form.submit()"> -->
</form>
</div>
MY FORM
class DeliveryDataForm(forms.Form):
csv = forms.FileField(widget=forms.ClearableFileInput(attrs={'size:':14,'onchange':'this.form.submit()'}))
MY VIEW
def upload_data(request):
...
form = DeliveryDataForm()
if request.method == "POST":
import pdb
pdb.stack_trace()
form = DeliveryDataForm(request.POST, request.FILES)
return HttpResponse('asd')
return render_to_response(template,context)
I know there are some missing parts in the view but the strange thing is, it never enters the if part. Any idea ?
from django.shortcuts import render
# ...
# return render_to_response(template,context)
return render(request,'index.html',context)