Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why DRF giving me 404
I am keep getting 404 in DRF whenever I send request from postman even though the url is correct. urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('backend.urls')) ] backend/urls.py from django.urls import path, include from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('/post', views.PostView, basename='post') urlpatterns = [ path('', include(router.urls)), ] from postman I am sending post request on this endpoint http://127.0.0.1:8000/post but I am keep getting 404 not found error. What am I doing wrong? -
I want to show last 4 products in Django
There are many products in the database. but I only want to show the 4 most recently added products. in the variable similar views.py def product_detail(request, category_slug, id): category = Category.objects.all() product = get_object_or_404(Product, category__slug = category_slug, id=id) images = ProductImages.objects.filter(product_id=id) similar = Product.objects.all().filter(category__slug=category_slug) context = { 'category': category, 'product': product, 'images': images, 'similar': similar, } return render(request, 'detail.html', context) -
Django- link answer choice to question and survey
I am trying to create a number of surveys in Django and put them in a survey index page. I have run into an issue: Up until now, all of my surveys had questions which had the same set of answer choices, so in my Django models I linked the answers only to the survey because it was the easiest for me and it was working. Now I have to add a new survey where each question has a different set of answers choices (if you are curious, this is the survey: https://www.fresno.ucsf.edu/pediatrics/downloads/edinburghscale.pdf). My problem is that for this new survey I am now getting every possible answer choice in the whole survey for each question. How can I link the answer choices to the question so that I will only see the choices for the corresponding question? Yes, I have read the Django polls tutorial and have tried requesting the question_id, but then I got an error along the lines of "missing question_id" so I went back to my original code. I think the right approach would be to link the answer choices to both the question and the survey, but not sure. Here is my model: class Questionnaire(models.Model): … -
how do I make a math Django and react web application?
Hope all is well. I want to have an input field in my react frontend that takes in a math expression (e.g 1 + 1) and I want my backend to respond with the answer 2. How do you do this using reactjs and Django? So far I have some of the frontend finished: it will send the input data to the backend using the API url. import React, {useState, UseEffect } from 'react'; function Home() { const [query, setQuery] = useState(""); return ( <div className='Home'> <form action={APIL_URL} method="POST"> <input name="linear-algebra-expression" id="linear-algebra-expression" type="text" onChange={e => setQuery(e.target.value)} value={query}> </input> </form> </div> ) } export default Home; I am aware that in my Django backend I am going to have something like: class LinearAlgebraView(APIView): def post(self, request): expression = request.POST['linear-algebra-expression'] return (... ?) I want to be able to return the computed data from Django to react at the samne web page where the user entered the math expression in the form/input. How do I do this? Thanks -
Django: How to create a view that can be emailed to users?
In my DB, I have a bunch of objects of model 'Foo'. Users can create, update, delete objects in the admin panel. Once a week I would like to send a digest of all objects that were created, updated, or deleted. I am using the django-simple-history plugin so I am able to create a dictionary that has changes for a given date range. This part is OK. I would like to take this data, put it in a HTML page, and then email it to a distribution list. For the 2nd part, do I create a Django view or just create a HTML template and do variable substitution? This view will never been shown on a webpage. Not sure what is the easiest way to do this. -
hosting django app its return path: .github/workflows/main_school-database.yml
am trying to host my django app on Microsoft azure but when i choose my github account, my repository and my branch when its successeful but when I click on Preview File its throws me an error saying: File path: .github/workflows/main_school-database.yml and with something i did not know. its looks like i need to create yml file inside my project directory and paste that code its throws me. I'm a begineer in Microsoft Azure and this is my first time building an applications on Azure with django after i migrate from Heroku to Microsoft Azure. is anybody who can help please? the logs: # Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy More GitHub Actions for Azure: https://github.com/Azure/actions More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions name: Build and deploy Python app to Azure Web App - school-database on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '3.9' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: pip install -r requirements.txt # Optional: Add step to run tests here (PyTest, … -
ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects
The Heroku Build is returning this error when I'm trying to deploy a Django application for the past few days. The Django Code and File Structure are the same as Django's Official Documentation and Procfile is added in the root folder. Log - -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> No Python version was specified. Using the buildpack default: python-3.10.4 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml): started Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python /app/.heroku/python/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /tmp/tmpqqu_1qow cwd: /tmp/pip-install-txfn1ua9/backports-zoneinfo_a462ef61051d49e7bf54e715f78a34f1 Complete output (41 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.10 creating build/lib.linux-x86_64-3.10/backports copying src/backports/__init__.py -> build/lib.linux-x86_64-3.10/backports creating build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.linux-x86_64-3.10/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory … -
Django file upload testcase: how to send both form data and files in request
I want to write a testcase for file upload page which also have other form fileds. So I come up with the following code: file_b = open(test_file2, 'rb') file_c = open(test_file3, 'rb') form_data = {'form_field_1': 'abc', 'form_field_2': 'def'} form_data = form_data.update({'file_name': self.file_b, 'co-file_name': self.file_c}) self.client.post(reverse('overrun_cause_modal', kwargs={'workflowid': self.wf_id}), data=form_data, format='multipart') the above code caused form to be invalid: form = WorkflowForm(data=form_data) form.is_valid() --> False if I do comment out: form_data = form_data.update({'file_name': self.file_b, 'co-file_name': self.file_c}) then form is valid. How can I send both form data and files in request so that I can have a valid regular form and also request.FILES['file_name'], request.FILES['co-file_name'] as well as request.FILES['file_name'].name and request.FILES['co-file_name'].name? -
Django migration IntegrityError: invalid foreign key (but the data exists)
I am gradually updating a legacy Django application from 1.19 -> 2.2 and beyond. To upgrade to 2.2, I just added on_delete=models.CASCADE to all models.ForeignKey fields that did not have the error. Possibly unrelated, when I run manage.py migrate, Django throws the following error (I shortened the table/field names for brevity): django.db.utils.IntegrityError: The row in table 'X' with primary key '3' has an invalid foreign key: X.fieldname_id contains a value '4' that does not have a corresponding value in Y__old.id. Note in particular the __old.id suffix for the db table that Django expects to contain a row with id 4. When manually inspecting the db, the table Y does really contain a valid row with id 4! I'm assuming, to support the migration, Django is making some temporary tables suffixed with __old and somehow it is unable to migrate said data? The db row Y in question is really simple: a char, boolean, and number column. -
Where does manage.py get the frontend when there isn't a main.js?
I want to know why my changes aren't reflecting in the browser/console I'm working on a React + Django app and encountered this warning react-dom.development.js:86 Warning: The tag <thread> is unrecognized in this browser When I saw this I found the one instance I wrote <thread> and replaced it with <thead> I then saved my changes and re ran python manage.py runserver and webpack --mode development --watch ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/frontend/ After reloading my app I'm still confronted with the same warning message and when I inspect the warning I can see in the Chrome console that the file is still using <thread> I thought it could be because I didn't clear my static/frontend/main.js before re running webpack which didn't change anything I then notice when I run python manage.py runserver without running the separate webpack command, and after deleting static/frontend/main.js my app still gets loaded to localhost... It was my understanding that static/frontend/main.js is what python uses to display my app in the browser Where is python getting the frontend to display my app when there isn't a main.js file? -
ValueError: Could not find function validator when calling makemigrations in Django 4.0
Using the solution here to validate URLField, I am getting ValueError when I run python manage.py makemigrations and I'm not sure why. What am I doing wrong? from django.contrib.auth.models import User from django.db import models from django.core.exceptions import ValidationError from urllib.parse import urlparse def validate_hostname(*hostnames): hostnames = set(hostnames) def validator(value): try: result = urlparse(value) if result.hostname not in hostnames: raise ValidationError(f'The hostname {result.hostname} is not allowed.') except ValueError: raise ValidationError('Invalid URL') return validator class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) twitter = models.URLField( blank=True, null=True, validators=[validate_hostname('twitter.com', 'www.twitter.com')] ) Traceback $ python manage.py makemigrations Migrations for 'userprofiles': userprofiles/migrations/0002_userprofile_twitter.py - Add field twitter to userprofile Traceback (most recent call last): File "/home/master/github/mywebsite/src/manage.py", line 22, in <module> main() File "/home/master/github/mywebsite/src/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 214, in handle self.write_migration_files(changes) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 255, in write_migration_files migration_string = writer.as_string() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", line 99, in serialize _write(arg_name, arg_value) File "/home/master/.cache/pypoetry/virtualenvs/mywebsite-WMQVlvmt-py3.10/lib/python3.10/site-packages/django/db/migrations/writer.py", … -
Model instances autocreation on interval
I want to implement django models autocreation but have no clue how to do it. As example we set 1 year interval, and when it passes the model instance is automatically created. -
Can not see an app with name "advertisements" in admin interface
I tested it many times. When I add an app with the name advertisements (add models, admin + register in INSTALLED_APPS) it is not listed in the admin interface (it is very hard to see but it disappears after microseconds). models.py: from django.db import models # Create your models here. class Advertisement(models.Model): pass admin.py: from django.contrib import admin from .models import Advertisement # Register your models here. @admin.register(Advertisement) class AdvertisementAdmin(admin.ModelAdmin): pass apps.py: from django.apps import AppConfig class AdvertisementsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'advertisements' settings.py: INSTALLED_APPS = [ # ... "advertisements", ] Changing an app directory to something like advertisements2, app name (in apps.py) to advertisements2 solves the problem. -
How to print value from specific model/queryset Django
This is my code for the view def return_chat(request): context = {'client_name': request.POST['client_name'], 'messages': [], 'datetime': []} def order_messages(): replies = Replies.objects.all().filter(unique_num=request.POST['unique_num']) sent_messages = InstantMessages.objects.all().filter(unique_num=request.POST['unique_num']) + 'S' from itertools import chain all_messages = list(chain(replies, sent_messages)) all_messages.sort(key=lambda x: x.datetime) return all_messages for item in order_messages(): context['messages'].append(item.message) context['datetime'].append(item.datetime) return render(request, 'chat.html', context) My HTML code: <html> <body> <div style="position:relative;background-color:#f5f5f5;width:900px;height:500px;border-radius:15px;border:2px solid black;margin:auto;margin-top:10%;"> <div style="position:absolute;left:20px;padding:10px;top:15px;border-left-style:solid;border-left-color:#48b8fa;margin:auto;width:870px;max-height:350px;overflow-y:scroll;"> {% for all_messages in messages %} <br> {{ all_messages }} <br> {% endfor %} </div> <textarea placeholder="Type your message to {{ client_name }} here.." style="background-color:#f5f5f5;position:absolute;width:900px;height:90px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;bottom:0;border:2px solid black;right:-2px;bottom:-2px;padding:20px;margin:auto;padding-right:80px"></textarea> <button style="position:absolute;width:80px;height:90px;border-bottom-right-radius:15px;bottom:0;border:2px solid black;right:-2px;bottom:-2px;"><b>Send</b></button> </div> </body> </html> Essentially. I want the replies on the left and the InstantMessages model to appear in the right side in the Django template. I need css/html, and Python advice. Either or all would help greatly!! -
Display field from another model in django admin
Let say I have two model. I want to make subject field in Program model appear in UserProgramAdmin. What is the best way to do that? class Program(models.Model): name = models.CharField(max_length=15, blank=False) summary = models.CharField(max_length=200, blank=True) subject = models.ManyToManyField(Subject, related_name='all_subjects') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) def __str__(self) -> str: return self.name class UserProgram(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) program = models.ForeignKey( Program, on_delete=models.CASCADE, ) is_active = models.BooleanField(default=True) is_finish = models.BooleanField(default=False, editable=False) /admin.py class UserProgramAdmin(admin.ModelAdmin): list_display = ('user', 'program' , 'is_active', 'is_finish') Thanks in advance -
How to change a field type in a Django model with existing data?
I have the following existing twitter field on the extended UserProfile model and I'd like to change the field type from a URLField to a CharField with max_length of 20. When I try to migrate the change, I get the error django.db.utils.DataError: value too long for type character varying(20). I do not care about existing data in that field and prefer they go blank if there is existing data when migrating. How can I change the field type and clear existing data? class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) # old field twitter = models.URLField(verbose_name="Twitter", blank=True) # new field # twitter = models.CharField( # max_length=20, verbose_name="Twitter Username", null=True, blank=True # ) -
dal.autocomplete and AutocompleteFilter don't work in model with foreign key to itself don't work in admin site
I wan't to make a filter on categories by parent category, I use a model and for parent category I linked to itself. the model: class Category(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="childs" ) description = models.TextField(null=True, blank=True) is_adult = models.BooleanField(default=False) is_active = models.BooleanField(default=True) in admin.py : class ParentCategoryFilter(AutocompleteFilter): title = "By parent category" field_name = "parent" autocomplete_url = "parent-category-autocomplete" is_placeholder_title = True class CategoryAdmin(admin.ModelAdmin): search_fields = ["name"] autocomplete_fields = ["parent"] fieldsets = ( ( _("Details"), { "fields": ( "name", "parent", "description", ), }, ), ) list_display = ( "name", "parent", ) list_filter = [ParentCategoryFilter] admin.site.register(Category, CategoryAdmin) and the views.py where ParentCategoryFilter is defined: class ParentCategoryAutocompleteView(autocomplete.Select2QuerySetView): permissions = [ "CategoryView", ] def get_queryset(self): qs = Category.objects.filter(parent__isnull=True) if self.q: qs = qs.filter(Q(name__istartswith=self.q)) return qs the problem I get is that in the filter I get the child's categories name. I don't know what the problem with it. -
ClientError at /saved_json/ An error occurred (403) when calling the HeadObject operation: Forbidden
I was trying to add images, json files to s3 bucket. It was going well about few months ago but i have opened it now and it shows an error on the line where the object of model is created. Error named: Exception Type: ClientError at /saved_json/ Exception Value: An error occurred (403) when calling the HeadObject operation: Forbidden for image in images: photo = Photo.objects.create( //eror is here email=data['email'], image=image, ) -
How to send emails with send_mass_mail in Django for more than one recipients dynamically?
I try to send an email to more than one recipients but I am doing something wrong. I try to use use a for loop to get the email addresses from the user. If I print the emails these are in this format: 'someone@xy.com'. But if I try to send them, only one user gets the email. views.py from django.shortcuts import render from django.core.mail import send_mass_mail from somemodels.models import Project import datetime import calendar def emails(request): today = datetime.date.today() weekday = today.weekday() month = datetime.date.today().month year = datetime.date.today().year cal = calendar.monthrange(year, month)[1] # az utolso nap az aktualis honapban firstday = datetime.date.today().replace(day=1) # az elso nap az aktualis honapban subject='hello' message='what's up?' from_email='myemail@gmail.com' for p in Project.objects.raw('SELECT * FROM somemodels_project INNER JOIN auth_user ON auth_user.id = othermodel_project.permitted_users'): recipient_list = p.email, print(recipient_list) if (today == firstday): messages = [(subject, message, from_email, [recipient]) for recipient in recipient_list] send_mass_mail(messages) print('Successfully sent') else: print('Not sent') return render(request, 'performance/emails.html') urls.py app_name = 'email' urlpatterns = [ path('emails/', login_required(views.emails), name='emails'), ] -
Django - dictionary update sequence element #0 has length 0; 2 is required
When I am logged out I cannot access my site anymore. Why does this happen? I doesn't matter what view I change I cannot access the site anymore. ValueError at /accounts/login/ dictionary update sequence element #0 has length 0; 2 is required Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 3.2.5 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 0; 2 is required Exception Location: /Users/lorenz/.conda/envs/netto_clone/lib/python3.10/site-packages/django/template/context.py, line 244, in bind_template Python Executable: /Users/lorenz/.conda/envs/netto_clone/bin/python Python Version: 3.10.4 Python Path: ['/Users/lorenz/PycharmProjects/netto_clone', '/Users/lorenz/PycharmProjects/netto_clone', '/Users/lorenz/Library/Application ' 'Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/213.6777.50/PyCharm.app/Contents/plugins/python/helpers/pycharm_display', '/Users/lorenz/.conda/envs/netto_clone/lib/python310.zip', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10/lib-dynload', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10/site-packages', '/Users/lorenz/Library/Application ' 'Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/213.6777.50/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend'] Server time: Fri, 01 Apr 2022 16:21:12 -0100 -
Django + Vue.js GET /ws HTTP/1.1 404 2292 error every second
I am building a project with Vue.js on the front-end and Django on the back-end. I am using port 8000 for Django and port 8080 for Vue.js. Every time I route to something on the 8080 port, I get this error like this that gets printed out every second: [01/Apr/2022 17:18:57] "GET /ws HTTP/1.1" 404 2292 Not Found: /ws I can't figure out why this happens or how to fix it. -
How to record audio from the mic and save it as a .wav file in django web app
I am trying to make and deploy speech emotion detection machine learning model using Django for that I have to take audio recording from the user before setting up the model, I am stuck at how can I take audio recording from the user and send it to my ML model to detect emotion. please help! -
Import csv file using django - form doesn't appear
I try to create a project and I need to import a csv file (Import csv file using django - Exception Type: DatabaseError) I want to display the form on other page, not on home. But, when I create a new path, it didn't display me that specific view. csvs/urls.py from django.urls import path from .views import upload_file_view app_name='csvs' urlpatterns =[ path('import/', upload_file_view, name='upload-view') ] csvs/views.py from django.shortcuts import render from .forms import CsvModelForm from .models import Csv import csv from django.contrib.auth.models import User from sales.models import Sales def upload_file_view(request): form = CsvModelForm(request.POST, request.FILES) if form.is_valid(): form.save() form = CsvModelForm() obj= Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: #row = "".join(row) #row = row.replace(";"," ") #row=row.split() #print(row) #print(type(row)) date = row[1] user = User.objects.get(username=row[0]) Sales.objects.create( date=date, product= row[2], user=user, ) obj.activated=True obj.save() return render(request, 'upload.html', { 'form': form }) main file - urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from sales.views import import_view, home_view urlpatterns = [ path('admin/', admin.site.urls), path('import/', import_view, name="import"), path('', home_view, name="home"), path('import/', include('csvs.urls', namespace='csvs')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) sales/views.py from django.shortcuts import render … -
How can I store data of registration into my django database?
I want to store data of patient from registration page to my django database using serializers but I am not sure how to do that!! Here I am attaching views.py file: from django.http import HttpResponse, HttpResponseForbidden from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from rest_framework import viewsets from .models import * from .serializers import PatientSerializer class PatientView(viewsets.ModelViewSet): queryset = patient.objects.all() serializer_class = PatientSerializer def login_user(request): if request.method == 'POST': username = request.POST['Username'] password = request.POST['Password'] user_type = request.POST['user_type'] user = authenticate(username=username, password=password) #doctor is superuser and receptionist is normaluser if user is None: login(request, user) if user_type == 'Doctor': return render(request,'') elif user_type == 'Receptionist': return render(request, 'Auth/registration.html') else: return render(request,'') else: messages.error(request, "Bad Credentials") return redirect('login') return render(request, "Auth/login.html") def registration(request): if request.method == "POST": username = request.POST['username'] PID = request.POST['PID'] Name = request.POST['Name'] Age = request.POST['Age'] DOB = request.POST['DOB'] gender = request.POST['gender'] BG = request.POST['BG'] PN = request.POST['PN'] Add = request.POST['Add'] else: if request.user.is_staff: return render(request,'Auth/registration.html') else: return HttpResponseForbidden('<h1> 403 Forbidden <br>You are not allowed to access this page.</h1>') This is my registration.html file : <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> … -
Making a GET request with filter
My model is the following class PokerRoom(models.Model): STATUS = (("Pending", "Pending"), ("Finished", "Finished")) status = models.CharField( max_length=11, choices=STATUS, verbose_name=_("Status da Story"), default="Pending", ) name = models.CharField(max_length=200, verbose_name=_("room name"), validators=[alphanumeric]) slug = models.CharField(max_length=200, verbose_name=_("room slug"), null=True, blank=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) styleCards = MultiSelectField(choices=CHOICES, default=FIBONACCI) datetime = models.DateTimeField(null=True, blank=True) date = models.CharField(max_length=10, null=True, blank=True) user = models.ForeignKey(User, on_delete=DO_NOTHING) first_name_user = models.CharField( max_length=200, verbose_name=_("user name"), null=True, blank=True ) deck = models.ForeignKey(Pack, on_delete=models.CASCADE) index = models.IntegerField( null=True, blank=True, verbose_name=_("story being voted") ) I'm my application, I want to make a searchbar for "status" and "name" and do a GET request with those filter that would be provided by the client when he make the search. But I don't know how to do that in my views.py I was thiking in a GET method like this, but I don't know how to get the planningName and planningStatus from the frontend. def get(self, request, pk): """GET of PokerRoom historic""" user = request.user pk = self.kwargs["pk"] planningName = planningStatus = moderatorRoom = PokerRoom.objects.values("id", "first_name_user", "date", "name", "status", "styleCards", "datetime", 'slug' ).filter(Q(user= user) | Q(name=planningName) | Q(status=planningStatus)).order_by("-datetime") Can someone helpe me?