Goal/tl;dr I want to call my added method from views.py when you submit the forum and use the stuff from the textfield to make a new post object.
I am new to django, and I have looked through other stack posts, but most of these errors seem to be for cookies or users. I have also looked at the python documentation as most people have suggested, but I haven't seen all the pieces together and I am not sure how to get the textfield from the forum. Correct code and/or and explanation of what I am doing wrong and how to do it would be much appreciated.
models.py
from django.db import models
class Post(models.Model):
text = models.TextField(max_length=250)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.text
views.py
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response, redirect
from blog.models import Post
from django.core.context_processors import csrf
def home(request):
try:
p = Post.objects.all()
except Post.DoesNotExist:
raise Http404
return render_to_response('index.html',
{'post':p})
def post(request, uID):
try:
p = Post.objects.get(pk=uID)
except:
raise Http404
return render_to_response('post.html',
{'post':p})
def delete(request, uID):
try:
p = Post.objects.get(pk=uID).delete()
except:
raise Http404
return render_to_response('delete.html',
{'post':p})
def new(request):
context = {}
context.update(csrf(request))
return render_to_response('new.html', context)
def added(request):
if request.method == 'POST':
context = {}
context.update(csrf(request))
p = Post.objects.create(text=request.text)
p.save()
return render_to_response("index.html", context)
else:
raise Http404
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'blog.views.home', name='home'),
url(r'^(?P<uID>\d+)/$', 'blog.views.post', name='Post Id'),
url(r'^(?P<uID>\d+)/delete/$', 'blog.views.delete', name='del'),
url(r'^new/$', 'blog.views.new'),
url(r'^created/$', 'blog.views.added'),
# url(r'^myApp/', include('myApp.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
new.html
<html>
<body>
<h2> Create a new Post </h2>
<form method="post" action="/created/">
{% csrf_token %}
Body: <input type="textarea" name="text">
<input type="submit" value="Submit">
</form>
</body>
</html>
You mean request.POST['text'].
You should probably investigate the forms framework though.
Related
I was doing some How-To tutorials about Django Forms.
But it will not display anything for me. Any ideas why? Picture below illustrates my problem.
This is my Login -> index.html
<body>
<div class="gradient-border" id="box">
<h2>Log In</h2>
<form action = "" method = "post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit">
</form>
</div>
</body>
this is forms.py
class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200)
last_name = forms.CharField(max_length = 200)
password = forms.CharField(widget = forms.PasswordInput())
this is views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import InputForm
def index(request):
return render(request, 'login/index.html')
def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "index.html", context)
def main(request):
return render(request, 'login/main.html')
this is urls.py
from django.contrib import admin
from django.urls import path, include
from login.views import index, main
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', index),
path('main/', main),
path('accounts/', include('django.contrib.auth.urls')),
]
Login Page
You are not passing the form context for the login route. In your index function, you don't have any context, and you put the form in home_view function which is not the view function being called by the /login route.
I'm very new to Django and part of the assignment was to create our own blog model form. I followed the previous examples of the youtube tutorial but was unable to create my own blog model form. The form will not save because it's invalid and I have been busting my head for 2 days to solve it but can't find what is wrong.
Also, every time I submit my form, it redirects me to another page which I don't quite understand why.
Please help.
I'm using Django version 2.0.7.
My models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=120) # Max length required
content = models.TextField()
active = models.BooleanField(default=True)
My forms.py
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = [
'title',
'content',
'active'
]
my views.py
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ArticleForm
from .models import Article
def article_list_view(request):
print("this is article_list.html")
queryset = Article.objects.all()
context ={
"object_list": queryset
}
return render(request, "blogs/article_list.html", context)
def article_create_view(request):
form = ArticleForm(request.POST or None)
print(ArticleForm.errors)
if form.is_valid():
print("Valid form")
form.save()
else:
print("invalid")
print(ArticleForm.errors)
context = {
"form": form
}
return render(request, "blogs/article_create.html", context)
article_create.html
{% extends 'base.html' %}
{% block content %}
<form action='.' method='POST'>{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Save'>
</form>
{% endblock %}
urls.py
from django.contrib import admin
from django.urls import include, path
from pages.views import (
home_view,
contact_view,
about_view,
social_view
)
from blog.views import (
article_list_view,
article_detail_view,
article_create_view
)
urlpatterns = [
path('products/', include('products.urls')),
path('', home_view, name='home'),
path('contact/', contact_view, name='contact'),
path('about/', about_view, name='product-detail'),
path('social/', social_view, name='social'),
path('admin/', admin.site.urls),
#blog paths
path('articles/', article_list_view, name = 'articles'),
path('articles/detail/<int:id>', article_detail_view, name = 'article-detail'),
path('articles/create', article_create_view, name = 'article-create'),
]
This shows up on my command prompt of my server:
Django version 2.0.7, using settings 'trydjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
<property object at 0x000001ED94386458>
invalid
<property object at 0x000001ED94386458>
[18/Apr/2019 22:33:51] "GET /articles/create HTTP/1.1" 200 920
this is article_list.html
[18/Apr/2019 22:34:02] "POST /articles/ HTTP/1.1" 200 668
As soon as I land onto the articles/create or article_create.html, the <property object at 0x000001ED94386458> shows up.
1) You should not use .errors on the class.
ArticleForm.errors
should be
form.errors
2) You should separate your GET and POST requests in your view.
def article_create_view(request):
if request.method == "POST":
form = ArticleForm(request.POST)
if form.is_valid():
print("Valid form")
form.save()
else:
print("Invalid form")
print(form.errors)
else:
form = ArticleForm()
context = {"form": form)
return render(request, "blogs/article_create.html", context)
Your form should be posting to "", not ".".
<form action='' method='POST'>{% csrf_token %}
Alternatively/additionally, make sure you originally navigate to /articles/create/, not /articles/create without the final slash. (Although normally the built-in CommonMiddleware will take care of redirecting to the path with the slash - have you set the APPEND_SLASH setting to False by any chance? Don't.)
views.py
name.html cannot be found
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import Get_name
# Create your views here.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/THANKS/')
else:
form = Get_name()
return render(request,'name.html',{'from':form})
name.html:why python is not able to find my template? my template dir structure is test2/templates/test2/name.html
<form action="/username/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
class Get_name(forms.Form):
user_name = forms.CharField(label='username',max_length='50')
test2/urls.py
from django.conf.urls import url
from .import views
urlpatterns=[
url(r'^$',views.index,name='index'),
]
test1/urls.py
from django.contrib import admin
from django.conf.urls import url , include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test2/',include('test2.urls')),
]
I think this will solve the problem.
Modify your views such that.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/THANKS/')
else:
form = Get_name()
return render(request,'test2/name.html',{'from':form})
prepend template name with test2 such that return render(request,'test2/name.html',{'from':form})
I am making a web site by seeing Django tutorial.
I wanna load results.html when I put vote button is in detail.html ,but now index.html is loaded.detail.html is
{% extends "polls/base.html" %}
{% load bootstrap3 %}
{% block contents %}
<h1>{{ question.question_text }}</h1>
<!--{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}-->
<form action="{% url 'polls:poll_vote' question.id %}" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Vote" />
</form>
{% endblock %}
When I put vote button is this code <input type="submit" value="Vote" />,
I wanna show results.html .
views.py is
from django.shortcuts import render
from django.urls import reverse_lazy
from django.utils.html import mark_safe
from .models import Question
from django.http import HttpResponse
from django.shortcuts import Http404
from django.shortcuts import get_object_or_404,redirect
from .models import Choice
from django.views.generic import TemplateView
from django.views.generic import DetailView
from django.views.generic import ListView
from .forms import MyForm
from .forms import VoteForm
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin
from django.shortcuts import resolve_url
from django.contrib import messages
# Create your views here.
def index(request):
return render(request,'polls/index.html',{
'questions': Question.objects.all(),
})
def vote(request,pk):
question = get_object_or_404(Question,pk=pk)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError,Choice.DoesNotExist):
return render(request,'poll/detail.html',{
'question':question,
'error_message':"You didn't select a choice",
})
else:
selected_choice.votes += 1
selected_choice.save()
return redirect('index')
return redirect('poll_results', pk)
# pass
def results(request,pk):
obj = get_object_or_404(Question,pk=pk)
return render(request,'polls/results.html',{
'question':obj,
})
class FormTest(FormView):
form_class = MyForm
template_name = 'polls/form.html'
success_url = reverse_lazy('polls:index')
form_test = FormTest.as_view()
class Detail(SingleObjectMixin,FormView):
model = Question
form_class = VoteForm
context_object_name = 'question'
template_name = 'polls/detail.html'
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['question'] = self.object
return kwargs
def form_valid(self, form):
form.vote()
choice = form.cleaned_data['choice']
messages.success(self.request,'"%s"に投票しました' % choice)
return super().form_valid(form)
def get_success_url(self):
return resolve_url('polls:results',self.kwargs['pk'])
detail = Detail.as_view()
I think def vote(request,pk) is read,so return redirect('poll_results', pk) is also read and results.html is load.But my ideal flow is not realized.Was I wrong to write directory?
Directory is
How can I fix this?return redirect('polls_results', pk) did not work.
Now I received one answer,
vote method in views.py is
def vote(request,pk):
question = get_object_or_404(Question,pk=pk)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError,Choice.DoesNotExist):
return render(request,'poll/detail.html',{
'question':question,
'error_message':"You didn't select a choice",
})
else:
selected_choice.votes += 1
selected_choice.save()
return redirect('index')
return redirect(reverse('polls_results'), pk=pk)
but same error happens.
urls.py in polls is
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
app_name="polls"
urlpatterns = [
url(r'(?P<pk>\d+)/$', views.detail, name='poll_detail'),
url(r'(?P<pk>\d+)/vote$', views.vote, name='poll_vote'),
url(r'(?P<pk>\d+)/results$', views.results, name='poll_results'),
url(r'^$',views.index,name='index'),
url(r'^form$', views.form_test),
]
It seems that you are using namespaced urls.
In that case, you should use the namespace prefix whenever you use reverse, redirect or {% url %}.
return redirect('polls:polls_results', pk=pk)
Use reverse or write the correct path in redirect method.
Example:
from django.urls import reverse
def the_view(request):
# change here
return redirect(reverse('poll_results'), pk=pk)
# or
return redirect('results_url', pk=pk)
EDIT: Based on your urlpatterns, it seems that you're passing the wrong name in the reverse method, polls_results, where as you've defined it to be as poll_results.
You haven't removed the redirect to index statement in else part of the code in vote method.
def vote(request, pk):
# your code
else:
# save to model
# remove redirect statement here
return redirect(reverse('poll_results'), pk=pk)
Ref: https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#reverse
I am trying understand why I get the NoReverseMatch error when I use the User register form that I've created:
According to my situation, I reference the relevant files/information:
I have the main urls.py file named neurorehab/urls.py
from django.conf.urls import include, url, patterns
from django.conf import settings
from django.contrib import admin
from .views import home, home_files
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', home, name='home'),
url(r'^', include('userprofiles.urls')),
#Call the userprofiles/urls.py
url(r'^(?P<filename>(robots.txt)|(humans.txt))$', home_files, name='home-files'),
]
# Response the media files only in development environment
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT,}),
)
I have the module/application named userprofiles, in which I have the userprofiles/urls.py file of this way:
from django.conf.urls import include, url, patterns
from .views import (ProfileView, LogoutView,
AccountRegistrationView, PasswordRecoveryView,
SettingsView)
from userprofiles.forms import CustomAuthenticationForm
urlpatterns = [
url(r'^accounts/profile/$', ProfileView.as_view(), name='profile/'),
# Url that I am using for this case
url(r'^register/$', AccountRegistrationView.as_view(), name='register'),
url(r'^login/$','django.contrib.auth.views.login', {
'authentication_form': CustomAuthenticationForm,
}, name='login',
),
url(r'^logout/$', LogoutView.as_view(), name='logout'),
]
The url register call to the CBV AccountRegistrationView located in the userprofiles/urls.py which is so:
from django.shortcuts import render
from django.contrib.auth import login, logout, get_user, authenticate
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
# Importing classes for LoginView form
from django.views.generic import FormView, TemplateView, RedirectView
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse, reverse_lazy
from .mixins import LoginRequiredMixin
from .forms import UserCreateForm
class AccountRegistrationView(FormView):
template_name = 'signup.html'
form_class = UserCreateForm
# Is here in the success_url in where I use reverse_lazy and I get
# the NoReverseMatch
success_url = reverse_lazy('accounts/profile')
#success_url = '/accounts/profile'
# Override the form_valid method
def form_valid(self, form):
# get our saved user with form.save()
saved_user = form.save()
user = authenticate(username = saved_user.username,
password = form.cleaned_data['password1'])
# Login the user, then we authenticate it
login(self.request,user)
# redirect the user to the url home or profile
# Is here in the self.get_success_url in where I get
# the NoReverseMatch
return HttpResponseRedirect(self.get_success_url())
My form class UserCreateForm in which I made the registration form is located in userprofiles/forms.py file and it's so:
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class UserCreateForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(UserCreateForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', u'Save'))
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username','email','password1','password2',)
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
And my template is the userprofiles/templates/signup.html file:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Register{% endblock %}
{% block content %}
<div>
{% crispy form %}
{% csrf_token %}
</div>
{% endblock %}
When I go to my register user form, and I pressed submit this save my user and I have it for that try redirect to profile of the user recent created, but I get this error
What may be happening to me in this case. Seem that the reverse_lazy does not work?
Any help will be appreciated :)
The reverse_lazy() function either takes view function or url name to resolve it not the url path. So you need to call it as
success_url = reverse_lazy('profile/')
#---------------------------^ use url name
However, I'm not sure if '/' character works in url name.
If you have to use path to resolve to an url, use resolve() function.