Why doesn't my search function work? - python

I'm currently trying to implement a search functionality to my Django app. Everything works perfectly fine, until the actual search query is handled. Say, I search for "hallo". Django would the return the following error:
django.core.exceptions.FieldError
FieldError: Cannot resolve keyword 'title' into field. Choices are: adresse, arbejde, beskrivelse, email, foerste_session, fulde_navn, id, profilbillede, relateret_til_andre_klienter, tidligere_klient, vurder_sidste_session
There seems to be some sort of conflict between my form (I am using a ModelForm) and my search function. How do I go about solving my problem?
Here is my forms.py:
from django import forms
from .models import Client
class ClientForm(forms.ModelForm):
class Meta:
model = Client
fields = (
'fulde_navn',
'adresse',
'email',
'tidligere_klient',
'foerste_session',
'beskrivelse',
'arbejde',
'relateret_til_andre_klienter',
'vurder_sidste_session',
'profilbillede'
)
And here is my models.py
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
import uuid
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
import os
import uuid
YESNO_CHOICES = (
(0, 'Ja'),
(1, 'Nej')
)
SESSION_CHOICES = (
(0, '1'),
(1, '2'),
(2, '3'),
(3, '4'),
(4, '5'),
)
def upload_to_location(instance, filename):
blocks = filename.split('.')
ext = blocks[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
instance.title = blocks[0]
return os.path.join('uploads/', filename)
# Create your models here.
class Client(models.Model):
fulde_navn = models.CharField('Navn', max_length=75)
adresse = models.CharField(max_length=100)
email = models.EmailField(null=True, blank=True)
tidligere_klient = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True)
foerste_session = models.DateField('Dato for 1. session', null=True, blank=True)
beskrivelse = models.TextField('Noter', null=True, blank=True)
arbejde = models.CharField('Arbejde', max_length=200)
relateret_til_andre_klienter = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True)
vurder_sidste_session = models.IntegerField(choices=SESSION_CHOICES, null=True, blank=True)
profilbillede = models.ImageField('Profilbillede',
upload_to='profile_pics/%Y-%m-%d/',
null=True,
blank=True)
def __unicode__(self):
return self.fulde_navn
def get_absolute_url(self):
return reverse(viewname="client_detail", args=[self.id])
And finally my views.py where my search function is located:
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView
from . import models
from .forms import ClientForm
# Create your views here.
class ClientsListView(ListView):
model = models.Client
template_name = 'clients/list.html'
paginate_by = 20
class SearchListView(ClientsListView):
def get_queryset(self):
incoming_query_string = self.request.GET.get('query', '')
return models.Client.objects.filter(title__icontains=incoming_query_string)
class ClientsDetailView(DetailView):
model = models.Client
template_name = 'clients/detail.html'
def client_create(request):
if request.method == 'POST':
form = ClientForm(request.POST)
if form.is_valid():
client = form.save()
client.save()
return redirect('client_detail', pk=client.pk)
else:
form = ClientForm()
return render(request, 'clients/form.html', {'form': form})
def client_edit(request, pk):
client = get_object_or_404(models.Client, pk=pk)
if request.method == "POST":
form = ClientForm(request.POST, instance=client)
if form.is_valid():
client = form.save()
client.save()
return redirect('client_detail', pk=client.pk)
else:
form = ClientForm(instance=client)
return render(request, 'clients/form.html', {'form': form})
class ClientsUpdateView(UpdateView):
model = models.Client
template_name = 'clients/form.html'
How do I solve this problem? I want to make it so my user is able to search for clients in my list.

In this line:
return models.Client.objects.filter(title__icontains=incoming_query_string)
You are trying to check if the field titlecontains the incoming_query_string. However, your ClientForm doesn't have such field.
You should use one of the fields you listed there or add title as a field.

Related

Django form not sending data to admin

I have a form users can fill out to reserve a table at a restaurant. However when they submit the form no data gets sent to the admin side.
I have watched some tutorials and read other posts on this site and nothing seems to fix it. I feel like it is something so small but I just cant figure it out.
views.PY
from django.shortcuts import render, get_object_or_404
from django.views import generic, View
from .models import Book
from .forms import BookForm
from django.http import HttpResponseRedirect
def Book(request):
"""
Renders the book page
"""
if request.user.is_authenticated:
form = BookForm(request.POST or None)
context = {
"form": form,
}
else:
return HttpResponseRedirect("accounts/login")
book_form = BookForm(data=request.POST)
if book_form.is_valid():
instance = book_form.save(commit=False)
instance.save()
else:
book_form = BookForm()
return render(
request,
"book.html",
{
"book_form": BookForm(),
}
)
models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
from cloudinary.models import CloudinaryField
class Book(models.Model):
name = models.CharField(max_length=50)
number_of_guests = models.PositiveIntegerField(validators=[MinValueValidator(1)])
date = models.DateTimeField()
email = models.EmailField()
requests = models.TextField(max_length=200)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
approved = models.BooleanField(default=False)
class Meta:
ordering = ['date']
def __str__(self):
return f"{self.date} for {self.name}"
forms.py
from .models import Book
from django import forms
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = (
'name',
'number_of_guests',
'date',
'email',
'requests',
)
Try this view:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect,render
#login_required(login_url="accounts/login")
def Book(request):
if request.method=="POST":
book_form = BookForm(request.POST)
if book_form.is_valid():
book_form.save()
return redirect("some_success_page")
else:
return redirect("some_error_page")
else:
book_form = BookForm()
return render(
request,
"book.html",
{
"book_form": book_form,
}
)
In settings.py
LOGIN_URL="accounts/login"

