Django framework python - django

I'm making a registration system for students in Django
When the user enters the student number, the system retrieves all the student data.
How can I work in this
def search(request):
if request.method== 'POST':
srch = request.POST['srh']
if srch:
match = Regiest_Form.objects.filter(Q(std_name__iexact=srch))
if match:
return render(request, 'Regiest_app/search.html', {'sr':match})
else:
messages.error(request,'no result')
else:
return HttpResponseRedirect('/search/')
else:
return render(request, 'Regiest_app/search.html')

Wow, you're missing a whole part of django's purpose.
Using django's form, you can delegate all your validation to your form.
If no results are found, your access errors using 'form.errors' and 'form.non_field_errors` within your template.
In forms.py
from django import forms
from .models import Regiest_Form
class RegisterSearchForm(forms.Form):
search=forms.Charfield(required=True)
def clean(self):
qs=Regiest_Form.objects.filter(Q(std_name__iexact=self.cleaned_data.get('search'))
if qs.exists():
self.add_error(field=None,error=forms.ValidationError("No results found"))
else:
return self.cleaned_data
#property
def results(self):
return Regiest_Form.objects.filter(Q(std_name__iexact=self.cleaned_data.get('search'))
In your views.py
from .forms import RegisterSearchForm
def search(request):
form = RegisterSearchForm(request.POST) if request.method== 'POST' else RegisterSearchForm()
if request.method== 'POST' and form.is_valid():
return render(request, 'Regiest_app/search.html',{'sr':forms.results, 'form':form})
return render(request, 'Regiest_app/search.html',{'form':form})

Related

Chained dropdown validation error. Form works

Creating a chained drop down following a tutorial. Everything works fine but it is throwing an unnecessary validation error.
It is a basic 3 field form creating a person object with name, country and city.
Views.py
from django.shortcuts import render, redirect, get_object_or_404
from .forms import CustomerForm
from .forms import PersonCreationForm
from .models import Person, City
def store(request):
form = CustomerForm()
context = {'form': form}
return render(request, 'store/store.html', context)
def cart(request):
form = CustomerForm()
context = {'form': form}
return render (request, 'store/cart.html', context)
def checkout(request):
form = CustomerForm()
context = {'form': form}
return render(request, 'store/checkout.html', context)
def signup(request):
context = {}
return render(request, 'store/signup.html', context)
def home(request):
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
pass # does nothing, just trigger the validation
else:
form = CustomerForm()
return render(request, 'shop.html', {'form': form})
def person_create_view(request):
form = PersonCreationForm()
if request.method =='POST':
form = PersonCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('person_add')
return render(request, 'store/ho.html', {'form': form})
def person_update_view(request, pk):
person = get_object_or_404(Person, pk = pk)
form = PersonCreationForm(instance = person)
if request.method == 'POST':
form = PersonCreationForm(request.POST, instance=person)
if form.is_valid():
form.save()
return redirect('person_change', pk = pk)
return render(request, 'store/ho.html', {'form': form})
#ajax
def load_cities(request):
country_id = request.GET.get('country_id')
cities = City.objects.filter(country_id = country_id)
return render(request, 'store/city_dropdown_list_options.html',{'cities':cities})
Forms.py
from django.forms import ModelForm
from .models import Customer, Person, City
from django import forms
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = '__all__'
class PersonCreationForm(forms.ModelForm):
class Meta:
model = Person
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['city'].queryset = City.objects.none()
if 'country' in self.data:
try:
country_id = int(self.data.get('country'))
self.fields['city'].queryset = City.objects.filter(country_id = country_id)
except(ValueError, TypeError):
pass
elif self.instance.pk:
self.fields['city'].queryset = self.instance.country.city_set.order_by('name')
In forms.py line 14 where it says-
self.fields['city'].queryset = City.objects.none()
this line is throwing a validation error when I try to submit the form. In the tutorial they add the if/else argument and that solves the problem and error goes away.
error: "Select a valid choice. That choice is not one of the available choices"
In my case the error still shows up. If I ignore it and re select the city and submit, it works just fine.
It is almost like having a pause at that line and the system suddenly realizes that there is more code.
How do I fix this problem. Appreciate any help.

Can we use instance in the form?

hello guys i am working on form i didint find how to get instance in the form. This is not a model form
def form(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
else:
form = Form()
return render(request, 'app/form.html', {'form': form})
You should have a form class something like below:
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Now To handle the form we need to instantiate it in the view for the URL where we want it to be published:
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
# process the data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Refer the Django documentation for more details.
https://docs.djangoproject.com/en/3.0/topics/forms/

Django - The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead

I am building an customer management app and have built few decorator's. but when i run the app give this error
The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead.
decorators.py
from django.http import HttpResponse
from django.shortcuts import redirect
def unauthenticated_user(view_func):
def wrapper_func(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('home')
elif request.user.is_authenticated == None:
return redirect('login')
else:
return view_func(request, *args, **kwargs)
return wrapper_func
def allowed_users(allowed_roles=[]):
def decorator(view_func):
def wrapper_func(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group in allowed_roles:
return view_func(request, *args, **kwargs)
else:
return HttpResponse('You are not authorized to view this page')
return wrapper_func
return decorator
def admin_only(view_func):
def wrapper_function(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'customer':
return redirect('user-page')
if group == 'admin':
return view_func(request, *args, **kwargs)
return wrapper_function
and my views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from .models import *
from .forms import OrderForm, CreateUserForm, CustomerForm
from .filters import OrderFilter
from .decorators import unauthenticated_user, allowed_users, admin_only
# Create your views here.
#unauthenticated_user
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user =form.save()
username = form.cleaned_data.get('username')
messages.success(request,'Account was created for '+ username)
return redirect('login')
context = {'form':form}
return render(request,'accounts/register.html',context)
#unauthenticated_user
def loginPage(request):
if request.method == 'POST':
username=request.POST.get('username')
password=request.POST.get('password')
user = authenticate(request,username=username, password=password)
if user is not None:
login(request,user)
return redirect('home')
else:
messages.info(request, 'Username or password or incorrect')
context = {}
return render(request,'accounts/login.html',context)
def logoutUser(request):
logout(request)
return redirect('login')
#admin_only
#login_required(login_url='login')
def home(request):
orders = Order.objects.all()
customers = Customer.objects.all()
total_customer = customers.count()
total_orders = orders.count()
delivered = orders.filter(status='Delivered').count()
pending = orders.filter(status='Pending').count()
context = {'orders':orders,'customers':customers,'total_orders':total_orders,'delivered':delivered,'pending':pending}
return render(request, 'accounts/dashboard.html',context)
#login_required(login_url='login')
#allowed_users(allowed_roles=['customer'])
def userPage(request):
orders = request.user.customer.order_set.all()
total_orders = orders.count()
delivered = orders.filter(status='Delivered').count()
pending = orders.filter(status='Pending').count()
context = {'orders':orders,'total_orders':total_orders,'delivered':delivered,'pending':pending}
return render(request, 'accounts/user.html',context)
#login_required(login_url='login')
#allowed_users(allowed_roles=['customer'])
def accountSettings(request):
customer = request.user.customer
form = CustomerForm(instance=customer)
if request.method == 'POST':
form = CustomerForm(request.POST, request.FILES,instance=customer)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'accounts/account_settings.html', context)
#login_required(login_url='login')
#allowed_users(allowed_roles=['admin'])
def product(request):
products = Product.objects.all()
return render(request, 'accounts/products.html', {'products': products})
#login_required(login_url='login')
#allowed_users(allowed_roles=['admin'])
def customer(request,pk_test):
customer = Customer.objects.get(id=pk_test)
orders = customer.order_set.all()
order_count = orders.count()
myFilter = OrderFilter(request.GET, queryset=orders)
orders = myFilter.qs
context = {'customer':customer,'orders':orders,'order_count':order_count,'myFilter':myFilter}
return render(request, 'accounts/customer.html',context)
#login_required(login_url='login')
#allowed_users(allowed_roles=['admin'])
def createOrder(request,pk):
OrderFormSet = inlineformset_factory(Customer,Order, fields=('product', 'status'),extra=10)
customer = Customer.objects.get(id=pk)
#form = OrderForm(initial={'customer':customer})
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
if request.method == 'POST':
#print('Printing POST',request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST,instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset':formset}
return render(request,'accounts/order_form.html',context)
#login_required(login_url='login')
#allowed_users(allowed_roles=['admin'])
def updateOrder(request,pk):
order = Order.objects.get(id=pk)
form = OrderForm(instance=order)
context = {'form':form}
if request.method == 'POST':
#print('Printing POST',request.POST)
form = OrderForm(request.POST,instance=order)
if form.is_valid():
form.save()
return redirect('/')
return render(request,'accounts/order_form.html',context)
#login_required(login_url='login')
#allowed_users(allowed_roles=['admin'])
def deleteOrder(request,pk):
order = Order.objects.get(id=pk)
if request.method == 'POST':
order.delete()
return redirect('/')
context={'item':order}
return render(request, 'accounts/delete.html',context)
Output when i run my local server
This is my first question tell me if i am not giving any information which is useful to answer this
I had the same error, how i solved it? actually it was a silly mistake.
First off all.
Go to admin, go to users than in group section,you will see that you have not assigned any group to that customer. assign customer group or admin group, according to your choice.
This was my mistake, i did not assign any group. I hope you made same mistake there.
As Lain Shelvington mentioned in comments, your admin_only decorator doesn't return a response for groups other the "admin" and "customer":
def admin_only(view_func):
def wrapper_function(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'customer':
return redirect('user-page')
elif group == 'admin':
return view_func(request, *args, **kwargs)
else:
return # <- return response here (possibly a redirect to login page?)
return wrapper_function
Shiv,
If you're following Dennis Ivy's tutorial and you're still having that problem, try the following:
Log in to the Django admin site with a superuser account
Go back to the main site
Log out and try to create another user
I got the same error when working through the signals video. I'm not sure if there is another bug that needs to be fixed, but this got the app working for me again.
Shiv,
I am assuming that you are following Dennis Ivy's tutorial on youtube...
I had the exact same problem. And for me, it was because when I was first migrating my database from sqlite to PostgreSQL and then from PostgreSQL to AWS RDS, somehow all my user informations got lost.
My workaround to this was to create a new superuser (since mine got deleted) with:
python manage.py createsuperuser then with this new superuser login info, log into the admin panel. You will see that your superuser is not assigned to any groups yet, and if you check your Groups panel, you will see that the group variables we created earlier, namely customer and admin are not here. So go ahead and create those two group types. Then go back to the Users panel and assign your superuser the admin variable.
Then logout and go to your /register/ page and create a normal account (not admin, just a customer). Then if you log into your superuser account and go to the admin panel again, you will see that your regular user (customer) is assigned with the customer variable just fine.
This is how I fixed the problem. I hope it helps you with yours. Cheers.
for some people that will get this error, the response of user "sogu" fixed it in my case:
SQLite works, but PostgreSQL migrated database causes ERROR - Django 3.0
(if the other solutions won't work out for you, just see that one)
The problem is that the account that you are logging with does not belong to any group. I assume this is the admin account you first created. Go to admin page --> then to users --> and assign admin group to him. But a better answer was given up there, as it does provide a fix.
Add this code to automatically assign the new user the group he'll belong to.
#unauthenticated_user
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
group = Group.objects.get(name='customer')
user.groups.add(group)
messages.success(request, 'Account was created for ' + username)
return redirect('login')
context = {'form':form}
return render(request, 'accounts/register.html', context)

Why Django raising ValueError?

This is my view.py file under my project folder.
When I add a value in ToDo list it raises this error?
The view my_day.views.index didn't return an HttpResponse object. It returned None instead.
views.py
from django.shortcuts import render, redirect
from .models import List
from .form import ListForm
from django.contrib import messages
# Create your views here.
def index(request):
if request.method == "POST":
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request, ('Task Added'))
return render(request, 'index.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request, 'index.html', {'all_items': all_items})
In your view, you have 3 possible outcomes based on the if conditions but only 2 of them returns a HttpResonse object. More specifically, the if form.is_valid() only returns a HttpResponse object if this condition passes. If it doesn't, it will return None (basically nothing) because there is no else condition or other fallback.
You need to add an else condition to the if form.is_valid(). More so, you should implement another approach than to serve content on a POST request. As WillemVanOnsem have commented, check out the Post/Redirect/Get pattern. I have replaced the return render(...) instances where needed to achieve this, but will need some tweaking to work, for instance replace the view name (should be defined in your urls.py file).
def index(request):
if request.method == "POST":
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request, ('Task Added'))
# Replaced the render(...) with a redirect instead.
# Replace "index" with the name of the view (if not index)
return HttpResponseRedirect(reverse("index"))
else:
# Added fallback if the form.is_valid() didn't pass
messages.failure(request, ('Failed when saving task'))
return render(request, 'index.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request, 'index.html', {'all_items': all_items})

type object 'ProductForm' has no attribute 'cleaned_data' django

I am making a form using Django 2.0.x and Python 3.6 and I am getting an error
I'm not sure what's going on, can someone help me out? Thanks!
Product/forms.py
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
title = forms.CharField(label='',
widget=forms.TextInput(attrs={"placeholder": "Your title"}))
description = forms.CharField(
required=False,
widget=forms.Textarea())
class Meta:
model = Product
fields = [
'title',
'description',
]
Product/views.py
from django.shortcuts import *
from django.http import *
from .models import Product
from .forms import ProductForm
import hashlib
# Create your views here.
def home_view(request,slug,*args,**kwargs):
form= ProductForm(request.POST or None)
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if form.is_valid():
newProduct=Product.objects.create(
title = "jose",
description=ProductForm.cleaned_data.get["description"]
)
if newProduct:
return HttpResponseRedirect("/)
else:
newProduct = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)
The code is giving me this error
type object 'ProductForm' has no attribute 'cleaned_data'
You fetch the cleaned_data from the ProductForm class, not from the form object that is an instance of ProductForm.
You can thus fix it by using form instead, like:
def home_view(request,slug,*args,**kwargs):
form= ProductForm(request.POST or None)
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if form.is_valid():
newProduct=Product.objects.create(
title = "jose",
description=form.cleaned_data.get["description"]
)
if newProduct:
return HttpResponseRedirect("/")
else:
newProduct = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)
But that being said, the workflow is not idiomatic. For example if newProduct will always succeed, regardless whether this is a valid newProduct or not. The Product.objects.create(..) however can raise an exception. A more idiomatic workflow is:
def home_view(request,slug,*args,**kwargs):
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if request.method = 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.instance.title = "jose"
form.save()
return redirect('home') # name of the view
else:
form = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)