i am just a beginner and starting with some tutorials on web, i can not understand why this isn't working for me:
my views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
class MainPage(View):
def get(self, request):
return render_to_response("helloworld.html")
class TestHandler(View):
def post(self, request):
q = {}
q.update(csrf(request))
#return render_to_response('test.html', q)
return render_to_response('test.html', {'q':q}, context_instance=RequestContext(self.request))
def get(self, request):
q = self.request.GET.get('q')
return HttpResponse(q)
and my urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from views import MainPage, TestHandler
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^hello$', MainPage.as_view(), name='home'),
url(r'^testform/', TestHandler.as_view()),
url(r'^admin/', include(admin.site.urls)),
helloworld.html
>->-<html>
>->->-<head>
>->->->-<title>Hello, World!</title>
>->->-</head>
>->->-<body>
>->->->-<form method="post" action="/testform/" >
{% csrf_token %}
>->->-<input name="q">
<input type="submit">
</form>
>->->-</body>
>->-</html>
test.html
>-<body>
>-Hello {{q}}
>-</body>
This is running on django 1.6, I read most of post and still can't figure it out.
Unfortunately what you have pasted is a bit of a mess, you are using Class Based Views but yet you have mixed them with function based views (also half of the declarations are missing).
Enable the CSRF Middlware in your settings.py
MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
...
)
Fix your views to proper Class Based Views, what you have pasted is totally wrong:
from django.views.generic import CreateView, TemplateView
from django.core.urlresolvers import reverse_lazy
# Create the form in your forms.py
from .forms import (
MyTestForm,
)
class MainPage(TemplateView):
template_name = "test.html"
class TestHandler(CreateView):
form_class = MyTestForm
template_name = "helloworld.html"
success_url = reverse_lazy('home')
Create your form template:
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<form method="post" action="/testform/">
{% csrf_token %}
<input name="q">
<input type="submit">
</form>
</body>
</html>
Related
trying to create an edit profile for users and i keep getting this error what should i add or change ? is my models right for UserEditView
this is my views.py (all of it edited)
maybe the vendor its not compatitable with User edit view
anything elses needs to be added or should i just change something
all imports are for vendor and UserEditView
from tkinter import Entry
from django.contrib.auth.models import User
from xml.dom.minidom import Entity
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth.forms import UserCreationForm , UserChangeForm
from django.utils.text import slugify
from django.shortcuts import render, redirect
from .models import Profile, Vendor
from products.models import Product
from .forms import ProductForm
# Create your views here.
def become_vendor(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
vendor = Vendor.objects.create(name=user.username, created_by=user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'vendor/become_vendor.html', {'form': form})
#login_required
def vendor_admin(request):
context = {
'user':request.user
}
vendor = request.user.vendor
products = vendor.products.all()
return render(request,'vendor/vendor_admin.html',{'vendor': vendor , 'products': products ,'context':context})
#login_required
def add_house(request):
if request.method == 'POST':
form = ProductForm (request.POST, request.FILES)
if form.is_valid():
product = form.save(commit=False)
product.vendor = request.user.vendor
product.slug = slugify(product.عنوان)
product.save()
return redirect('vendor_admin')
else:
form = ProductForm()
return render(request,'vendor/add_house.html',{'form': form})
class UserEditView(generic.UpdateView):
models = User
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
seccess_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
urls.py
from django.urls import path
from .import views
from .views import UserEditView
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpattern =[
path('signup/', views.become_vendor, name='become_vendor'),
path('profile/', views.vendor_admin, name='vendor_admin'),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path('login/', auth_views.LoginView.as_view(template_name='vendor/login.html'), name='login'),
path('edit_profile/', UserEditView.as_view(template_name='vendor/edit_profile.html'), name='edit_profile'),
]
edit_profile.html
(where the error pops up)
{% extends "base.html"%}
{% load static %}
{% block content %}
<title>title</title>
<div class="section pt-9 pb-9">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-title">
<div class="wrap-title">
<h3 class="title">
<span class="first-word"></span>
</h3>
<br>
<form method="post" >
{% csrf_token %}
<table>
{{ form.as_p }}
</table>
<button class='button'>Update</button>
</form>
</div>
<hr>
{% endblock content %}
I think that you didn't declare your model correctly:
class UserEditView(generic.UpdateView):
# models = UserChangeForm #That has no sense.
model = User #The name of your model (Probably the default one: User).
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
success_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
Other thing. You have declared your template name twice. According to your views.py you can delete the template_name on your urls.py:
path('edit_profile/', UserEditView.as_view(), name='edit_profile'),
iam using django framework and i want to scan out text from an image passed in a form to tesseract ocr in views.py and pass result to html template.
Iam still challenged on how to read this image from the form without sending it to the database.
I request for your assistance
iam using django 4.0.2 in a virtual environment
my python version is 3.10.2
My forms.py
from django import forms
class uploadform(forms.Form):
first_name= forms.CharField(max_length=100)
image= forms.ImageField(max_length=100)
My html template
{% extends 'hm.html' %}
{% block content %}
<br>
<h1>Here you are able to make Uploads</h1>
<form class="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p}}
{{text}}
<button type="submit" name="button" class='btn btn-primary'>Upload your image</button>
</form>
<p>{{imge}}</p>
{{k}}
{{h}}
{% endblock %}
My urls.py file is
from django.contrib import admin
from django.urls import path, include
from scannerapp import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home_view,name='home'),
path('new/',views.upload, name="uppath"),
]
if settings.DEBUG:#This is just for development purposes, dont use it in production
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
my views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse,JsonResponse
from django.views.generic import FormView
from .forms import uploadform
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import FileSystemStorage
import json
import pytesseract
from PIL import Image
def upload(request):
form= uploadform()
first_name=""
myimg=""
context={'form': form}
if request.method == 'POST'and form.is_valid=="True":
submitbutton= request.POST.get("submit")
t="am request Post is passed"
#if form.is_valid():
p="form validation is passed"
form= uploadform(request.POST or request.FILES)
first_name= form.cleaned_data.get("first_name")
myimg= form.cleaned_data.get("image")
print(first_name)
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
#mym=Book._meta.get_field('cover')
text = pytesseract.image_to_string(mym, lang='eng')
#redirect('home')
context={'form': form, 'firstname': first_name,'imge':myimg, 'k':t,'h':text}
return render(request,'new.html',context)
I'm getting a NoReverseMatch error in my home page. It is from the html that I injected from my announcement app. It says that the reverse of the link is cannot be found. When I removed that line It shows the card but the text with template tag.
_announcement_home.html:
<div class="container">
<div class="card announcement-card" style="width: 18rem;">
<h5 class="card-header">Announcement</h5>
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
</div>
<br>
</div>
index.html:
{% extends 'base.html' %}
{% block content %}
<div class="w3-container w3-teal">
<h1>BANNER HERE</h1>
<p>Dito yung banner</p>
</div>
{% include 'announcement/_announcement_home.html' %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
app_name = 'announcement'
urlpatterns = [
path('create/', views.AnnouncementCreateView.as_view(), name='create'),
path('', views.AnnouncementListView.as_view(), name='list'),
path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'),
path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'),
path('edit/<int:pk>/', views.AnnouncementUpdateView.as_view(), name='edit')
]
main urls.py:
"""urcipro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from home import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Home.as_view(), name='home'),
path('bod/', views.BOD.as_view(), name='bod'),
path('announcement/', include('announcement.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from . import forms
from . import models
# Create your views here.
class AnnouncementListView(LoginRequiredMixin, generic.ListView):
model = models.Announcement
class AnnouncementDetailView(LoginRequiredMixin, generic.DetailView ):
model = models.Announcement
class AnnouncementUpdateView(LoginRequiredMixin, generic.UpdateView):
model = models.Announcement
form_class = forms.AnnouncementForm
class AnnouncementCreateView(LoginRequiredMixin, generic.CreateView ):
model = models.Announcement
form_class = forms.AnnouncementForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class AnnouncementDeleteView(LoginRequiredMixin, generic.DeleteView ):
model = models.Announcement
def get_success_url(self):
return reverse('home')
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
home app views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
class Home(TemplateView):
template_name = 'index.html'
class BOD(TemplateView):
template_name = 'bod.html'
This is what I see when I remove the a tag:
Error traceback:
It looks like the context has announcement to display this information, and then you used self in the url tag which isn't defined.
So change the url param to announcement.pk which we can assume will exist because that's the object in use with this block.
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
I am very puzzled as to why the URL dispatcher is try to look for an empty path although a url was specified for it? Does it imply that it is unable to find the specified url and therefore trying to find the default.
This happens when I try to POST and HttpResponseRedirect searches for an empty path instead of following the specified path. Assume that the other.
Using Django version: 2.0
Thanks in advance!
main/urls.py (ROOT_URLCONF)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/', include('shorterner.urls'))
]
shorterner/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('request/', views.RequestView.as_view(), name="request"),
path('list/', views.IndexView.as_view(), name="list")
]
shorterner/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.conf import settings
from django.urls import reverse
from django.views import View, generic
from .models import Urls
import requests
import json
from .forms import SubmitUrlForm
class RequestView(View):
form_class = SubmitUrlForm
initial = { 'url': ''}
template_name = "shorterner/request.html"
context_object_name = 'url'
def form_valid(self, form):
return super().form_valid(form)
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
input_url = form.cleaned_data['url']
short_url = google_url_shorten(input_url)
print(input_url)
print(short_url)
new_url = Urls.create(short_url, input_url)
new_url.save()
return HttpResponseRedirect('/app/request/')
return render(request, self.template_name, {'form': form})
shorterner/templates/shorterner/request.html
{% extends 'shorterner/base.html' %}
{% block content %}
<form action="/" method="POST">
{% csrf_token %}
<input type="text" name="url" placeholder="Url..." required/>
<input type="submit" value="Submit"/>
</form>
{% endblock %}
Screenshot of the problem
Error Page
Looks like you're sending form data to this path /. But you've not defined that route in main/urls.py.
#### model using ModelForm: models.py
from django.db import models
from django.forms import ModelForm
class customers(models.Model):
name = models.CharField(max_length=50)
custAdd = models.TextField()
class Meta:
db_table = 'tb_amit_test'
ordering = ['-name']
verbose_name_plural = 'customers'
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('customers_customers', (), { 'customers_name': self.name })
class customerForm(ModelForm):
class Meta:
model=customers
#### View:views.py
from django.shortcuts import render_to_response
from mtcc_customer_db import customers
from mtcc_customer_db import customerForm
from django.template import RequestContext
def adddata(request):
if request.method == 'POST':
f=custform(request.POST)
if f.is_valid():
newcust=f.save(commit=False)
newcust.save()
return HttpResponseRedirect('/')
return render_to_response('index.html',
context_instance=RequestContext(request))
#### URLs:
from django.conf.urls import patterns, include, url
from mtcc_customer_db import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),)
urlpatterns +=patterns('mtcc_customer_db.customers.views',
(r'^customers/$', 'adddata'),)
### Template: customer.html
{% extends "base.html" %}
{% block site_wrapper %}
<div id="main">
{% include "tags/navigation.html" %}
Skip to main content
<form action="." method="post">
<input type="text" name="name" id="name" value="{{name}}">
<input type="text" name="custAdd" id="custAdd" value="{{custAdd}}">
<input type="submit" value="Submit">
</form>.........
{% endblock %}
I am getting the error in the browser:
Request Method: GET
Request URL: someaddress.customers/
Django Version: 1.4.3
Exception Type: ImportError
Exception Value:
--->>cannot import name customerForm
Where am i going wrong?? Please help
Try this:
from your_module_name.models import customerForm
in your views.py file
The form is in models.py (*), so you should be doing from mtcc_customer_db.models import customerForm.
(*) note that it should probably be in forms.py anyway, but still.