comment django errno 22 - python

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)

Related

TemplateSyntaxError at /: Cannot Parse the remainder

I am trying to update my homepage whenever a new "article" is added, however it is giving me this error whenever I try to update the page using my updateHomepage view it doesn't work and I get the error
TemplateSyntaxError at /
Could not parse the remainder: ' 'update_homepage'' from 'url 'update_homepage''
I am very new to django so any help with this would be amazing.
My Views.py
def index(request):
articles = Article.objects.all()
context = {'articles': articles}
return render(request, 'able/homepage.html', context)
def updateHomepage(request, pk):
form = EditorForm(instance=task)
context = {'form': form}
article = Editor.objects.get(id=pk)
return render(request, 'able/update_homepage.html', context)
if request.method == 'POST':
form = EditorForm(request.POST, instance=task)
if form.is_valid():
form.save()
return redirect('/')
def editorview(request):
editor = EditorForm
context = {'editor': editor}
return render(request, 'able/editor.html', context)
if request.method == 'POST':
form = EditorForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
urls.py
urlpatterns = [
path('', views.index, name='homepage'),
path('editor/', views.editorview),
path('update_homepage/<str:pk>/', views.updateHomepage, name='update_homepage')
]
homepage.html
<h1>My Blog</h1>
{% for article in articles %}
<div class="article">
{% csrf_token %}
<h1>{{ article.title }}</h1>
<h3>{{ article.text }}</h3>
</div>
{% endfor %}
Update
update_homepage.html
<h3>Update Homepage</h3>
<form action="" method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
</form>

While running on Server i am getting HTML code on my browser

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)

Context Not Printing Django

I'm aware my issue may be to lack of Django knowledge, but I'm trying to pass user input from one form in a view, to another view which will then render that view's HTML page with the given input.
I'm redirected fine, but the data is not being displayed. I believe it has something to do with the contexts not being passed properly, but I do not understand what is wrong or how to fix it.
views.py
def home_view(request, *args, **kwargs):
print(args, kwargs)
print(request.user)
if request.method == 'POST':
form2 = PostForm(request.POST)
if form2.is_valid():
post = form2.save(commit=False)
post.poster = request.user
post.content = form2.cleaned_data.get('content')
post.title = form2.cleaned_data.get('title')
post.syntax = form2.cleaned_data.get('syntax')
post.public = form2.cleaned_data.get('public')
rand = str(uuid.uuid4())[:6]
while Paste.objects.filter(generated_url=rand):
rand = str(uuid.uuid4())[:6]
post.generated_url = rand
form2.save()
context = {
"poster_name": post.poster,
"paste_contents": post.content,
"paste_title": post.title,
"paste_syntax": post.syntax,
"paste_visible": post.public
}
return HttpResponseRedirect(reverse('details', args=(post.generated_url,)), context)
else:
form2 = PostForm()
return render(request, "home.html", {'form2': form2})
def detail_view(request, *args, **kwargs):
if request.user.is_authenticated:
if request.method=='POST':
form3 = PostForm(request.POST)
url = form3.generated_url
your_posts = Paste.objects.get(url)
context = {
'form3': form3
}
return render(request, "paste_detail.html", context)
return render(request, "paste_detail.html", {'form3': form3})
home.html
{% extends "base.html" %}
{% block content %}
<h1>Your user is {{ request.user }}</h1>
<div class="submit_form">
<form action="" method="POST">
{% csrf_token %}
{{ form2.as_p }}<br>
<input type="submit" name="submit" value="Paste" id="submit">
</div>
{% endblock content %}
And paste_detail.html
{% extends "base.html" %}
{% block content %}
<!--<h1>Name of post: {{ post.title }}</h1>-->
<p>Content of post:</p>
I AM REDIRECTED
<h1>Name of post: {{ form2.title }}</h1>
<p>Content of post:</p>
<p>{{form3.content|linebreaks}}</p>
{{ form3.poster }}
{{ form3.contents }}
{{ form3.title }}
{{ form3.syntax }}
{{ form3.visible }}
{% endblock %}
edit:
views.py
def home_view(request, *args, **kwargs):
if request.method == 'POST':
form2 = PostForm(request.POST)
if form2.is_valid():
post = form2.save(commit=False)
post.poster = request.user
post.save()
rand = str(uuid.uuid4())[:6]
while Paste.objects.filter(generated_url=rand):
rand = str(uuid.uuid4())[:6]
post.generated_url = rand
# return HttpResponseRedirect(reverse('details', args=(post.generated_url,)), context)
return redirect('detail', rand)
else:
form2 = PostForm()
return render(request, "home.html", {'form2': form2})
def detail_view(request, custom_uuid):
post = get_object_or_404(Paste, pk=pk)
return render(request, "paste_detail.html", {'post': post})
#return render(request, "paste_detail.html", {'form3': form3})
paste_detail.html
{% extends "base.html" %}
{% block content %}
<p>Content of post:</p>
I AM REDIRECTED
<h1>Name of post: {{ post.title }}</h1>
<p>Creator of post:</p> {{ post.poster }}
<p>Content of post:</p> {{ post.content }}
<p>Title of post:</p> {{ post.title }}
{{ post.syntax }}
{{ post.visible }}
{% endblock %}
And urls.py
...
urlpatterns = [
path('home/', home_view, name='home'),
path('contact/', contact_view, name='contact'),
path('admin/', admin.site.urls, name='admin'),
path('about/', about_view, name='about'),
url(r'^signup/$', views.signup, name='signup'),
path('paste_list/', paste_list_view, name='paste_list'),
url(r'^$', home_view),
#url(r'^(?P<rand_url>\S{6})/$', detail_view, name='details'),
path('detail/<str:custom_uuid>/', detail_view, name='detail'),
path('accounts/', include('django.contrib.auth.urls')),
]
There are several problems in your code. Lets fix them one by one(Please check the code comments for explanation):
In home_view you are doing some redundant codes, you can simplify like this:
from django.shortcuts import redirect
...
if request.method == 'POST':
form2 = PostForm(request.POST)
if form2.is_valid():
post = form2.save(commit=False) # it is not saved in db
post.poster = request.user
rand = str(uuid.uuid4())[:6]
while Paste.objects.filter(generated_url=rand).exists():
rand = str(uuid.uuid4())[:6]
post.generated_url = rand
post.save() # it will save all information to DB, so you don't need to call form2.cleaned_data.get(..)
return redirect('details', custom_uuid=rand) # I am redirecting to `detail_view`. here `rand` is the random uuid of the post which is saved in db
else:
form2 = PostForm()
return render(request, "home.html", {'form2': form2}) # rendering form for GET request
Now lets update detail view to catch the redirection:
from django.shortcuts import get_object_or_404
def detail_view(request, custom_uuid):
post = get_object_or_404(Post, generated_url=custom_uuid) # getting the post object from database using model.
return render(request, "post_detail.html", {'post': post}) # sending data in context to template
# url
path('detail/<str:custom_uuid>/', detail_view, name='detail') # here <str:custom_uuid> will catch the uuid sent in the url
# HTML
{% extends "base.html" %}
{% block content %}
<p>Content of post:</p>
I AM REDIRECTED
<h1>Name of post: {{ post.title }}</h1> // <-- getting this context from view
<p>Content of post:</p>
<p>{{post.content|linebreaks}}</p>
{{ post.poster }}
{{ post.contents }}
{{ post.title }}
{{ post.syntax }}
{{ post.visible }}
{% endblock %}
Here get_object_or_404 gets the entry for model Post, if its not found then throws 404 error.
Contexts are per-request. Once your view has returned, the context no longer exists. When you do a redirect, you are finishing that request/response cycle and starting another one with your detail view. None of the context will carry over.
Instead, you need a way to store pertinent information between requests. One fairly simple way to do this is storing data in the session.
For example, you might store title in a session like this in home_view:
request.session['title'] = post.title
And then in your detail_view view, you could add it to your context:
context = {
'title': request.session.get('title')
}
Check out the Django documentation on sessions for more info: https://docs.djangoproject.com/en/2.1/topics/http/sessions/