Uploading Multiple Images django REST

I would like to upload multiple images using the Django model field(ImageField).
I created a model and was able to upload multiple images on the admin side like so https://imgur.com/BzVDPC5
I got the idea here (https://github.com/raszidzie/Multiple-Images-Django-Tutorial) in the Post(admin.py)
admin.py
from django.contrib import admin
from .models import School,SchoolImage
class SchoolImageAdmin(admin.StackedInline):
model = SchoolImage
#admin.register(School)
class SchoolAdmin(admin.ModelAdmin):
list_display=('school_name','school_type',"school_country")
search_fields=('school_name','school_type',"school_country")
list_filter=('school_name','school_type','school_gender')
inlines = [SchoolImageAdmin]
class Meta:
model =School
#admin.register(SchoolImage)
class SchoolImageAdmin(admin.ModelAdmin):
pass
I created the SchoolImage Model to handle multiple images in admin.py
models.py
from django.db import models
from django_countries.fields import CountryField
from partial_date import PartialDateField
class School(models.Model):
school_name = models.CharField(max_length = 30)
school_country = CountryField()
school_city = models.CharField(max_length= 30,default= None)
school_population = models.IntegerField()
school_description = models.TextField(max_length = 300)
year_build = PartialDateField()
total_branches = models.IntegerField()
school_fees = models.IntegerField()
school_images = models.FileField()
def __str__(self):
return self.school_name
class SchoolImage(models.Model):
schoolImages = models.ImageField()
school = models.ForeignKey(School, on_delete=models.CASCADE)
def __str__(self):
return self.school.school_name
not sure how to make it work in the veiws
here is my views code
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from .models import School
from .serializers import *
#api_view(['GET','POST'])
def school_list(request):
if request.method == 'GET':
data = School.objects.all()
serializer = SchoolSerializer(data, context={'request': request},many = True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = SchoolSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response( status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_404_NOT_FOUND)
How do I make it work in my views??

How do i pass data from a django function to another function

I have this signup django app and its more like a signup page for a website. I have an issue now, i made a one to one database relationship between the users data and their web profile
from django.db import models
import datetime
from django.utils import timezone
class UserDetail(models.Model):
SEX = (
('M', 'Male'),
('F', 'Female'),
)
first_name = models.CharField(max_length=60)
middle_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=60)
gender = models.CharField(max_length=1, choices=SEX)
email = models.EmailField()
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
class WebDetail(models.Model):
user = models.OneToOneField(UserDetail, on_delete=models.CASCADE)
username = models.CharField(max_length=60)
password = models.CharField(max_length=60)
# TODO: i need to search how to do auto_now_add function
# time_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.username
and here is my views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import UserDetailForm, WebDetailForm
from .models import UserDetail, WebDetail
from django.shortcuts import redirect, reverse
def index(requests):
form = UserDetailForm()
if requests.method == "POST":
form = UserDetailForm(requests.POST)
if form.is_valid():
UserDetail.objects.create(**form.cleaned_data)
# print(requests.POST['first_name'])
# return HttpResponse('<h1>Hello</h1>')
# return redirect('signup:web_detail_create')
context = {'form': form}
return render(requests, 'signup/index.html', context)
def web_detail_create(requests):
form = WebDetailForm()
if requests.method == "POST":
form = UserDetailForm(requests.POST)
if form.is_valid():
# TODO: i need the function above to go with the users data and that would be refrenced as the user
# of the password and the username.
WebDetail.objects.create(**form.cleaned_data)
return redirect('signup:final')
context = {'form': form}
return render(requests, 'signup/final.html', context)
now i want to be able to pass in the users data to the web_detail_create view.
Thanks for your contribution

django forms post request raising an error on __init__ method

I have a django form which takes a paramater from the view to initialize the MultipleChoiceField based on the user instance.
The form is working fine when loading the template.
when i submit the form the init method in the form raising an error.
My Model models.py
from django.db import models
from django.contrib.auth.models import User
class Group(models.Model):
group_name = models.CharField('Group name', max_length=50)
def __str__(self):
return self.group_name
class GroupMembers(models.Model):
group_name = models.ManyToManyField(Group)
members = models.ForeignKey(User, on_delete=models.CASCADE)
class Transactions(models.Model):
bill_type = models.CharField('Bill type',max_length=200)
added_by = models.ForeignKey(GroupMembers, on_delete=models.CASCADE)
added_to = models.ForeignKey(Group, on_delete=models.CASCADE)
purchase_date = models.DateField(auto_now=True)
share_with = models.CharField('Share among',max_length=250)
amount = models.IntegerField(default=0)
def __str__(self):
return self.bill_type
forms forms.py
from django import forms
from .models import Transactions, GroupMembers
class Bill_CreateForm(forms.ModelForm):
def __init__(self, user_list, *args, **kwargs):
super(Bill_CreateForm, self).__init__(*args, **kwargs)
self.fields['share_with'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.members) for name in user_list]))
class Meta:
model = Transactions
fields = (
'bill_type',
'amount',
'added_by',
'added_to',
'share_with',
)
** RESOLVED MY ISSUE WITH THE HELP OF #Alasdair "
EDITED SOLUTION
views views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Transactions, Group, GroupMembers
from .forms import Bill_CreateForm
from django.http import HttpResponse, HttpResponseRedirect
def add_bills_home(request, id=None):
user = User.objects.get(pk=id)
grpname = Group.objects.filter(groupmembers__members=user)
gm = GroupMembers.objects.filter(group_name__group_name=grpname[0])
users_list = [i for i in gm]
if request.method == 'POST':
form = Bill_CreateForm(users_list, request.POST)
if form.is_valid():
print(form.cleaned_data['share_with'])
form.save()
form = Bill_CreateForm(users_list)
return render(request, 'bills/create_bill.html', {'form':form})
else:
form = Bill_CreateForm(users_list)
return render(request, 'bills/create_bill.html', {'form':form})
The error is
After submiting the form with data
the request.POST method returning
below data
i don't know if the request.POST method re-initializes the form with the filled data and pass it to the init method in the form.py.
Please help me with this

