Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use django-rest-framework to implement a method that can authenticate users and paginate
I saw some ways to implement paging with drf on the Internet.For example, the following method: def get(self, request, format=None): roles = Product.objects.all() pg = PageNumberPagination() page_roles = pg.paginate_queryset(queryset=roles, request=request, view=self) ser = ProductSerializer(instance=page_roles, many=True) return Response(ser.data, status=HTTP_200_OK) But this method only accepts a single number page number in the request query parameters.I hope this method can accept parameters about user information in order to authenticate user rights. -
Does Django Channels uses ws:// protocol prefix to route between Django view or Channels app?
I am running Django + Channels server using Daphne. Daphne server is behind Nginx. My Nginx config looks like as given at end. When I try to connect to ws://example.com/ws/endpoint I am getting NOT FOUNT /ws/endpoint error. For me, it looks like Daphne is using protocol to route to either Django views or Channels app. If it sees http it routes to Django view and when it sees ws it routes to Channels app. With following Nginx proxy pass configuration the URL always has http protocol prefix. So I am getting 404 or NOT FOUND in logs. If I change proxy_pass prefix to ws Nginx config fails. What is the ideal way to setup Channels in the this scenario? server { listen 443 ssl; server_name example.com location / { # prevents 502 bad gateway error proxy_buffers 8 32k; proxy_buffer_size 64k; # redirect all HTTP traffic to localhost:8088; proxy_pass http://0.0.0.0:8000/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #proxy_set_header X-NginX-Proxy true; # enables WS support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 999999999; } } -
How to include a field in search_fields if the model is inline in wagtail
I am trying to include a field in search say class BaseClass and I want to search a field in class Subclass which is inherited from class Orderable and ParentalKey with BaseClass how to add the field of subclass in search_field class BaseClass(Page): header = models.CharField(max_length=255, blank=True) search_fields = Page.search_fields + [ index.SearchField('title', partial_match=True) class SubClass(Orderable): article = ParentalKey('BaseClass',on_delete=models.CASCADE, related_name='article_description') body = RichTextUploadingField(_('Body'), blank=True) -
While sorting: '<' not supported between instances of 'NoneType' and 'str'
I am trying to remove all duplicate and null elements of an array, then sorting it. cities = [js.city for js in company_jscollects] filter(None, cities) cities_unique = list(sorted(set(cities))) But then I got this error: Django Version: 2.0.4 Exception Type: TypeError Exception Value: '<' not supported between instances of 'NoneType' and 'str' Exception Location: D:..\views.py in dashboard_analytics, line 175 Line 175 being the one including the sorted function. I am pretty confused because the error tells that there are None elements being compared to Strings, but I used filter to avoid that in the first place. -
Django: comment_create() got an unexpected keyword argument 'pk' error
I am now implementing a comment function on the post_detail page. but occurred comment_create() got an unexpected keyword argument 'pk' error. I also tried to change the def comment_creat(request, post_pk): part to def comment_creat(request, pk): on views.py. and I try {% url 'comment_create' pk=post.pk %} --> post_pk=post.pk views.py @login_required def comment_create(request, post_pk): if request.method == 'POST': post = get_object_or_404(Post, pk=post_pk) content = request.POST.get('content') com_user = request.user if not content: messages.info(request, 'Write please') return redirect('post_detail', post_pk) Comment.objects.create(post=post, comment_user=com_user, comment_content=content) return redirect('post_detatil', post_pk) urls.py path('post_detail/<int:pk>/comment_create/',views.comment_create, name='comment_create') post_detail.html <form action="{% url 'comment_create' pk=post.pk %}" method="POST"> {% csrf_token %} <input type="text", name="content", placeholder="comment..."> <input type="submit", value="Go"> </form> Please help me. -
Throwing error saying that context must be a dict rather than str
I am newbie to dJango. What I want is that passing the data from view.py to .html in order to handle the data from the models. However, I had a hard time passing the data from view to html page. My code is as shown in below. form.html <!DOCTYPE html> <meta charset="utf-8"> {% load staticfiles %} <form method="post" action="../form/" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="files" multiple/> <input type="submit" value="Upload"/> </form> <form method="post" action="../form/" enctype="multipart/form-data"> {% csrf_token %} {% for c in column_name %} <tbody> <tr> <td>{{c}}</td> <td><input type="checkbox" name="columns" value="{{c}}"></td> </tr> </tbody> {% endfor %} {% if column_name %} <input type="submit" value="Submit"> {% endif %} </form> <script> var data = {{ columns_dict|safe }}; console.log(data); </script> views.py def Form(request): if request.method == 'POST': if len(request.FILES) !=0: file = request.FILES['files'] column_name = upload_file_name(file) return render(request,"index/form.html",{"column_name":column_name}) else: columns = request.POST.getlist('columns') print(columns) columns_dict = dict(columns) print(columns_dict) return render(request,"index/form.html",json.dumps(columns)) else: return render(request,"index/form.html",{}) As you can see, I have been trying to pass the data in the code below. return render(request,"index/form.html",json.dumps(columns)) However, in the html page, the script block <script> var data = {{ columns_dict|safe }}; console.log(data); </script> it cannot show the data from view.py. I can see the error below. context must be a … -
Deploy a Django Application to Digital Ocean - Gunicorn Error
I'm trying to deploy my first app to digital ocean with help of this tutorial. When I try to run sudo supervisorctl restart [appname], I get the following error. (This is only a part of the error) [2019-01-16 09:10:49 +0000] [2653] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/srimal/django_project/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/srimal/django_project/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/srimal/django_project/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/srimal/django_project/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/srimal/django_project/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/srimal/django_project/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/srimal/django_project/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/srimal/django_project/productUploader/shadesProductUploader/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/srimal/django_project/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/srimal/django_project/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/srimal/django_project/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/srimal/django_project/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/srimal/django_project/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'authSection' My setup in the server is and the supervisor config file #!/bin/sh [program:productUploader] command=/home/srimal/django_project/bin/gunicorn_start user=srimal autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/srimal/logs/gunicorn-error.log and the gunicorn_start file #!/bin/bash NAME="productUploader" DIR=/home/srimal/django_project USER=srimal GROUP=srimal WORKERS=3 BIND=unix:/home/srimal/run/gunicorn.sock DJANGO_SETTINGS_MODULE=productUploader.shadesProductUploader.settings DJANGO_WSGI_MODULE=productUploader.shadesProductUploader.wsgi LOG_LEVEL=error cd $DIR source /home/srimal/django_project/bin/activate export … -
How can I update the photo each second in my django template?
everyone. I am pretty new with django. There is a particular position to show the photo in my django template, and the photo should be updated each second. How can I do that? (Paths for new photos come from the database. I know how to get them from db.) I only know how to return a html with a url request, but how can I update a particular item in that html without a new url request? -
Django App on Chrome - Very Slow Performance
I'm desperate posting this question here as I'm having problems that I cannot solve with Django and Chrome. For some reason, which I have not been able to identify, my Django app on the development server as well as the production server gets slowed down by up to 50 times after a while of use (maybe 5 minutes or so). The only thing that 'resets' it back to normal is if I close Chrome, open Chrome, and open the website again. Restarting the development/production server does not work. Closing and reopening the website tab in Chrome does not work. I have a feeling that Chrome is the problem here as I think I've noticed similar issues while browsing StackOverflow. I know of the Django performance issues guide: https://docs.djangoproject.com/en/2.1/topics/performance/ However note that my database is barely populated with anything so it is definitely not a Django performance issue. There is something else going on here. Any idea where to start with fault finding? Thanks for your help -
How to print api in django console instead if queryset
serializers.py from rest_framework import serializers from access.models import SeekerRegister from .models import CandidateDetails,Social,CvDetails,KeySkills,CandidateCompanyDetails,CandidateEducationDetails,ContactInfo class MainSeekerSerializer(serializers.ModelSerializer): class Meta: model = SeekerRegister fields = ('contact_info', 'candidate_details','social', 'cv_details','key_skills', 'candidate_company_details', 'candidate_education_details', 'seeker_language', 'seeker_name','seeker_email', 'seeker_contact_no','verified') depth = 1 views.py class AdvanceSearchViewSet(viewsets.ReadOnlyModelViewSet): queryset = SeekerRegister.objects.all() serializer_class = MainSeekerSerializer def get_queryset(self): queryset = SeekerRegister.objects.all() if self.request.query_params.get('skills_any', None) is not None: skills_any = self.request.query_params.get('skills_any', None).split(",") else: return JsonResponse({"code":401,"msg":"skills_any is required"}) if self.request.query_params.get('skills_must', None) is not None: skills_must = self.request.query_params.get('skills_must', None).split(",") else: skills_must = None if (skills_any is not None and skills_must is None: filters = Q(key_skills__skills__in=skills_any) & Q(key_skills__skills__in=skills_must) else: filters = Q(key_skills__skills__in=skills_any) queryset = queryset.filter(filters) print(queryset) return queryset result in browser: [ { "key_skills": [ { "id": 1, "skills": "python", "versions": "3.600", "experience": "2.000", "user": 3 }, { "id": 4, "skills": "angular", "versions": "3.600", "experience": null, "user": 3 }, { "id": 5, "skills": "java", "versions": "16.060", "experience": null, "user": 3 } ] } ] In console when i am printing queryset it is coming How can i get api in console whatever i am getting in browser. Because i have edit something in the skills of dictionary. Please have a look. I have sharded serializers and view file . is there any way to modify the api. -
Nginx: 502 BAD GATEWAY while deploying django to AWS EC2 instance
I am trying to deploy a django website on aws EC2 instance with Nginx. I am getting the following error. *1 connect() failed (111: Connection refused) while connecting to upstream, client: **.***.***.***, , server: **.**.***.*, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "*.amazonaws.com" In /etc/nginx/sites-available folder I have a file with the following configurations server{ listen 80; server_name your_public_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/mySiteFolder; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } } Where is the mistake that I am committing? Thank you in advance. -
Update data in profiles model,using extended django User model
I'm trying to create a project where I need user profiles.I have extended django default User. I am able create users successfully,but I'm not able to add data into profile model, for example: I have created user an user 'Demouser', user is successfully created and I'm also able to login with created user.But next step is to updata data about 'Demouser' in profiles model,for that I have created register view and form but doesn't seem to work. Forms.py file: class ProfileForm(forms.ModelForm): class Meta: model = profiles exclude=( 'id','Username','User', ) Models.py : class profiles(models.Model): class Meta: verbose_name_plural='Profile\'s' Username=models.OneToOneField( User, on_delete=models.CASCADE, unique=True, related_name='profile', ) first_name=models.CharField( max_length=25, ) last_name=models.CharField( max_length=25, ) email_id=models.EmailField() previous_projects=models.TextField( null=True, blank=True, ) Views.py : class ProfileEditView(views.View): def get(self,request,*args,**kwargs): if request.user.is_authenticated: return render(request,'editprofile.html',context={'form':ProfileForm}) else: messages.success(request,('You must Login into system for access')) return redirect('profiles:Login') def post(self,request,*args,**kwargs): user=User.objects.get(username=request.user.username) print(user) form=ProfileForm(request.POST,instance =user) if form.is_valid(): form.save() messages.success(request,('Profile Edited succesfully')) return render( request, 'editprofile.html', context={ 'form':ProfileForm } ) When I update the data using ProfileEditView, suppose I update the First name of logged in User, The data is updated in default django User model , I want it to be updated in my profiles model... thanks in advance -
can't run Django into productions with Apache and mod_Wsgi
I never done setup of server before this my first time, for past 7 days I'm been trying to setup and lunch the server to production, where input a pre-built django codes into the server. I had try and modified lot of things to troubleshoot several different errors, in the end I just delete the folder of Apache24 and download a new ones (link:https://httpd.apache.org/download.cgi#apache24) here's the erros issue: C:\WINDOWS\system32>C:\Frontier_Website\Apache24\bin\httpd.exe -k start (OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : AH00072: make_sock: could not bind to address [::]:8050 (OS 10048)Only one usage of each socket address (protocol/network address/port) is normally permitted. : AH00072: make_sock: could not bind to address 0.0.0.0:8050 AH00451: no listening sockets available, shutting down AH00015: Unable to open logs This are my error logs: Starting the 'Apache2.4' service The 'Apache2.4' service is running. pm_winnt:notice] [pid 11084:tid 620] AH00455: Apache/2.4.37 (Win64) configured -- resuming normal operations [Wed Jan 16 16:34:12.381577 2019] [mpm_winnt:notice] [pid 11084:tid 620] AH00456: Apache Lounge VC15 Server built: Nov 21 2018 11:51:35 [Wed Jan 16 16:34:12.381577 2019] [core:notice] [pid 11084:tid 620] AH00094: Command line: 'C:\\Frontier_Website\\Apache24\\bin\\httpd.exe -d C:/Frontier_Website/Apache24' [Wed Jan 16 16:34:12.404151 2019] [mpm_winnt:notice] [pid 11084:tid 620] AH00418: Parent: Created child … -
D3.js how do i make the last child into a clickable link that passes the text variable associated with it? e.g. href = link
I am using this codes: https://bl.ocks.org/mbostock/1283663 I am setting up a django project. How do i to make the last bar chart (last child) into a clickable link that passes the text variable associated with it. -
Django: How to redirect when rendering form using custom templatetag
I want to make form on modal and I created custom templatetag for rendering it so I can use it for every views. But I still don't get how I can redirect to a page after submission. The templatetag is supposed to return form so I cannot return HttpResponseRedirect. templatetag @register.simple_tag(takes_context=True) def render_profile_form(context): """render Profile edit form for every views""" request = context['request'] if 'profile_form' in request.POST: profile_form = ProfileForm(instance=request.user, data=request.POST, files=request.FILES) if profile_form.is_valid(): profile_form.save() # message here # return to the current url else: profile_form = ProfileForm(instance=request.user) return profile_form here is modal part {% render_profile_form as profile_form %} <form method="POST" enctype="multipart/form-data"> <div class="modal fade" id="editProfileModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> {% csrf_token %} <div class="form-group"> {% if profile_form.photo.errors %} <div class="alert alert-danger">{{ profile_form.photo.errors }}</div> {% endif %} <label>{{ profile_form.photo.label }}</label> {{ profile_form.photo }} </div> <div class="form-group"> {% if profile_form.first_name.errors %} <div class="alert alert-danger">{{ profile_form.first_name.errors }}</div> {% endif %} <label>{{ profile_form.first_name.label }}</label> {{ profile_form.first_name|add_class:'form-control' }} </div> <div class="form-group"> <label>{{ profile_form.last_name.label }}</label> {{ profile_form.last_name|add_class:'form-control' }} </div> <div class="form-group"> <label>{{ profile_form.bio.label }}</label> {{ profile_form.bio|add_class:'form-control' }} </div> </div> <div class="modal-footer"> <button type="submit" name="profile_form" class="btn btn-primary">Save</button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </form> Anyone knows … -
When django project is runing, how to independently run a python command to change data by django ORM?
My django project is running, at same time I want to use python-fire moudle in my fire_command.py for updating data manually. like this: python fire_command.py ManagementCommand change_data --date=20190101 management is one of my apps, structure as below: ├── management ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tasks.py ├── tests.py ├── urls.py ├── fire_command.py fire_command.py: import datetime, os, sys import fire BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(BASE_DIR)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') from management.models import ModelOne class ManagementCommand(object): def change_data(self, date): model_one_obj = ModelOne.objects.all().first() model_one_obj.dt = date model_one_obj.save() if __name__ == '__main__': fire.Fire() My problem My problem is when I run python fire_command.py ManagementCommand change_data --date=20190101 , it raise error AppRegistryNotReady("Apps aren't loaded yet.") can you help me about it, what should i do to make it correctly running.. great thanks.. -
Add Extra Option Tag to Select Field - Django
I am using crispy forms to build my form. Now i want to add one more extra <option> tag with value in my timesheet_jobs field which is Foreign Key Field. Please help me to add one more extra <option> field in my <select> at the end after loading all the options. forms.py class ClockInForm(forms.ModelForm): class Meta: model = TimesheetEntry fields = ['timesheet_jobs', 'timesheet_clock_in_date', 'timesheet_clock_in_time'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) -
How to deploy on AWS Lambda with Zappa through Git
I am looking for ways to deploy on AWS Lambda with ZAPPA through my github repository. I couldn't find any videos or blogs about this. Does anyone know -
sessionid gets deleted from the cookie after browser redirection through SAML authentication - Python/Django
I have a Python/Django web based application hosted in production. The application needs SSO login to get redirected to our application. I'm using SAML authentication process for the logging of users. I have written a django middleware to capture the "sessionid" from the cookie after successful login to display user details in my application homepage. The sessionid is being seen in the browser cookie after successful login but once it gets completely redirected to my application it goes off. Due to this i couldn't able to capture the sessionid from the request.COOKIES after browser refresh/navigation. I'm also storing a session key in request.session to display the user details unless it's a new request/session expiry. But for the next time page refresh, the session is gone. Is there a way where i can store the sessionid after first time login? -
Django, JQuery and Updating img tag in html
In my project, I would like to convert a pdf to image, then show it to the user on the screen. I have created image under some directories. I have passed the path to the JQuery, however, it cannot find the path. I pass the path below to the JQuery {"path":"/home/USERNAME/Desktop/PROJECTNAME/src/FOLDER1/FOLDERID/pdf/image.png"} When I inspect Network field in the browser, I can see this: Using the URLconf defined in PROJECTNAME.urls, Django tried these URL patterns, in this order: ^$ admin/ SUBFIELD1/ SUBFIELD2/ ^$ [name='index'] SUBFIELD3/ The current path, home/USERNAME/Desktop/PROJECTNAME/src/FOLDER1/FOLDERID/pdf/image.png, didn't match any of these. Note that, SUBFIELD's and FIELD1 are not equal. Here is my folder schema under src Project FIELD1 FOLDERID pdf image.png SUBFIELD1 migrations folder admin.py models.py ... SUBFIELD2 same as SUBFIELD1 SUBFIELD3 same as SUBFIELD1 The JQuery code for showing image to the user function getpdf() { $.getJSON('/SUBFIELD1/convertPdf2Image/',function (data) { $('#myimage').attr('src', ''); $("#myimage").attr('src', data.path); }); } Html Code <img id="myimage" style="width:500px;height:600px;"/> -
Custom Middleware blocking my Password Reset View
I had made a Custom Middelware to secure all my views at once and made a custom decorator to exempt login and register/signup functions so that they're accessible to visitors. But when i tried to reset my password using the password-reset, i couldn't as it redirected me to login page, this system worked earlier when i had not put my Custom middelware inside the settings.py Middleware.py from django.contrib.auth.decorators import login_required def login_exempt(view): # <-- Custom Decorator view.login_exempt = True return view class LoginRequiredMiddleware: # <-- Custom Middleware def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): if getattr(view_func, 'login_exempt', False): return if request.user.is_authenticated: return return login_required(view_func)(request, *view_args, **view_kwargs) Settings.py 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', #custom auth middleware 'dashboard.middleware.LoginRequiredMiddleware', ] Now, if i remove my custom middleware i'm able to visit my password-reset. So what should i do to exclude my Auth Views using my Login_exempt Custom Decorator. TIA UrlCONF from django.urls import path,include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include("myapp.urls")), path('accounts/', include('django.contrib.auth.urls')) ] if settings.DEBUG: urlpatterns += (static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)) -
Update the PostgreSQL Database every hour via python script or using django models?
I am setting a web server based on Django Framework with PostgreSQL. I need to update the models in my Django app every hour and I am wondering if is it better way to update the database from another script file using python and psycopg2 or using script that directly connects to Django models and update them using Django API for models? I use this Database only in Django web server. Summarizing... What is better logic? update_db.py that contains: connect to database via psycopg2, update the tables update_db.py that contains: connect to Django app models, update them using Django API for models I will run script every hour using Cron, and the Django Project is already connected to that specific database and it works fine. I am just asking for better performance and better way in logic sense. Data won't be updated very often but it would have big jsons. -
How to run django + email handler in App Engine
I try to run django and email handler app together in Google App Engine. I use code as google's doc and it must be run with python27. When I converted to code for python37 got script must be set 'auto' error. Can anyone help me? My code as below. Thanks in advance app.yaml runtime: python37 entrypoint: gunicorn -b :$PORT myproject.wsgi env_variables: ... inbound_services: - mail - mail_bounce handlers: - url: /static static_dir: static - url: /_ah/mail/.+ script: handle_incoming_email.app login: admin handle_incoming_email.py import logging from google.appengine.ext.webapp.mail_handlers import InboundMailHandler class IncomingMailHandler(View, InboundMailHandler): def receive(self, mail_message): logging.info("Received a message from: " + mail_message.sender) when I run this error raises from 'script: handle_incoming_email.app' script must be set 'auto'. How can I get handle_incoming_email.py to app.yaml if I set script: auto. change '.+' as '.*' have tried. -
Error: Duplicate foreign key constraint name
I exported a schema from workbench and now trying to use that script to create table in my server, But getting error I tried to change the table and also tried to find duplicate foriegn key. ERROR 1826: Duplicate foreign key constraint name 'bank_id' SQL Statement: -- Table aditya.users_has_bank CREATE TABLE IF NOT EXISTS aditya.users_has_bank ( users_user_id INT NOT NULL AUTO_INCREMENT, bank_id INT NOT NULL, user_id INT NOT NULL, PRIMARY KEY (users_user_id), INDEX bank_id_idx (bank_id ASC) VISIBLE, INDEX user_id_idx (user_id ASC) VISIBLE, CONSTRAINT bank_id FOREIGN KEY (bank_id) REFERENCES aditya.bank (bank_id) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT user_id FOREIGN KEY (user_id) REFERENCES aditya.users (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB -
Can't get form data in view function: Django
I need to submit a string to a view function via a dropdown menu and submit button. in my template I have: <form action="{% url 'exec_task' %}" method="post"> {% csrf_token %} <select id="select_task" form="select_task" name="select_task"> {% for task in available_tasks %} <option id="selected_task" value="{{ task }}">{{ task }}</option> {% endfor %} </select> <input class="button" type="submit" value="Run Selected Task"> </form> in my view function I have: def exec_task(request): if request.method == 'POST': task = request.POST.get('select_task') print(task) getattr(tasks, task)(0) return redirect('management') The print(task) always comes out as None, which generates an error when I try to call it via getattr in the next line. I've read through all the questions and tutorials I can find on this and I don't know what I'm doing wrong, but when I print the request.POST object, all I get is the csrf token. The QueryDict has nothing else in it. Any ideas?