Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-How to create a User Model without store in database
I Want to add more fileds to User model and each user has an album so i create This Model class : class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=CASCADE) album = models.OneToOneField(Album, on_delete=CASCADE) profile_picture = models.ImageField(upload_to=upload_destination) in Views i want to create a UserProfile Model , so i have to create a User And aslo an Album . this is the code : def register_user(request): form = forms.UserRegistrationForm(request.POST or None, request.FILES or None) context = {'form': form, 'title': 'Registration'} if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') email = form.cleaned_data.get('email') user = User.objects.create(username=username, password=password, first_name=first_name, last_name=last_name, email=email) album = Album.objects.create(name=username, author=first_name, picture_address=form.cleaned_data.get('profile_picture')) UserProfile.objects.create(profile_picture=form.cleaned_data.get('profile_picture'), user=user, album=album) login(request, user) return redirect('/music') else: print(form.errors) return render(request, 'user/forms.html', context) Is this the correct way to do that ? according to UserProfile model when i delete a UserProfile Object , its User and Album also should be deleted (because of CASCADE on_delete) . but its not happend . whats the problem ? -
Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited
I am using Django 2.x I have two associated models as class Chapter(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(max_length=250, blank=False) created_by = models.ForeignKey(User, on_delete=models.CASCADE) class META: db_table = 'chapters' def __str__(self): return self.name class ChapterQuestion(models.Model): chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) word = models.CharField(max_length=250) definition = models.CharField(max_length=250) audio = models.CharField(max_length=250) created_by = models.ForeignKey(User, on_delete=models.CASCADE) modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class META: db_table = 'chapter_questions' def __str__(self): return self.word I'm creating formset to create multiple ChapterQuestion while creating Chapter forms.py from django.forms import ModelForm, inlineformset_factory from courses.models import Chapter, ChapterQuestion class ChapterForm(ModelForm): class META: model = Chapter fields = ['name'] class ChapterQuestionForm(ModelForm): class META: model = ChapterQuestion fields = ['word', 'definition', 'audio'] ChapterQuestionFormSet = inlineformset_factory(Chapter, ChapterQuestion, form=ChapterQuestionForm, extra=2) But still it gives error as "Calling modelformset_factory without defining 'fields' or " django.core.exceptions.ImproperlyConfigured: Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited. I do have defined fields but it is still giving error. -
Selenium Cannot Find Webdriver Django
as stated in the title Selenium cannot find my web driver. Have tried adding specific path: self.selenium = webdriver.Firefox('C:/Users/Mike/venv/website/hygiene_ratings/web_drivers/') As well as placing the driver in venv, website directory and app directory. Can anyone point me in the right direction? -
TypeError: create_superuser() missing 1 required positional argument: 'profile_picture'
It all was working before adding the "profile_picture" field. I'm sure someone can help me out. This profile_picture field is an "ImageField" set as "Null = True". have tried --- def create_user(...., profile_picture=None, ....) # nothin changed! models.py .... class UserManager(BaseUserManager): def create_user(self, email, full_name, profile_picture, password=None, is_admin=False, is_staff=False, is_active=True): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") if not full_name: raise ValueError("User must have a full name") user = self.model( email=self.normalize_email(email) ) user.full_name = full_name user.set_password(password) # change password to hash user.profile_picture = profile_picture user.admin = is_admin user.staff = is_staff user.active = is_active user.save(using=self._db) return user .... -
Django creating modals in template loop.
When I click on an image, it only displays title for the last article, I cannot figure out why. I have spent hours on this to figure it out. I am using different ids for my modal div. I really appreciate's anyone's help. <div class="grid"> {% for article in Articles %} <div class="card" style="position:relative;"> <img id="myImg{{article.sourceID}}" class="urlImage" alt= {{article.description}} src={{article.urlImage}} /> <h4 id="title{{article.sourceID}}"> {{article.title}}</h4> <p>{{article.description}}</p> </div> <!-- The Modal --> <div id="id{{article.sourceID}}" class="modal"> <span class="close">&times;</span> <img class="modal-content" id="img{{article.sourceID}}"> <div class="background"> <h1 class="modalTitle" id="modal-title{{article.sourceID}}" > </h1> <div id="caption{{article.sourceID}}"></div> </div> </div> <script> var id = "{{article.sourceID}}"; // Get the modal var modal = document.getElementById('id'+id); // Get the image and insert it inside the modal - use its "alt" text as a caption var img = document.getElementById('myImg' + id); var modalImg = document.getElementById("img"+ id); var captionText = document.getElementById("caption"+id); var title = document.getElementById('title'+id).innerHTML; img.onclick = function () { modal.style.display = "block"; modalImg.src = this.src; captionText.innerHTML = this.alt; document.getElementById('modal-title'+id).innerHTML = title; } // Get the <span> element that closes the modal var span = document.getElementsByClassName("close") ['{{article.sourceID}}']; // When the user clicks on <span> (x), close the modal span.onclick = function () { modal.style.display = "none"; } </script> {% endfor %} </div> -
from django.conf.urls import path,include, import error
I am creating a simple about me web page using django. I am getting error that cannot import name 'path'. I have python 3.6 installed on my machine and latest version of django is installed. Can anyone tell me the solution and what I'm doing wrong. I'm using Jinja template. Is there any problem? personal/urls.py from django.conf.urls import patterns, url from . import views urlpatterns = [ path(r'^$', views.index, name='index'), ] mysite/urls.py from django.contrib import admin from django..conf.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path(r'^index/', include('personal.urls')), ] -
ProgrammingError at /admin/login/
So I changed the device I was working my Django App with. In order to change device, I just copy pasted the entire repository to the new device, setup the database, ran a fake migration and then when the app was working fine, started developing again. However, when I started developing on the Django Admin site, I run into this problem. ProgrammingError at /admin/login/ relation "django_session" does not exist LINE 1: SELECT (1) AS "a" FROM "django_session" WHERE "django_sessio... Now, I don't know how I can access the Django Admin again. I've already checked: whether the app, django admin and it's related dependencies are in the INSTALLED APPS. They are. whether the django-admin related tables are in the database: they are. Checked whether I've registered the models to the Admin Site in admin.py. I have. Whether I did a correct fake migration. I ran python manage.py makemigrations, and it told me No changes detected. I ran migrate, told me no migrations to apply. I even looked at showmigrations and it already applied all the migrations to the admin site. The one thing I haven't tried, and I would prefer not to do it, is to delete all the migration files … -
Django url with multiple slugs, no reverse match error
I have a blog project in Django, and I want to be able to filter my posts based on the type of post, for example Travel posts, Programming posts. In my template I therefore need to filter the post by both the post slug, and the type slug, but I'm getting : NoReverseMatch at / Reverse for 'getPost' with keyword arguments '{'categoryTypeSlug': '', 'postTitleSlug': ''}' not found. 1 pattern(s) tried: ['categories/(?P[\w\-]+)/(?P[\w\-]+)/$'] My simplified template (getCatTypePosts.html): {% block content %} {% for post in posts %} {% if post.show_in_posts %} <a href="{% url 'getPost' categoryTypeSlug postTitleSlug %}"> <img src="{{ MEDIA.URL }} {{post.editedimage.url}}" alt="image-{{post.title}}"/> {% endif %} {% endfor %} {% endblock content %} My models.py class categoryType(models.Model): title = models.CharField(max_length=200) categoryTypeSlug = models.SlugField(unique=True) def __str__(self): return self.title class Meta: verbose_name_plural = "categoryTypes" def save(self, *args, **kwargs): self.categoryTypeSlug = slugify(self.title) super(categoryType, self).save(*args, **kwargs) class Post(models.Model): title = models.CharField(max_length=200) postTitleSlug = models.SlugField() summary = models.CharField(max_length=500, default=True) body = RichTextUploadingField() pub_date = models.DateTimeField(default=timezone.now) category = models.ManyToManyField('Category') categoryType = models.ManyToManyField('categoryType') author = models.ForeignKey(User, default=True) authorSlug = models.SlugField() editedimage = ProcessedImageField(upload_to="primary_images", null=True, processors = [Transpose()], format="JPEG") show_in_posts = models.BooleanField(default=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.postTitleSlug = slugify(self.title) self.authorSlug = slugify(self.author) super(Post, self).save(*args, **kwargs) … -
Django Rest Ordering By Count not working
I'm using Django Rest to order some models by number of authors. Example of the setup is this one: Models.py class Book(models.Model): title = models.CharField(max_length=50) authors = models.ManyToManyField(CandidateProfile, blank=True) objects = BookManager() Views.py class BookFilter(filters.FilterSet): author_items_count = filters.NumberFilter(method='filter_author_by_item_count') def filter_author_by_item_count(self, queryset, name, value): return queryset.filter(author_items_count=value) class Meta: model = models.Book fields = ['author_items_count'] class WebinarViewSet(BPIViewSet): serializer_class = serializers.BookSerializer queryset = models.Book.objects.annotate(author_items_count=Count('authors')).all() filter_class = BookFilter ordering_fields = ['author_items_count', ] I am currently able to filter by the item count of the numbers but sorting by the author_items_count simply doesn't work. There's no log or anything as if the param didn't existed. I also tried with adding this to the model but no luck. @property def authors_length(self): return self.authors.count() -
Heroku Docker returning gunicorn: error: No application module specified even though it's specified
There are quite a few moving parts in this Heroku + Docker + Django setup, but I'll try to keep it succinct: I'm able to deploy the Docker container to Heroku. But the CMD of my Dockerfile which starts gunicorn will return an error of gunicorn: error: No application module specified.. I believe it is specified--if I change the CMD instruction, the traceback will show the error just the same, originating from the same CMD. What's going on? Here's the Dockerfile.django: FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev openssl-dev py-cffi RUN addgroup -S django \ && adduser -S -G django django # Requirements have to be pulled and installed here, otherwise caching won't work COPY ./requirements /requirements RUN pip install --no-cache-dir -r /requirements/production.txt \ && rm -rf /requirements COPY ./compose/production/django/gunicorn.sh /gunicorn.sh RUN sed -i 's/\r//' /gunicorn.sh RUN chmod +x /gunicorn.sh RUN chown django /gunicorn.sh COPY ./compose/production/django/entrypoint.sh /entrypoint.sh RUN sed -i 's/\r//' /entrypoint.sh RUN chmod +x /entrypoint.sh RUN chown django … -
How can I modify drf api
API HERE I HAVE AN API, I want to change it so it will look like ` [ cats: [ { "id": 1, "description": "I lost my mind", "petName": "kappies", "phone": 56765665464 }, { "id": 2, "description": "I lost my dog somewhere", "petName": "Doggy", "phone": 38093716438 } ], dogs: [{ "id": 3, "description": "", "petName": "", "phone": 0 }, { "id": 3, "description": "", "petName": "", "phone": 0 }] ]` <== smth like this. Who knows how can I do it? Do I need to create API for cats and dogs separately? sry for cups. serializers -
In the django web project, how to translate BytesIO object to image url? How to convert the file stream(image) to the original image file?
First, My Situation description is below: I am developing a Django app demo. The demo can receive an image file from the user. Then my Django app will processing this image, like add some text or change the image size. I am a newbie in Django, file stream and response. I try to do some search and research. But I can not find a suitable case. Maybe I did not describe my question by the accurate and appropriate keywords. I don't want to save the processed image to the local disk first, and then get the file's local path back to Django web. I want to return the image directly to the browser in memory. Incidentally, django does not seem to recommend reading the media files directly on the local disk. Both css and js need to be configured with static_path to work properly. In addition, according to my investigation, it seems that handling and returning files directly in memory is a more mainstream practice. Of course, I have just come into contact with this field. It may not be the case. I just want to introduce ideas to help describe this tricky problem. My mistake is this: Now my … -
How do I autoplay a song when rendering home page in python/django
I am new to programming and currently in a coding bootcamp. I finished my python/django stack and I am making my first game. I would like to have a song autoplay on the homepage. I have tried pygame and many hours of research but cannot find an answer that works. I converted my mp3 to an ogg and the file rests in a folder titled media within my app folder at the same level as my static and templates. Any guidance on where to find this would be much appreciated! Using python 2.7 on mac. I'm writing my logic in views.py. -
<pip3 package> command not found on zsh but found on bash
I installed django on my Ubuntu 16.04 using pip3 install django. But when I type django-admin and hit enter I get command not found. I even verified using: import django print(django.get_version()) I use zshell instead of bash. At first I thought this is a django issue. So I installed another pip3 package virtualenv. I then typed virtualenv on terminal and hit enter, same output: command not found. Then I was sure this is a shell issue. So I changed my shell back to bash and both django-admin and virtuaenv commands were found. How can I get zsh to discover the pip3 packages? -
How can I pass google token to django auth
I am using google firebase as authentication for my django web application. I was not been able to check weather the user is authenticated or not by using request.user.is_authenticated() function as I'm using google firebase as authentication. So I thought maybe by passing token to django auth I can check weather the user has valid token or not. If this is not right what can be the best way for me to check whether the user is logged in or not. I'm using pyrebase (A python wrapper for google firebase API) for authentication. Help will be highly appreciated. Thanks -
DJANGO: Trying to save POST data to Student model - IntegrityError
Hi I am trying to save data from a form to Student model; abstract User model. Please help! PROBLEM: IntegrityError at /register/ UNIQUE constraint failed: accounts_students.username Not sure what the problem, in the view i am trying to clean the data and save it to the database. Interestingly, the data is being saved, just the page is not being redirected! from .models import * from django.contrib.auth.forms import UserCreationForm, UserChangeForm from betterforms.multiform import MultiModelForm from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = Students fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'bio', 'location', 'birth_date', ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user models.py class Students(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) views.py from django.shortcuts import render from django.shortcuts import redirect from accounts.forms import RegistrationForm, EditProfileForm from django.contrib.auth.models import User from accounts.models import Students from django.contrib.auth.forms import UserChangeForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required # Create your views here. # def login(request): # return render(request, 'accounts/login.html') def home(request): return render(request, 'accounts/home.html') def login_redirect(request): return redirect('/login/') def register(request): # Once register page loads, either it … -
How to calculate current multi-user streak in Django?
For my first webapp, I'm building a group-based, habit-tracking app. I have the following models: class Habit_group(models.Model): name=models.CharField(max_length=50, unique=True) users=models.ManyToManyField(User, through='Activity') timezone=models.CharField(max_length=100, default='UTC') def __str__(self): return self.name class Activity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) habit = models.ForeignKey(Habit, on_delete=models.CASCADE) update_date = models.DateField() Streak Definition: A streak is incremented by 1 when all members of the habit group have "updated" (checked-in) on the day. If any member of the habit group fails to "update" on any given day, the streak is reset to 0. As a side note, I hope to implement streaks for tasks that need to be completed every x days in the future. I originally had a streak field in the Habit_group model, but it quickly got out of hand and after reading: How to calculate current streak in Django? I've since changed my approach. Currently, in the views, I'm trying to first calculate a list of dates that satisfy the criteria of having "updates" from all members. Then passing these dates into the logic here: https://stackoverflow.com/a/23275847/7449480 Apart from inefficiently querying the database, my current solution fails to account for the fact that the users in a habit group may change over time. I've been struggling with this for a … -
G Suite and Django for SMTP
I'm in the process of getting G Suite to work with my django site so that it will replace the SMTP server of my host. I configured my domain within my webhost's config panel. As a result, when I send an email to support@mysite.com, I can see that it successfully comes though to the Google Account, which is great. My application is setup to send out a confirmation email after someone tries to register. I've completed what I believe to be all of the required steps to setup G Suite with my django project, but I still get a "[Errno 111] Connection refused" when my project attempts to send out the confirmation email after someone registers. Specifically, I'm seeing the following on the Django error page: Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connection refused I've completed the following steps: I've setup the SMTP relay service (https://support.google.com/a/answer/2956491), which means I've: - turned on comprehensive mail storage as per the instructions - added the SMTP relay service setting - allowed less secure apps (https://myaccount.google.com/lesssecureapps) in my settings In my django settings files, I'm using the following settings: EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = 'support@mysite.com' EMAIL_HOST_PASSWORD = '********' DEFAULT_FROM_EMAIL = 'support@mysite.com' SERVER_EMAIL = … -
NameError: 'user' not defined: Trying to extend abstract user model - DJANGO
First attempt at trying to create a student user by extending the User model. Issue: Upon clicking register btn i.e.Login (btn) instead of redirecting to home it shows the following: NameError at /register/ ...name 'user' is not defined File "E:\ifb299\tutorial2\accounts\views.py", line 33, in register Students.objects.create(user=user) NameError: name 'user' is not defined [25/Mar/2018 14:38:07] "POST /register/ HTTP/1.1" 500 67801 Not really sure what I'm doing wrong, why is Students.objects.create(user=user) wrong and how do i fix it, please? views.py from django.shortcuts import render from django.shortcuts import redirect from accounts.forms import RegistrationForm, EditProfileForm from django.contrib.auth.models import User from accounts.models import Students from django.contrib.auth.forms import UserChangeForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required def home(request): return render(request, 'accounts/home.html') def login_redirect(request): return redirect('/login/') def register(request): # Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): form.save() Students.objects.create(user=user) return redirect('../home/') else: # Create the django default user form and send it as a dictionary in args to the reg_form.html page. form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) @login_required def view_profile(request): … -
from .models import profile ImportError: cannot import name 'profile'
I used following code in admin.py but i got an error : ______________________admin.py____________________________________________ from django.contrib import admin from .models import profile class profileAdmin(admin.ModelAdmin): class Meta: model = profile admin.site.register(profile,profileAdmin) ______________________error_____________________________ from .models import profile ImportError: cannot import name 'profile' can anyone suggest to fix this in python3.4 -
allauth isn't sending verification email
I'm using django allauth for my user accounts. I'm using the default settings, except for the following: ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_REQUIRED = True EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" which have all been set in my settings.py file. When I create an account, it successfully tells me it will send an email to the address for verification. However I don't receive this email. I'm not sure if my django email backend is not working (how do I check if it is?) or if my allauth settings are not configured properly. My django site is running on a remote Ubuntu server with Nginx/Gunicorn. Any idea? -
Can get into Django project admin fine but blog is getting an error loading page
I'm getting the error below trying to open my Django app in Heroku. It seems to have deployed successfully and is working from my local pc totally fine. I'm hoping this a simple fix. Thanks Environment: Request Method: GET Request URL: https://djangowaston.herokuapp.com/ Django Version: 1.11.2 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/blog/views.py" in post_list 30. data = json.dumps(tone_analyzer.tone(post.text, content_type='text/plain', sentences=None, tones='emotion', content_language=None, accept_language=None), indent=1) # converting to string and storing in the data Exception Type: TypeError at / Exception Value: tone() got an unexpected keyword argument 'content_type' -
Django1.11 Customized UserCreationForm filter email
I am trying to filter user's alias. I am using Django's userform and its authentication. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignupForm(UserCreationForm): email = forms.CharField( retuired=True, widget=EmailInput( attrs={'class':'validate',} ) ) views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as auth_login def signup(req): if req.method == "POST": form = UserCreationForm(req.POST) if form.is_valid(): user = form.save() auth_login(req, user) return redirect('home') else: form = UserCreationForm() context = { 'form':form, } return render(req, "signup.html", context) I believe that I need to filter inside of views.py. For example, if I want to filter alias which is not gmail, they cannot signup. How can I filter email? Thanks in advance! -
Django Views that have multiple functions
I'm trying to wrap my head around this. I'm able to write views that do things pretty well, add, edit, delete, produce custom queries. But now I'm trying to write a "report" view that does a couple things and I'm not sure how to go about this. I've started with a function based view but I'm wondering if something like this needs to be a class based view? I can run a query from the form input on a model and output exactly what I need to the template. But now I want to do more things with that data on the same page like export data to csv, mabye send an email with the output, display some totals and run some calculations on the data and have it display on the template. Here's an example of what I have so far: Views.py def agent_commission_report(request): agent = request.user agent_company = agent.agent_profile.company agents = Agent.objects.filter(company=agent_company) if 'choose_agent' and 'start_date' and 'end_date' in request.GET: selected_agent = request.GET['choose_agent'] start_date_url = request.GET['start_date'] start_date = datetime.strptime(start_date_url, "%Y-%m-%d").date() end_date_url = request.GET['end_date'] end_date = datetime.strptime(end_date_url, "%Y-%m-%d").date() load_list = Load.objects.filter(agent=selected_agent).filter( date_created__range=(start_date, end_date)) return render(request, 'reports/agent_commission.html', {'load_list' : load_list, 'agents' : agents, }) return render(request, 'reports/agent_commission.html', {'agents' : agents}) … -
"Cannot use None as a query value"
I was wondering if someone could help explain why something works. The first code produces no errors and my program works well, while my second code produces a "TypeError: 'int' object is not iterable". I thought I was only getting rid of the redundancy. First Code class SearchForm(ListView): template_name = 'Training_App/Search_Page.html' context_object_name = 'barcode_search' model = models.Input def get_queryset(self): res = 0 sq = self.request.GET.get('search_box') if sq == None: model = models.Input sq = self.request.GET.get('search_box') #Word the User looked for else: if sq == None: print("PLEASE SUBMIT1") else: sq = self.request.GET.get('search_box') model = models.Input res = model.objects.filter(barcode__icontains=sq) return res Second Code class SearchForm(ListView): template_name = 'Training_App/Search_Page.html' context_object_name = 'barcode_search' model = models.Input def get_queryset(self): res = 0 sq = self.request.GET.get('search_box') if sq == None: model = models.Input sq = self.request.GET.get('search_box') #Word the User looked for else: sq = self.request.GET.get('search_box') model = models.Input res = model.objects.filter(barcode__icontains=sq) return res