django - file upload fails when its being opened from a template using {% include "file_upload.html%" %} - django-views

When uploading a file by opening the file_upload.html template directly which contains the html form the server gives the following message:
[13/Nov/2022 08:00:54] "POST /upload_view/ HTTP/1.1" 200 948 and I see the file in the media root folder.
When doing the same thing but opening up index.html which uses {% include %} to bake in the file_upload.html I see this:
[13/Nov/2022 08:02:59] "POST / HTTP/1.1" 200 1538 and **no** uploaded file in media root folder.
Any ideas of what I'm doing wrong here?
My views:
def index_view(request, *args, **kwargs):
return render(request, "index.html", {})
def upload_view(request, *args, **kwargs):
if request.method == 'POST':
user_file = request.FILES['filename']
stored_file = FileSystemStorage()
stored_file.save(user_file.name, user_file )
return render(request, "file_upload.html", {})
my templates:
index.html
{% extends "base_template.html" %}
{% block content %}
<p>this is a test</p>
{% include "file_upload.html" %}
{% endblock %}
file_upload.html
{% block content %}
<p>Upload</p>
<form method="POST" enctype="multipart/form-data">
<!--cross site request forgery documentation https://docs.djangoproject.com/en/4.1/ref/csrf/-->
{% csrf_token %}
<input type="file" name="filename">
<button type="submit"> Upload file</button>
</form>
{% endblock %}
URL patterns in urls.py module:
urlpatterns = [
path('admin/', admin.site.urls),
path('', index_view, name='index'),
path('index/', index_view, name='index'),
path('upload_view/', upload_view, name='fileupload'),
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('static/favicon/favicon.ico')))

I solved it by adding the line upload_view(request) to my index_view:
def index_view(request, *args, **kwargs):
upload_view(request)
return render(request, "index.html", {})

Related

TemplateDoesNotExist at /wiki/CSS/edit_entry error in djano

I have tried other answers in StackOverflow, but didn't find a solution.
I have a function that edits the page content:
def edit_entry(request, title):
content = util.get_entry(title)
if request.method == 'POST':
form = AddForm(request.POST)
if form.is_valid():
title = form.cleaned_data["title"]
util.save_entry(title, content)
return redirect('edit_entry', title)
return render(request, "encyclopedia/edit_entry", {
"title": title,
"content": content
})
My urls.py looks like:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:title>", views.entry, name="entry"),
path("search", views.search, name="search"),
path("add_entry", views.add_entry, name="add_entry"),
path("wiki/<str:title>/edit_entry", views.edit_entry, name="edit_entry")
]
Here is my edit_html template:
{% extends "encyclopedia/layout.html" %}
{% block title %}
Edit page
{% endblock %}
{% block body %}
<form action="{% url 'edit_entry' title %}" method="POST">
{% csrf_token %}
{{ title }}
{{ content }}
<input type="submit" value="Save Editing">
</form>
{% endblock %}
As you see, the template exists here:
But it says TemplateDoesNotExist at /wiki/CSS/edit_entry
The template belongs to my application, so, I guess, no need to add it to DIRS = [], which is located in settings.py. And other routes except this one are working fine.
Replace
return render(request, "encyclopedia/edit_entry", {
"title": title,
"content": content
})
with
return render(request, "encyclopedia/edit_entry.html", {
"title": title,
"content": content
})
Your template should have the full file name edit_entry.html

password_reset email template doesn't render html tag

