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})
Related
I'm having problems deleting a user, where the authenticated user can delete their own account.
But what happens is that the page just refreshes, in the same template and returning '200 ok from POST'
[06/Aug/2022 11:46:33] "POST /members/profile/ HTTP/1.1" 200 4998
members.views.profiles.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
#login_required(login_url="/accounts/login/")
def profile(request):
template_name = "members/profile.html"
context = {}
return render(request, template_name, context)
def profile_delete(request, pk):
user_profile = User.objects.filter(pk=pk)
template_name = "members/profile_delete.html"
context = {
"user_profile": user_profile,
},
if request.method == "POST":
user_profile.delete()
return render(request, template_name, context)
return render(request, template_name, context)
members.urls.py
from django.urls import path
from allauth.account import views as allauth_views
from . import views
app_name = "members"
urlpatterns = [
path("login/", allauth_views.LoginView.as_view(), name="login"),
path("logout/", allauth_views.LogoutView.as_view(), name="logout"),
path("profile/", views.profile, name="profile"),
path("profile/<int:pk>/delete/", views.profile_delete, name="profile_delete"),
]
profile.html
<div>
<form method="POST">
{% csrf_token %}
<p>Are you sure you want to delete <strong>{{ user | title }}</strong> ?</p>
<button class="btn btn-danger" href="{% url 'members:profile_delete' user.pk %}" type="submit">
Delete
</button>
</form>
</div>
Solution:
views.py
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
#login_required(login_url="/accounts/login/")
def profile(request):
template_name = "members/profile.html"
context = {}
return render(request, template_name, context)
def profile_delete(request, pk):
user_profile = get_object_or_404(User, pk=pk)
user_profile.delete()
template_name = "members/profile_delete.html"
context = {}
return render(request, template_name, context)
When you're pressing your button the server sends a GET request, try changing the logic in your function, instead of:
if request.method == "POST":
Use:
if request.method == "GET":
You should use get_object_or_404 for querying single user's profile and then delete it, currently filter() makes no sense, so:
user_profile=get_object_or_404(User,pk=pk)
Note: you should always return HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it's a good web practice in general.
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.
So, I have a code below:
newEra/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include('mentor.urls')),]
mentor/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.home_page),
]
my views.py
from django.shortcuts import render,redirect
from .models import *
from .forms import *
def home_page(request):
todo = ToDo.objects.all()
form = ToDoForms()
if request.method == 'POST':
form = ToDoForms(request.POST)
if form.is_valid():
form.save()
return redirect('')
context = {'todo' : todo, 'form':form}
return render(request, 'home.html',context)
home.html
<h1>To-Do list</h1>
<form action="POST" method="/">
{% csrf_token %}
{{form.name}}
<input type="submit" value="Create task" >
</form>
<ul>
{% for to in todo %}
<li>{{ to }}</li>
{% endfor %}
</ul>
But I am getting this error below
**Using the URLconf defined in NewEra.urls, Django tried these URL patterns, in this order:
admin/
The current path, POST, didn't match any of these.**
'mentor' file added to the SETTINGS
URLs are regexes.
Try:
urlpatterns = [
path('^/$',views.home_page),
]
When i'm submitting a jpg image then it refreshes and shows 'This field required'validation error,so in views i tried to print(request.POST),it shows csrfmiddlewaretoken and pic in console but field validation is getting violated. Please correct me.
models.py
from django.db import models
class picture(models.Model):
pic = models.ImageField(upload_to='documents/')
forms.py
from django import forms
from .models import picture
class pictureForm(forms.ModelForm):
class Meta:
model = picture
fields = ['pic',]
views.py
from django.shortcuts import render,redirect
from .models import picture
from .forms import pictureForm
# Create your views here.
def pictureView(request):
if request.method == 'POST':
print(request.POST)
form = pictureForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = pictureForm()
return render(request,'home.html',{'form':form})
urls.py(APP level urls)
from django.urls import path
from . import views
urlpatterns = [
path('',views.pictureView, name = 'home')
]
urls.py(Directory level urls)
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('post.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Media files
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
template
<form method="post">
{% csrf_token %}
{{form.as_p}}
<input value="submit" type="submit">
</form>
based on the doc: uploaded-files-with-a-model
you should initialize your form:
form = pictureForm(request.POST, request.FILES)
and in the template you need add enctype="multipart/form-data"
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input value="submit" type="submit">
</form>
I have been given an assignment to load the contents of a CSV file and display the content in a mobile application using Python and Django. I am relatively new to Python and Django. I know of the Django REST framework. But how do I go about with it? Please do let me know
EDIT:
This is the code I have so far. I have been trying to upload the CSV file and trying to parse the file after that.
views.py
from django.shortcuts import render
import csv
import codecs
# Create your views here.
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from items.models import UploadFileForm
def handle_files(f):
reader = csv.DictReader(open(f))
for row in reader:
print row
def home(request):
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_files(request.FILES['csv_file'])
return HttpResponseRedirect('/workflow/')
else:
print form.errors
print request.FILES
return HttpResponseRedirect('/workflow/upload')
else:
form = UploadFileForm()
return render(request, 'template.html', {'formset': form})
template.html
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="file" name="csv_file" />
<input type="submit" value="Upload" />
</form>
forms.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
items/urls.py
from django.conf.urls import url
from django.contrib import admin
from items import views
from . import views
urlpatterns = [
#url(r'^admin/', admin.site.urls),
url(r'^$', views.home , name='home'),
]
customer-data/items/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
#url(r'^admin/', admin.site.urls),
url(r'^admin/', admin.site.urls),
url(r'^home/', include('items.urls')),
]