Django - Why am I getting this IntegrityError: NOT Null constraint failed: restaurants_restaurantlocation.owner_id?

I am trying to make a website where people can find restaurants and menu items based on their pickiness. Currently I am trying to do it so when I add something to the restaurants through forms I have it associated to an user but when I submit the form I get this error:
IntegrityError
NOT Null constraint failed: restaurants_restaurantlocation.owner_id
Here is my forms.py:
from django import forms
from .models import RestaurantLocation
from .validators import validate_category
class RestaurantCreateForm(forms.Form):
name = forms.CharField()
location = forms.CharField(required = False)
category = forms.CharField(required = False)
def clean_name(self):
name = self.cleaned_data.get("name")
if name == "Hello":
raise forms.ValidationError("This is an invalid name. You stubid boy.")
return name
class RestaurantLocationCreateForm(forms.ModelForm):
#email = forms.EmailField()
#category = forms.CharField(validators = [validate_category], required = False)
class Meta:
model = RestaurantLocation
fields = [
"name",
"location",
"category"
]
def clean_name(self):
name = self.cleaned_data.get("name")
if name == "Hello":
raise forms.ValidationError("This is an invalid name. You stubid boy.")
return name
My models.py:
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save
from .utils import unique_slug_generator
from .validators import validate_category
# Create your models here.
User = settings.AUTH_USER_MODEL
class RestaurantLocation(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(max_length=120)
location = models.CharField(max_length=120, null=True, blank=True)
category = models.CharField(max_length=120, null=True, blank=True, validators= [validate_category])
slug = models.SlugField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
#property
def title(self):
return self.name #obj.title
def rl_pre_save_reciever(sender, instance, *args, **kwargs):
instance.category = instance.category.capitalize()
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(rl_pre_save_reciever, sender=RestaurantLocation)
My views.py:
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.views import View
from django.views.generic import TemplateView, ListView, DetailView, CreateView
from django.utils.datastructures import MultiValueDictKeyError
from .forms import RestaurantCreateForm, RestaurantLocationCreateForm
from .models import RestaurantLocation
# Create your views here
def restaurant_createview(request):
form = RestaurantLocationCreateForm(request.POST or None)
errors = None
if form.is_valid():
# customise
# like a pre save
form.save()
# like a post save
return HttpResponseRedirect("/restaurants/")
if form.errors:
errors = form.errors
template_name = "restaurants/form.html"
context = {"form" : form, "errors" : errors}
return render(request, template_name, context)
def restaurant_listview(request):
template_name = "restaurants/restaurants_list.html"
queryset = RestaurantLocation.objects.all()
context = {
"object_list": queryset
}
return render(request, template_name, context)
class RestaurantListView(ListView):
def get_queryset(self):
slug = self.kwargs.get("slug")
if slug:
queryset = RestaurantLocation.objects.filter(
Q(category__iexact = slug) |
Q(category__icontains = slug)
)
else:
queryset = RestaurantLocation.objects.all()
return queryset
class RestaurantDetailView(DetailView):
queryset = RestaurantLocation.objects.all()
class RestaurantCreateView(CreateView):
form_class = RestaurantLocationCreateForm
template_name = "restaurants/form.html"
success_url = "/restaurants/"
If you need any other piece of code please ask, thank you
Looking at your RestaurantLocation model, you have a foreign key into the User table:
class RestaurantLocation(models.Model):
owner = models.ForeignKey(User)
By default this can't be empty (this is what "NOT null constraint" means). And indeed it looks like your form does not do anything to fill in a restaurant owner, so you will get a database constraint error when you try to commit.
"This is an invalid name. You stubid boy."
Not a very nice thing to say to your users.

Categories