When i am running my Django project on local server. It is returning whole html code on webpage.
Like after executing command python manage.py runserver and copy and pasting url on browser i am getting whole HTML file code instead element i have used.
My Html file
{% extends "wfhApp/base.html" %}
{% block body_block %}
<div class="jumbotron">
{% if registered %}
<h1>Thank you for registration</h1>
{% else %}
<h1>Register here!</h1>
<h3>Fill out the form:</h3>
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" name="" value="Register">
</form>
{% endif %}
</div>
{% endblock %}
My views.py
from django.shortcuts import render
from wfhApp.forms import UserForm
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data = request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm
return render(request, 'wfhApp/registration.html',
{'user_form': user_form},
{'registered': registered})
Above is from template inheritance.
Not 101% sure since you didn't really explained what you meant by "It is returning whole html code on webpage" but here:
return render(request, 'wfhApp/registration.html',
{'user_form': user_form},
{'registered': registered})
you're not correctly passing the template context - or, more exactly, you are passing {'user_form': user_form} as the context and {'registered': registered} as the response's content_type (which would else be the default "text/html").
What you want is (splitted on two lines for readability):
context = {
'user_form': user_form,
'registered': registered
}
return render(request, 'wfhApp/registration.html', context)
Related
I'm trying to make a website that lets visitors search for books using another search engine. I have a script that takes a query, and returns some HTML with the results of the search, but I'm struggling to make a front end for this. I am using django because it seemed like the best option when I started, but now I am going in circles and I can't figure out how to make this thing - I'm just getting overwhelmed because the different tutorials and documentation that I'm reading all go into the advanced stuff before I can get the basic thing working.
Do I need separate search and results templates? Right now I'm getting the error The view book_search.views.search didn't return an HttpResponse object. It returned None instead.
How can I fix this error and/or design this whole thing better?
Here's what I have so far (the script that returns the results in html is pull.py):
The views and urls are from inside the book_search app.
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from . import pull
from .forms import SearchForm
def index(request):
return HttpResponse("Welcome to the index page")
def test_search(request):
context = {'query': 'test query'}
return render(request, 'book_search/search.html', context)
def search(request):
if request.method == "GET":
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
results = pull.main(query)
context = {'query': query, 'form': form, 'results': results}
return render(request, 'book_search/results.html', context)
apps.py:
from django.apps import AppConfig
class BookSearchConfig(AppConfig):
name = 'book_search'
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('index', views.index, name='index'),
path('test', views.test_search, name='test_search'),
path('', views.search, name='search'),
]
forms.py:
class SearchForm(forms.Form):
query = forms.CharField(label='Search', max_length=200)
template base.html:
<html>
<head>
</head>
<body>
<form method="GET" action="/search/">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{% block content %}{% endblock %}
</body>
</html>
template results.html:
{% block content %}
{% results %}
{% endblock content %}
Since we guessed that form isn't valid (because no POST handler - you do not send anything to the form) and wrong indentation gives None response, now you can fix reference before assignment:
def search(request):
if request.method == "GET":
form = SearchForm()
context = {'form': form}
elif request.method == "POST":
form = SearchForm(request.POST)
if form.is_valid():
query = form.cleaned_data['query']
results = pull.main(query)
context = {'query': query, 'form': form, 'results': results}
return render(request, 'book_search/results.html', context)
and render errors in results.html template by putting this:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
I got some troubles with solving of "TypeError at /editprofile/
context must be a dict rather than set." in my Django project. I'm trying to allow the users to edit their personal information but I keep getting an error. I tried to read everything here and in other pages but nothing has helped, I would love to know how to solve this if anyone could direct me or give me some tips on how to fix this.
forms.py
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = (
'username',
'email',
'country'
)
views.py
def editprofile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return render(request, 'movies_app/profile.html')
else:
form = EditProfileForm(instance=request.user)
args = {'form', form}
return render(request, 'movies_app/editprofile.html', args)
editprofile.html
{% extends 'base.html' %}
{% block head %}
<title>Edit form</title>
{% endblock %}
{% block body %}
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
In your views.py args should be a dict, you should replace the , for a :.
I have refrenced this stackoverflow page and tried to display my forms error on the html template.
I did:
{% if form.error %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
as said in the stackoverflow question I also tried simply doing:
{% if form.error %}
This should pop up if there is an error
{% endif %}
Nothing comes up regardless:
Heres my view.py code:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password2')
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/')
else:
print(form.errors)
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
I am able to get the form errors onto the django console but it refuses to show up on the template.
Printing form.errors prints to the console: <li>password2<ul class="errorlist"><li>The two password fields didn't match.</li></ul></li></ul>
forms.errors fired up, but at the end, you declare a new form form = UserCreationForm() just before you render your view.
After checking whether the form is valid or not, all your validation errors are inside form instance, remember processes run as sequence, at the end, you destroy the variable form with form = UserCreationForm() so no validation errors anymore.
What you can do is add this new form form = UserCreationForm() to else statement when your request method is GET to keep having an empty form. By adding the else statement you avoid the new assignment of the form; after the validation process, it will jump to render(request,....) with the form instance containing all validation errors
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password2')
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/')
else:
print(form.errors)
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
Note, the correct call for form errors in templates is form.errors with s not form.error
{% if form.error %} {% if form.errors %}
Hi i try add comment to my django blog procject and i get OSError: [Errno 22] Invalid argument: "C:\Users\marci\PycharmProjects\08.04\blog\templates\"
so my urls
path('<int:a_id>/addcomment', views.addcomment, name='addcomment'),
views.py
def addcomment(request, a_id):
article = get_object_or_404(Articles,id=a_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.article = article
comment.save()
return HttpResponseRedirect('/article/%s' % a_id)
else:
form = CommentForm()
template = 'addcomment.html'
context = {'form': form}
return render_to_response(request,template,context)
addcomment.html
{% extends 'main.html' %}
{% block article %}
<form action="/article/{{ article.id }}/addcomment/" method="post" class="form-horizontal well">{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-inverse" name="submit" value="Dodaj komentarz" />
</form>
{% endblock %}
thx
You should be using render instead of render_to_response. You should also include article in the template context if you use it. Deindent the template and contect lines, so that the view works for invalid post requests.
def addcomment(request, a_id):
article = get_object_or_404(Articles,id=a_id)
if request.method == 'POST':
...
else:
form = CommentForm()
template = 'addcomment.html'
context = {'form': form, 'article': article}
return render(request, template, context)
Form is not shown in html correctly.I wrote in search.html,
{% load static %}
<form action='/search/' method='POST>
<table>
{{ form.as_table }}
</table>
<input name="submit" type="Search" />
{% csrf_token %}
</form>
in views.py
def search(request):
form = SearchForm()
if request.method == 'GET':
return render_to_response(
'search.html', {'form': form}, RequestContext(request))
elif request.method == 'POST':
form = SearchForm(request.POST)
search_result = POST.objects.all()
if form.is_valid():
result = search_result.filter(Q(title__contains=form.cleaned_data['keyword']))
return render_to_response('search.html',{'form':form, 'result':result})
When I access search method,search.html is shown as strings like
now search.html
It is not From,so I really cannot understand why such a thing happens.No error happens but UserWarning: A {% csrf_token %}was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
"A {% csrf_token %} was used in a template, but the context " is shown in terminal.How should I fix this?What is wrong in my code?
This may not be the issue, but I think your input tag is wrong, it should be this:
<input name="submit" type="Search">
As here : https://www.w3schools.com/tags/tag_input.asp