I'm trying to override content for default password_reset_email.html with some html tag but it doesn't work. Here is my modification. For testing purpose, I'm just using p tag. But i doesn't work. I'm totally unaware what going wrong.
Here is my process.
urls.py
path('accounts/', include('django.contrib.auth.urls')),
and here is my html templates
{% load i18n %}
{% autoescape on %}
{% blocktrans %}You're receiving this email because you requested a password reset for your user account at
{{ site_name }}.{% endblocktrans %}
{% trans "Please go to the following page and choose a new password:" %}
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
{% endblock %}
<p>Hello world</p>
{% trans 'Your username, in case you’ve forgotten:' %} {{ user.get_username }}
{% trans "Thanks for using our site!" %}
{% blocktrans %}The {{ site_name }} team{% endblocktrans %}
{% endautoescape %}
and here is the output
The email_template_name is standard one that is send in raw text, not in HTML. Indeed, in the PasswordResetView we see:
class PasswordResetView(PasswordContextMixin, FormView):
email_template_name = 'registration/password_reset_email.html'
extra_email_context = None
form_class = PasswordResetForm
from_email = None
html_email_template_name = None
subject_template_name = 'registration/password_reset_subject.txt'
success_url = reverse_lazy('password_reset_done')
template_name = 'registration/password_reset_form.html'
title = _('Password reset')
token_generator = default_token_generator
#method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def form_valid(self, form):
opts = {
'use_https': self.request.is_secure(),
'token_generator': self.token_generator,
'from_email': self.from_email,
'email_template_name': self.email_template_name,
'subject_template_name': self.subject_template_name,
'request': self.request,
'html_email_template_name': self.html_email_template_name,
'extra_email_context': self.extra_email_context,
}
form.save(**opts)
return super().form_valid(form)
In case you thus alter the registration/password_reset_email.html, it will still send the email as raw text, so an email client will render it as raw text.
What you can do is simply make a new path that takes precedence, and where you override the html_email_template_name:
# urls.py
urlpatterns = [
path('accounts/password_reset/',
views.PasswordResetView.as_view(
html_email_template_name='registration/password_reset_email.html'
),
name='password_reset'
),
path('accounts/', include('django.contrib.auth.urls')),
# …
]
It is important that this path appears before the path that includes the django.contrib.auth.urls, since otherwise it will still take the "old" path.
This is just 5 letters to be added, and boom..!! you work will done.
change---
urls.py
patterns = [
path('accounts/password_reset/',
views.PasswordResetView.as_view(
email_template_name='registration/password_reset_email.html'
),
name='password_reset'
),
path('accounts/', include('django.contrib.auth.urls')),
# …]
to--
patterns = [
path('accounts/password_reset/',
views.PasswordResetView.as_view(
html_email_template_name='registration/password_reset_email.html'
),
name='password_reset'
),
path('accounts/', include('django.contrib.auth.urls')),
# …]

Reverse for 'register' not found. 'register' is not a valid view function or pattern name

I'm trying to make a simple app that uses the django built-in User model. I have created a registration page, but when I run the server, I get this error at the index page. Here's the code I'm using:
Registration.html
<!DOCTYPE html>
{% extends "basic/base.html" %}
{% block title_block %}
<title>Registration</title>
{% endblock title_block %}
{% block body_block %}
<div class="jumbotron">
{% if registered %}
<h1>Thank you for registering</h1>
{% else %}
<h1>Register here!</h1>
<h3>Fill out the form: </h3>
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{userForm.as_p}}
{{profileForm.as_p}}
<input type="submit" value="Register" name="">
</form>
{% endif %}
</div>
{% endblock body_block %}
Views.py for the 'register' method
def register(request):
registered = False
if(request.method == 'POST'):
userForm = forms.UserForm(data=request.POST)
profileForm = forms.UserProfileInfoForm(data=request.POST)
if((userForm.is_valid()) and (profileForm.id_valid())):
user = userForm.save()
user.set_password(user.password)
user.save()
profile = profileForm.save(commit=False)
profile.user = user
if('profileImage' in request.FILES):
profile.profileImage = request.FILES['profileImage']
profile.save()
registered = True
else:
print(userForm.errors, profileForm.errors)
else:
userForm = forms.UserForm()
profileForm = forms.UserProfileInfoForm()
return render(request, 'basic/registration.html', {'userForm':userForm, 'profileForm':profileForm, 'registered':registered})
This is the urls.py for the project
from django.contrib import admin
from django.urls import path, include
from basic import views
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
path('basic/', include('basic.urls', namespace='basic'))
]
This is the urls.py for the basic app
from django.urls import path
from . import views
app_name = 'basic'
urlpatterns = [
path('register/', views.register)
]
And the link to the page in base.html
<a class="nav-link" href="{% url 'basic:register' %}">Register</a>
What can cause the error here?
You must include a name argument to the register route.
path('register/', views.register, name='register')
https://docs.djangoproject.com/en/2.1/topics/http/urls/#reverse-resolution-of-urls
try this (inside your html file)
<a class="nav-link" href={% url 'basic:register' %}>Register</a>
and your urls.py (inside your app) as this:
urlpatterns = [
path('register/', views.register,name='register'),
]
this method worked for me I was fasing the same issue.