CSRF verification failed. Request aborted. Django 2.0

def order_view(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('Order Submitted')
else:
form = OrderForm()
return render_to_response('home/order.html', {'form': form})
order_view function in views.py
<form class="form form-table" method="post">
{% csrf_token %}
{{ form|crispy }}
<input class="btn br-green" type="submit" value="Submit"/>
</form>
There is still a CSRF error in it. Have tried most of the solution but they are not working.Have tried adding RequestContext(request) as well.
HttpResponseRedirect takes a url. I don't think 'Order Submitted' is.
Try
def order_view(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
form.save()
else:
form = OrderForm()
return render_to_response('home/order.html', {'form': form})
If this works then you're sorted and use django.messages to provide the message to your user.

Can't add file in django 1.7

I cannot add a file in Django. When I click the "save" button, it does not save the database.
This is my view.py:
def add_product(request):
if request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.userprofile = request.user
post.save()
return redirect('kerajinan.views.add_product', pk=post.pk)
else:
form = PostForm()
return render(request, 'kerajinan/add_product.html', {'form': form})
add_product.html:
{% block content %}
<h1>New Product</h1>
<from method="POST" class="post-form" enctype="multiple/form-data">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</from>
{% endblock %}
forms.py:
class PostForm(forms.ModelForm):
class Meta:
model = Product
fields = ('category','title', 'price','image', 'description')
and urls.py:
url(r'^add_product/$', views.add_product, name='add_product'),
Can you help me solve my problem?
You need to change your enctype to: enctype="multipart/form-data"
Your current value (multiple/form-data), is not a valid method of encoding.
From the docs:
Note that request.FILES will only contain data if...the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

Categories