Django form won't render (modelForm) - django

I have an existing site, and I'm trying to render a form to it
I tried looping trough the form and rendering it field by field, but no luck. I think i might screwed up something in my views, im a beginner to django
HTML:
{%block wform%}
<form method="POST" class="form">
{% csrf_token %}
{{ form.as_p }}
<div class="form__group">
{%if user.is_authenticated%}
<input type="submit" class="submit" value="Submit Your Data">
{%else%}
Submit Your Data
{%endif%}
</div>
</form>
{%endblock wform%}
Forms.py
from django.forms import ModelForm
from users.models import Profile
class WeightForm(ModelForm):
class Meta:
model = Profile
fields = ['weight','height','goal']
Views.py
from django.shortcuts import render
from django.contrib import messages
from users import models
from users.models import Profile
from .forms import WeightForm
# Create your views here.
def home(request):
return render(request, 'Landing/index.html')
def formsave(request):
form = WeightForm()
return render(request, 'Landing/index.html', {'form': form})

from django.shortcuts import render
from django.contrib import messages
from users import models
from users.models import Profile
from .forms import WeightForm
# Create your views here.
def home(request):
form = WeightForm()
return render(request, 'Landing/index.html', {'form': form})

Related

Django - UserEditView is missing a QuerySet?

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'),

i want to scan out text from an image passed in a django form to tesseract ocr in views.py and pass result to html template

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)

Cannot assign "Note.user" must be a "User" instance. Django

I am getting the following error on running my django code. I am an absolute beginner and I was following a tutorial to create a crud app.
On typing the information in my html form I get the following error
ValueError: Cannot assign django.contrib.auth.models.AnonymousUser object at 0x00000288775D3EF0: "Note.user" must be a "User" instance
from form.instance.user = request.user in my views.py
views.py
from django.shortcuts import render
from django.shortcuts import render, redirect
from .models import Note
# Create your views here.
from .forms import NoteModelForm
# CRUD - create update retrieve and delete
def createView(request):
form = NoteModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('/')
context = {
'form': form
}
return render(request, "create.html", context)
forms.py
from django import forms
from .models import Note
class NoteModelForm(forms.ModelForm):
class Meta:
model = Note
fields = ['title','url','image']
create.html
<!DOCTYPE html>
<html>
<head>
<title>CRUD APP</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit">
</form>
</body>
</html>
If the user is not logged in, request.user gives AnonymousUser, which can't be assigned to the form instance.
To avoid this situation, you may add a condition before accessing the view. For this, you may use login_required decorator, as shown below
from django.contrib.auth.decorators import login_required
#login_required
def createView(request):
....

CSRF verification failed in Django project update, and RequestContext solution not working

I have a Django project in which trying to 'update' (clicking on the button) causes the following error:
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
I have viewed various questions and answers that suggest that adding RequestContext is the solution, but I have tried something to that effect tailored to my code, and still am unable to get it working.
Original code views.py is below
#USERS (register) view.py
from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages #this allows us flash messages for testing
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm
from .forms import UserUpdateForm
from .forms import ProfileUpdateForm
from django.contrib.auth.decorators import login_required
def register(request):
if request.method =='POST':
#this UserRegisterForm is created in forms.py and inherits from UserCreationForm (the ready made form)
form = UserRegisterForm(request.POST) #create a form that has the data that was in request.POST
if form.is_valid(): #is the form valid (do you have a username like this already, passwords match?
form.save()
username = form.cleaned_data.get('username')
messages.success(request,f'Account created for {username}, you can now login.')
return redirect('login')
else:
form =UserRegisterForm() #if the form input is invalid, render the empty form again
return render(request, 'users/register.html',{'form':form})
#login_required #this is a decorator (adds functionality to an existing function)
def profile(request):
if request.method =='POST':
u_form =UserUpdateForm(request.POST,instance=request.user)
p_form =ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request,f'Your Account has been directed')
return redirect('profile')
else:
u_form =UserUpdateForm(instance=request.user)
p_form =ProfileUpdateForm(instance=request.user.profile)
context={
'u_form': u_form,
'p_form': p_form
}
return render(request,'users/profile.html',context)
As mentioned I also tried:
return render(request,'users/profile.html',context_instance=RequestContext(request))
I also tried adding the below to imports
from django.shortcuts import get_object_or_404, render,redirect
Note: I do not wish to try the 'remove middleware' alternative.
The profile.html file code is below and I have included the CSRF token correctly, as far as I know:
{% extends "socialmedia/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
<form method="POST" enctype="multipart/form-data>
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Information</legend>
{{u_form|crispy}}
{{p_form|crispy}}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update....</button>
</div>
</form>
</div>
{% endblock content %}
Finally, for context, here is forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm): #form that inherits from the usercreationform
email = forms.EmailField()
class Meta:
model = User
#when this form validates it creates a new user
#type the fields to be shown on your form, in that order.
fields = ['username','email','password1','password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username','email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model= Profile
fields=['image']
Question: What is causing the error and what do I need to add/change in the code as it stands?
I also came across an answer on StackOverflow which said this "The problem is you are not returning the result. Remember that the view is a function. You need to return render_to_response(...) not just call it (which is also why by removing CSRF you got the didn't return an HttpResponse error)" ....can someone explain this in my context? I don't understand what it means or how to implement it either.
It looks like it should work, however I noticed you seem to be missing a quote at the end here
<form method="POST" enctype="multipart/form-data>

Want to create search field but error 'WSGIRequest' object has no attribute 'request'

I am doing a django project, a music app .It contains artist name,album title,genre and image. When I create a search form ,I get this error.I am using django version 1.9.1
view.py
from django.views import generic
from . models import Album
from django.views.generic.edit import CreateView , UpdateView ,DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate,login
from django.views.generic import View
from .forms import UserForm
from django.db.models import Q
def get_queryset(self):
query= self.request.GET.get('q')
if query:
return Album.objects.filter(Q(album_title__icontains=query))
else:
return Album.objects.all()
form.py
<form class="navbar-form navbar-left" method="GET" action="">
<div class="form-group">
<input type="text" class="form-control" name="q" value='{{ request.GET.q }}'>
</div>
<button type="submit" class="btn btn-default" >search</button>
</form>
url.py
#checking for search
url(r'^search/$', views.get_queryset, name='search'),
Image of error in browser:
get_queryset is not a View class, so the self argument is actually the request object.
To correct your problem you can simply do:
def get_queryset(request):
query= request.GET.get('q')
if query:
return Album.objects.filter(album_title__icontains=query)
else:
return Album.objects.all()
but I suggest to double check the docs about the views and the class-based views.