Django: Can't display data from an abstract model in template

I'm trying to display data from table(Tornillos) that inherits from table (articulos. abstract table) i want to get the value from sistema to display on my template.
My views.py
# def tipo_medicion(request, id):
def tipo_medicion(request):
template = 'inventario/sistema.html'
try:
sis = Tornillo.objects.values('sistema').distinct()
print(sis)
except Tornillo.DoesNotExist:
raise Http404()
#return render(request, template, { sis:'sis', id:'id' })
return render(request, template, { sis:'sis' })
My Server terminal screen:
[11/Jun/2018 23:55:10] "GET /sistema-medicion/2 HTTP/1.1" 200 761
<QuerySet [{'sistema': 'MM'}, {'sistema': 'STD'}]>
[11/Jun/2018 23:55:10] "GET /sistema-medicion/2 HTTP/1.1" 200 761
My Template:
{% extends 'inventario/base.html' %}
{% block content %}
<div class="container">
<h1 class="tag">SISTEMA</h1>
<ul>
{% for s in sis %}
<li>{{s.sistema}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
I'am struggling with an other issue i don't understand the concept yet for urlconf. currently my url for this view is static, i have tried with and get an inspected value error
My urls.py
app_name = 'inventario'
urlpatterns = [
path('', views.index, name='index' ),
path('categorias/', views.categorias, name='categorias'),
path('sistema-medicion/2', views.tipo_medicion, name='medicion')
#path('sistema-medicion/<int:id>', views.tipo_medicion, name='medicion')
]
you have reversed the key with the value in your dictionary
def tipo_medicion(request):
...
return render(request, template, { 'sis':sis })
urls.py
path('sistema-medicion/<int:pk>/', views.tipo_medicion, name='medicion')

Getting csrfmiddleware token in url

I am getting csrf token in the url after submitting my form like this.
http://127.0.0.1:8000/detail/?csrfmiddlewaretoken=lqvoeSG32IcodLTFksWEU1NPQ9XCmHybwmzMKEuPzxDN1e73B0JORpAGOcGGxsjH&symbol=FLWS
After making a GET request to view, the url is showing the csrf token in the url.
/views.py
def search(request):
if(request.method=='GET'):
form=searchform(request.GET)
if(form.is_valid()):
id=request.GET['symbol']
data=company.objects.filter(Symbol=id)
form=searchform()
return render(request, 'list-company.html',{"data":data,"form":form})
/urls.py
from django.contrib import admin
from django.urls import path
from csv2db.views import Company,search
urlpatterns = [
path('admin/', admin.site.urls),
path('company/',Company,name='company-details'),
path('detail/',search,name='search')
]
form in HTML file
{% block content %}
<form method="get" action="{% url 'search' %}">
{% csrf_token %}
{{ form.as_ul}}
<button type="Submit">Submit</button>
</form>
You are adding csrf_token template tag in the HTML file and form method is set to get. So data is appended as query parameters including csrf token.
So you can either change it to post method or remove the csrf_token template tag.
{% block content %}
<form method="POST" action="{% url 'search' %}">
{% csrf_token %}
{{ form.as_ul}}
<button type="Submit">Submit</button>
</form>
and change your view
def search(request):
form=searchform()
if(request.method=='POST'):
form=searchform(request.POST)
if(form.is_valid()):
id=request.GET['symbol']
data=company.objects.filter(Symbol=id)
form=searchform()
return render(request, 'list-company.html',{"data":data,"form":form})
return render(request, 'list-company.html',{"form":form})