Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i have a issue in view job button in Django Project
I am new in Django and I am trying to do my project and I have an issue in that project. in my project, I have a view job button and whenever I click on any job or view job then it will redirect to another page and on that page, I want to show a full description of that job so please help me. thank you. this is my views.py def BrowseJob(request): all_job = jobs.objects.all() myFilter = jobsFilter(request.GET, queryset = all_job) all_job = myFilter.qs return render(request,'jobs.html',{'all_job':all_job,'myFilter':myFilter}) this is urls.py from django.urls import path from . import views urlpatterns = [path('',views.index,name='index'), path('Browse_Job',views.BrowseJob,name='Browse_Job'), path('contact',views.contact,name='contact'), path('job_details',views.jobdetails,name="job_details")] this is my job.html {% for job in all_job %} <div class="job_lists"> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="single_jobs white-bg d-flex justify-content-between"> <div class="jobs_left d-flex align-items-center"> <div class="thumb"> <img src="{{job.job_img.url}}" alt=""> </div> <div class="jobs_conetent"> <a href="job_details"><h4>{{job.job_name}}</h4></a> <div class="links_locat d-flex align-items-center"> <div class="location"> <p> <i></i>{{job.job_Category}}</p> </div> <div class="location"> <p> <i></i>{{job.job_Experience}}</p> </div> </div> </div> </div> <div class="jobs_right"> <div class="apply_now"> <a href="job_details" class="boxed-btn3">View Job</a> </div> <div class="date"> <p>Last Date for Apply: {{job.last_date}}</p> </div> </div> </div> </div> </div> </div> {% endfor %} this is my jobdetails.html {% for job in all_job %} <img src="{{job.job_details.url}}" alt=""> {% endfor %} please help … -
FullCalendar Some Events (not all) on Wrong Dates
I am listing dates on FullCalendar and as you can see in the image, some dates show up correctly and some don't. I cannot find any reason that this is the case. The only thing the incorrect events have in common is that they have a start time of 8pm or later. I selected the August 17th, which has two events. Only one shows correctly on the calendar. Here is my event code: events: [ {% for event in connected_events %} { title: "{{event.event_title}}", start: "{{event.start_time|date:'c'}}", end: "{{event.end_time|date:'c'}}", url: "{% url 'events:event-detail' event.unique_id %}", details: "test", {%if event.budget_amount > 0 and event.lfg_state == 'LFGM' %}color : "#ff8f07"{%elif event.budget_amount <= 0 and event.lfg_state == 'LFGM' %}color : "#d943c5"{%elif event.budget_amount > 0 and event.lfg_state == 'LFP'%}color : "#1ad914"{%else%}color:"#38b3ff"{%endif%}, }, {% endfor %} -
Django ValueError: Unable to configure handler 'file'
I'm having a hard time because my django project. I have a hard time because I'm a django beginner. Please share your wisdom in solving this problem. python3 manage.py runserver Problems arise when a project is executed. Change settings.py import os from dotenv import load_dotenv load_dotenv() ... SECRET_KEY = os.getenv('SECRET_KEY') DEBUG=os.getenv('DEBUG') DATABASES = { 'default': { 'ENGINE': os.getenv('DB_ENGINE'), 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } ... and then I met this error message. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 562, in configure handler = self.configure_handler(handlers[name]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 735, in configure_handler result = factory(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py", line 148, in __init__ BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py", line 55, in __init__ logging.FileHandler.__init__(self, filename, mode, encoding, delay) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1087, in __init__ StreamHandler.__init__(self, self._open()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1116, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: '/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/logs/logfile' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, … -
Image Not Found Using HTML/Django
Django cant find jpg. It is in the same folder as my html. Tried everything i could, I have no idea why this is happening. I am using index.html. Tried different files, different file paths, different file types...etc. File isnt corrupted, program works fine for everything else. File Locations <div> <img src="portBack.jpg" alt=""> </div> -
Django postgresql ArrayField with default of callable raises error while running tests
Looks like when I when I use the callable as recommended, I get this error when trying to run tests on my project. I do not have this issue if I us [] as the default or if I have done that or pass "--keepdb". django.db.utils.ProgrammingError: type "citext[]" does not exist LINE 1: ...RIMARY KEY, "role" varchar(16) NOT NULL, "emails" citext[] N... I am not sure what is happening here. I think my version of postgresql is >11. -
TypeError: Post() got an unexpected keyword argument 'body' in command line while working on query set
I am working on creating a blog app in Django and while I was making the Query set in cmd I got the following error, CODE IN CMD: from django.contrib.auth.models import User >>> from blog.models import Post >>> user = User.objects.get(username='mratyunjay') >>> post = Post(title='Another post', ... slug='another-post', ... body='Post body.', ... author=user) ERROR : Traceback (most recent call last): File "<console>", line 4, in <module> File "C:\Users\Computer\Desktop\project\my_env\lib\site-packages\django\db\models\base.py", line 501, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Post() got an unexpected keyword argument 'body' admin.py :- from django.contrib import admin # Register your models here. from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ( 'title', 'slug', 'author', 'publish', 'status') list_filter = ( 'status', 'created', 'publish', 'author') search_fields = ( 'title', 'body' ) prepopulated_fields = {'slug': ('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ( 'status', 'publish' ) models.py:- from django.db import models # Create your models here. from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = … -
How to make a same field as Dropdown or Char Field in Django
I am having a Django custom form in this its having one field that need to be dropdown / Char Field Thease are my forms class VehicleDetails(forms.ModelForm): vehicle_type = forms.ModelChoiceField( queryset=List.objects.all(), required=True, widget=forms.Select(attrs={'data-init-plugin': 'select2', 'data-item': 'true'})) class VehicleForm(forms.Form): vehicle = forms.ModelChoiceField(queryset=None, required=True, widget=forms.Select( attrs={'data-init-plugin': 'select2', 'request': 'true', 'data-item': 'true'})) def __init__(self, project=None,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['vehicle'].queryset = Vehicles.objects.all() if vehicle: self.fields['vehicle'].initial = vehicle My issue is if I am selecting vehicle_type as car/bike it need to be shows a dropdown ...... But if I select other it need to be a char field in the form So users can enter the details...... -
Django: too many values to unpack (excpected 2) error (.objects.filter)
I am trying to remake the project alone that I've already finished with my team. What i want to do is to make the project almost the same with the one we've done. We worked with 3 apps-User, Product, Order-so this time again, I'll go with those 3 apps. And I decided to do it with the DB(going to call it 'old DB') that we've already built because whole environment of this project setting is just the same with the previous one. After connecting the old DB on settings.py, I wrote User app's views.py to try SignUp and SignIn API, and it didn't work. I realised that I didn't write other apps' models.py to make old DB work fine(because the old DB consists of info from all the apps we made-all three apps' models.py are connected to each other with foreign keys). So, I wrote every piece of models.py of all the apps(User, Product, Order) to figure out this issue. However, the same error occurs. Traceback (most recent call last): File "/Users/soomialexhwang/miniconda3/envs/superfluid/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/soomialexhwang/miniconda3/envs/superfluid/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/soomialexhwang/miniconda3/envs/superfluid/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
Slow iframe ReactJS and Django
It is the first time that I ask a question here, I always read their answers and they help me a lot. I am developing a web page in ReactJS that receives information from surveillance cameras that come from the backend that is mounted in django, my problem is that I am showing them through an iframe on the frontend and they are seen with terrible fluency and I need that the visualization is online since in the current way it does not serve me. I leave you some code snippets to see if you can help me. Thank you! I have tried with react-video, react-player and it does not play anything (it remains black) I have only been able to show it with iframes and as an object import React from 'react'; import { FullScreen, useFullScreenHandle } from "react-full-screen"; function OnFullScreen() { const handle = useFullScreenHandle(); const url = sessionStorage.getItem('url'); return ( <div> <FullScreen handle={handle} id="fullScreen"> <iframe title = "iFrame" frameBorder = "0" allowFullScreen scrolling = "no" src={`http://localhost:8000/video_feed/${url}`} id="iFrame" > Su Navegador Web no admite iFrames. </iframe> </FullScreen> <button onClick={handle.enter} className="btn btn-success mb-5 mt-2"> Pantalla Completa </button> </div> ); } export default OnFullScreen; -
IntegrityError: UNIQUE constraint failed: users_customuser.email
I'm a beginner at Django and this is my first project without a book or tutorial. I started my project with a Custom User class, base on AbstractUser. After that, I used the third-party package django-allauth to handle user registration flow, and it all worked fine. Users could only sign up and login with their email and username was not required as expected. The problem started when I changed the sign up form in the django-allauth configs. In this new form I added some custom fields when the user signed up, but that gave me this error that I can't fix. One important thing is that the new users are created, even though I keep getting this error. I've read a lot of question on the same issue but none helped me to fix my problem. Here is my models.py: class CustomUser(AbstractUser): email = models.EmailField(verbose_name="Email", unique=True, max_length=250) first_name = models.CharField(verbose_name="Nome", max_length=100, null=True) last_name = models.CharField(verbose_name="Sobrenome", max_length=250, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'university', ] My forms.py: class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'first_name', 'last_name', 'major', 'university',) class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ('first_name', 'last_name', 'major', 'university',) And my admin.py: class CustomUserAdmin(UserAdmin): … -
How should I call API request automatically from Twitter?
I want user's tweet data whenever they tweet new. But without running script every 15 minutes to know whether they have new tweet or new. It takes lots of resources. Is there any way that I will get data only when they tweet? -
How to prevent AWS EC2 server from running indefinitely?
I have a Django app that users can submit video through to be processed via a python script running OpenCV on a separate EC2 instance. As this is a moderately expensive server to run (p2.Xlarge ~ $3.00/h) it is only spun up when the video is submitted and I want to ensure that it doesn't continue to run if there is some hiccup in the processing. If the program works fine the instance is properly shut down. The problem is sometimes the python script gets hung up (I can't seem to replicate this on it's own which is a separate problem) when the script doesn't fully execute the server continues to run indefinitely. I have tried the solution provided here for self terminating an AWS EC2 instance. The solution works if the server is idle but doesn't seem to work if the server is busy trying to process the video. Is there a better way to make sure the server doesn't run longer than x minutes and stop it, even if the server is in the middle of a process? The code I'm currently using: import paramiko import boto3 import sys from botocore.exceptions import ClientError import json from time import … -
how to manage websocket connection in django use asgi
my application like this # asgi.py import os from django.core.asgi import get_asgi_application from websocket_app.websocket import websocket_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_app.settings') django_application = get_asgi_application() async def application(scope, receive, send): if scope['type'] == 'http': # Let Django handle HTTP requests await django_application(scope, receive, send) elif scope['type'] == 'websocket': # handle websocket connections here await websocket_application(scope, receive, send) else: raise NotImplementedError(f"Unknown scope type { scope['type'] }") # websocket.py async def websocket_application(scope, receive, send): while True: event = await receive() if event['type'] == 'websocket.connect': await send({ "type": "websocket.accept" }) if event['type'] == 'websocket.disconnect': break if event['type'] == 'websocket.receive': try: # result = json.loads(event['text']) await route(scope, event, send) except Exception as e: await send({ "type": "websocket.send", "text": e.__repr__() }) I want to send a message to A client when I received a message from B client, but i have no idea how can I find a websocket connection and send message to A client. I think I should do something to manage multiple websocket connection, but I have no idea how to do it. -
How to use 'view.kwargs' correctly
I am trying to add a Profile Image for a user in a page next to his username which is working fine and I have tried to use the same logic to add the profile image but it didn't work and I don't know what is the reason, there is no error message showing it is simply not showing because probably it is not written correctly. I am trying to understand how to use the query function correctly so this is a trial for me Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username'), profile=self.kwargs.get('profile')) <---------------------------- Here is my trial to add profile return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted') Here is the template {{ view.kwargs.username }} <---------------------- Showing correctly <embed class="profile_image" src={{ view.kwargs.user.profile.image.url }}> <------------- not appearing -
photoshop 3d mockup change its texture programmatically
I'm plannin on buying 3d mockups for my products. My website is using django. Before I used to use blender on server to make mockups like below: when a user / administrator uploads a product dlajgo celery to put a texture of image / color on the product using blender/pyton script but I found out there is similar function on photoshop. https://creativemarket.com/webandcat/3770816-Folded-Fabric-Mock-up I really would like to use this mockup and would like to know if there is any similar way to programmatically change its texture image like blender/python on server side(centos 7) Thanks! -
.env keyError in django project
I'm having a hard time because my django project. Who can help? I'd like to thank you for your help. set .env in proeject Root path SECRET_KEY=exampleKey DEBUG=False DB_ENGINE=django.db.backends.mysql DB_NAME=example DB_USER=admin ...Blah Blah project settings.py import os import environ env = environ.Env(DEBUG=(bool, False), ) environ.Env.read_env() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG') ...Blah Blah And when run the project I get an this error message. Django_workspace/asone/asone/.env doesn't exist - if you're not configuring your environment separately, create one. "environment separately, create one." % env_file) raise KeyError(key) from None KeyError: 'SECRET_KEY' During handling of the above exception, another exception occurred: /Django_workspace/asone/venv/lib/python3.7/site-packages/environ/environ.py", line 277, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable I have a hard time because I'm a django beginner. Who can help? I'd like to thank you for your help. thank you for watching I'll be waiting for your response -
Is there a way to have a list type object in Django models?
I'm starting my first solo Django project and have run into how to store things on my database. What I'm doing is trying to create a web-based grocery store. I'm wanting to add an order model where I can store a user and then a list or optimally a dictionary of what they want. I know the dictionary may be a stretch, but is there some way to create a model list? I've looked at similar questions and seen the JSON option I'm not really sure how I can make that work since I can't manipulate that in the admin. Thanks in advance. -
Not able to save foreign key serializer value
I have two models namely Media and Source. Source is a foreign key field in Media table. Below code shows the Serializer needed by REST API and to save the Media information. What problem I am facing is that whenever I tried to POST data on MEDIA rest end point, Source value is not getting stored. It shows null. {"id":44,"category":["deepfake"],"source":null,"status":"under_review","nsfw":false,"severity":"unknown","title":"Lakshmi Menon Deepfake(Bollywood Sexy Tease)","description":null,"type":"video","url":"https://adultdeepfakes.com/v1940539","file":"https://adultdeepfakes.com/wp-content/uploads/videos/B_LAKSHMI_MENON_AS_MAID_FUCKING_TRAILER_PAID_REQ_o_c_optimized.mp4","image":null,"data":{"views":"213","likes":"1","dislikes":"0","tags":""},"published_at":"2020-08-20T09:00:39Z","created_at":"2020-08-21T00:37:06.654294Z","updated_at":"2020-08-21T00:37:06.654305Z","persons":[]} What I tried is remove source = SourceSerializer(many=False, read_only=True) code and save. It works!! But then in rest api it doesn’t show the source details. Can anyone please advise me how I could get best of both the worlds? class MediaSerializer(serializers.ModelSerializer): """Serializer for the Media model """ category = CustomSlugRelatedField( queryset=Category.objects.all(), many=True, read_only=False, slug_field="name", ) source = SourceSerializer(many=False, read_only=True) class Meta: model = Media fields = "__all__" read_only_fields = [ "created_at", "updated_at", ] -
Redirected to index after search query in another url in Django
so I added another html page to my project besides the index. The page technically works but it does not render any results, only redirects me to index expressing the result of the else condition in that function. I am not sure why this is happening, it's as if the search queries of my html template were not working. This is my view: from django.shortcuts import render, HttpResponse from django.views.generic import ListView import requests def people(request): people = [] if request.method == 'POST': people_url = 'https://ghibliapi.herokuapp.com/people/' search_params = { 'people' : 'name', 'people' : 'gender', 'people' : 'age', 'people' : 'eye_color', 'q' : request.POST['search'] } r = requests.get(people_url, params=search_params) results = r.json() if len(results): for result in results: people_data = { 'Name' : result['name'], 'Gender': result['gender'], 'Age' : result['age'], 'Eye_Color' : result['eye_color'], 'Films' : result['film'] } people.append(people_data) else: message = print("No results found") print(people) context = { 'people' : people } return render(request,'core/people.html', context) def index(request): movies = [] if request.method == 'POST': film_url = 'https://ghibliapi.herokuapp.com/films/' search_params = { 'films' : 'title', 'films' : 'description', 'films' : 'director', 'films' : 'release_date', 'q' : request.POST['search'] } r = requests.get(film_url, params=search_params) results = r.json() if len(results): for result in results: movie_data = … -
raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES
I want to create a new app using 'python manage.py startapp' in my files but I am getting this error. raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. here is the databases in my seetings.py: DATABASES = { 'default': dj_database_url.config(), } db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) This is after migrating to heroku. -
Why am I still getting 'DeferredAttribute' object has no attribute 'objects'?
After a few days of searching, I still am unable to get over this hurdle. I'm just trying to print a list of descriptions from Sellers as a view. Here's what I'm working with... models.py: from django.db import models class Sellers(models.Model): index = models.BigIntegerField(blank=True, null=False) seller = models.TextField(db_column='SELLER', blank=False, null=False, primary_key=True) block = models.TextField(db_column='BLOCK', blank=False, null=False) street = models.TextField(db_column='STREET', blank=False, null=False) space = models.TextField(db_column='SPACE', blank=False, null=False) description = models.TextField(db_column='DESCRIPTION', blank=True, null=True) document_with_idx = models.TextField(blank=False, null=False) document_with_weights = models.TextField(blank=False, null=False) class Meta: managed = False db_table = 'Sellers' def __str__(self): return self.index ''' views.py: from django.http import HttpResponse from search.models import Sellers def search(request): output = Sellers.description.objects.all() return HttpResponse(output) ''' Any direction would be appreciated, I feel like I've read every related post related to this. Figured it was about time to post a question with my exact setup. Thanks! -
TypeError in Django Application
I am making a Django application. It's a wikipedia page that will allow you to create a new page if you click . The path is in urlpatterns is: path("create", views.create, name="create") The function in views.py is: def create(request): if request.method == 'POST': form = Post(request.POST) if form.is_valid(): title = form.cleaned_data["title"] textarea = form.cleaned_data["textarea"] entries = util.list_entries() if title in entries: return render(request, "encyclopedia/error.html", {"form": Search(), "message": "Page already exist"}) else: util.save_entry(title,textarea) page = util.get_entry(title) page_converted = markdowner.convert(page) context = { 'form': Search(), 'page': page_converted, 'title': title } return render(request, "encyclopedia/entry.html", context) else: return render(request, "encyclopedia/create.html", {"form": Search(), "post": Post()}) The error message I am getting is: TypeError: decoding to str: need a bytes-like object, NoneType found -
Bad Gateway when configuring nginx with. Django app container and Gunicorn
I'm using docker-compose to deploy a Django app on a VM with Nginx installed on the VM as a web server. but I'm getting " 502 Bad gateway" I believe it's a network issue I think Nginx can't access the docker container! however, when I use the same configuration in an Nginx container it worked perfectly with the Django app but I need to use the installed one not the one with docker. This is my docker-compose file: version: "3.2" services: web: image: ngrorra/newsapp:1.0.2 restart: always ports: - "8000:8000" volumes: - type: volume source: django-static target: /code/static - type: volume source: django-media target: /code/media environment: - "DEBUG_MODE=False" - "DB_HOST=…” - "DB_PORT=5432" - "DB_NAME=db_1” - "DB_USERNAME=username1111" volumes: django-static: django-media: And this is my nginx.conf file: upstream web_app { server web:8000; } server { listen 80; location /static/ { autoindex on; alias /code/static/; } location /media/ { autoindex on; alias /code/media/; } location / { proxy_pass http://web_app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } #For favicon location /favicon.ico { alias /code/assets/favicon.ico; } # Error pages error_page 404 /404.html; location = /404.html { root /code/templates/; } } Does anyone know what is the issue? Thank you! -
When http doesn't return answer I get UnboundLocalError
I have a website and I was trying to add a feature so that when you look for a movie title that doesn't exist, you get a message that says "Not results found". However, when I try the feature that I added with the else statement, I get this error: "UnboundLocalError at / local variable 'movie_data' referenced before assignment". It only happens when I search for something that doesn't exist. Why is it happening? This is my view: def index(request): movies = [] if request.method == 'POST': film_url = 'https://ghibliapi.herokuapp.com/films/' search_params = { 'films' : 'title', 'films' : 'description', 'films' : 'director', 'films' : 'release_date', 'q' : request.POST['search'] } r = requests.get(film_url, params=search_params) results = r.json() for result in results: movie_data = { 'Title' : result['title'], 'Release_date': result['release_date'], 'Director' : result['director'], 'Producer' : result['producer'], 'Description' : result['description'] } movies.append(movie_data) else: message = 'Not results found' context = { 'movies' : movies } return render(request,'core/index.html', context) -
Problem with CheckboxSelectMultiple from a CharField ModelForm in Django
I'm having trouble getting my form to save in Dajngo due to the following error on validation: <ul class="errorlist"><li>pt_medical_condition<ul class="errorlist"><li>Select a valid choice. [&#x27;anx&#x27;, &#x27;Bip&#x27;] is not one of the available choices. >pt_surgical_history<ul class="errorlist"><li>Select a valid choice. [&#x27;bre&#x27;, &#x27;pca&#x27;] is not one of the available choices. I've got this model: class pt_data(models.Model): condition_choices = [('ane', 'Anemia'), ('anx', 'Anxiety'), ('art', 'Arthritis'), ('ast', 'Asthma'), ('Bip', 'Bipolar'), ('ca', 'Cancer'), ('clo', 'Clotting disorder'), ('chf', 'CHF'), ('mdd', 'Depression'), ('cop', 'COPD'), ('ger', 'GERD'), ('gla', 'Glaucome'), ('hiv', 'HIV/AIDS'), ('ibs', 'IBS/Crohn\'s'), ('hld', 'High cholesterol'), ('ckd', 'Kidney disease'), ('ner', 'Nerve/Muscle disease'), ('ocd', 'OCD'), ('ost', 'Osteoporosis'), ('pai', 'Pain disorder'), ('pts', 'PTSD'), ('sch', 'Schizophrenia'), ('sei', 'Seizures'), ('sca', 'Sickle cell anemia'), ('su', 'Substance use disorder'), ('thy', 'Thyroid disease')] surgery_choices = [('app', 'Appendix removal'), ('bra', 'Brain surgery'), ('bre', 'Breast surgery'), ('cabg', 'CABG'), ('pca', 'Cardiac stent'), ('cho', 'Gallbladder removal'), ('col', 'Bowel surgery'), ('csec', 'C-section'), ('fra', 'Bone fracture repair'), ('her', 'Hernia repair'), ('hys', 'Uterus removal'), ('joi', 'Joint replacement'), ('lun', 'Lung surgery'), ('spi', 'Spine/back surgery'), ('thy', 'Thyroid surgery'), ('ton', 'Tonsil removal'), ('strf', 'Tubal ligation'), ('strm', 'Vasectomy'), ('wei', 'Weight reduction surgery')] pt_medical_condition = models.CharField(max_length=100, blank=True, null=True, choices=condition_choices) pt_surgical_history = models.CharField(max_length=100, blank=True, null=True, choices=surgery_choices) And this form: class ptForm(forms.ModelForm): class Meta: model = pt_data fields = ('__all__') widgets …