Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Django to PostgreSQL database (GeoDjango)
I am having issues connecting to my Postgresql database with my Django website. My database is set up at Port 5434 as there is already an existing database in the default 5432 port. This is the error I am getting Traceback (most recent call last): File "c:\users\anouphong\appdata\local\programs\python\python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\anouphong\appdata\local\programs\python\python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run self.check_migrations() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\core\management\base.py", line 505, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\loader.py", line 223, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 270, in cursor return self._cursor() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 246, in _cursor self.ensure_connection() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 230, in ensure_connection self.connect() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 230, in ensure_connection self.connect() File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\utils\asyncio.py", line 25, in inner return func(*args, **kwargs) File "C:\Users\Anouphong\.virtualenvs\project_homecook-l563S6IX\lib\site-packages\django\db\backends\base\base.py", line 211, in connect self.connection … -
Angular.js @angular/core bug
Welcome everyone... how can i fix this im working on it 2 days but nothing change. Can you help me ?See my all codes in app.module.ts That's my nodejs screen import { AngularFireModule} from '@angular/fire/compat'; //it should be '@angular/fire' import { AngularFireDatabaseModule } from '@angular/fire/compat/database'; //it should be '@angular/fire/database' imports: [ AngularFireModule.initializeApp(environment.firebaseConfig), AngularFireDatabaseModule ]; Thank you, -
DRF: validate_empty_values() is called when not empty
I created a subclass of ChoiceField in order to add custom code to supply the default value. At this point, I've copied the validate_empty_values() method over to my new class without modifying it at all - I just want to understand how it works. Here's that method (copied straight from the Field class in /rest_framework/fields.py): def validate_empty_values(self, data): """ Validate empty values, and either: * Raise `ValidationError`, indicating invalid data. * Raise `SkipField`, indicating that the field should be ignored. * Return (True, data), indicating an empty value that should be returned without any further validation being applied. * Return (False, data), indicating a non-empty value, that should have validation applied as normal. """ if self.read_only: return (True, self.get_default()) if data is empty: if getattr(self.root, 'partial', False): raise SkipField() if self.required: self.fail('required') return (True, self.get_default()) if data is None: if not self.allow_null: self.fail('null') # Nullable `source='*'` fields should not be skipped when its named # field is given a null value. This is because `source='*'` means # the field is passed the entire object, which is not null. elif self.source == '*': return (False, None) return (True, None) return (False, data) I have done a PATCH (we use PATCH for … -
Django lists of objects in a template max out
Not an expert on django and I have a problem that I have tried to find documentation about. Hopefully someone can help me out. Sometimes my templates do not return the intended page html, but instead returns a text based html list of the objects .I suspect this is related to number of rows in the queryset. Where can I find the documentation about this? Is it a django setting or the CSS class for the list that determines this? -
How to set on delete and on update cascade in django?
Look at these modules: class Customer2(models.Model): Customer_Name=models.CharField(max_length=30) Customer_Address=models.CharField(max_length=100) Customer_Phone=models.IntegerField() Customer_Email=models.EmailField(max_length=50) class Meta: db_table="Customer_Table" class Product(models.Model): Product_Name=models.CharField(max_length=100) Quantity=models.FloatField(max_length=100) Comming_Date=models.DateField(max_length=15) Expire_Date=models.DateField(max_length=15) Comming_Price=models.FloatField(max_length=50) Picture=models.ImageField(upload_to='Images',blank=True, null=True) class Sale(models.Model): Customer=models.ForeignKey(Customer2, default=1, on_delete=models.CASCADE) Product=models.ForeignKey(Product, default=1, on_delete=models.CASCADE) Quantity=models.FloatField() Price=models.FloatField() Date=models.DateTimeField() Customer_Name1=models.CharField(max_length=20,default=0) Product_Name1=models.CharField(max_length=20,default=0) class Meta: db_table="Sale_Table" In the above modules,when I am trying to to delete (customer) from customer it gives me(Do you really want to execute "DELETE FROM customer_table WHERE customer_table.id = 2"?)message, while I already used on delete cascade in customer table,What should I do? I want to set on update and on delete cascade in customer table. -
unable to send post request using HTMX + Django
I'm trying to create a CRUD page using django + HTMX and unable to send POST request. hx-post sends a GET request instead of POST request. my Role Models is as follows: class Role(models.Model): name = models.CharField(max_length=200) I'm creating the form using Cripsy Forms as follows class RoleForm(forms.ModelForm): class Meta: model = Role fields = ('name', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['name'].label = "Role" self.helper.add_input(Submit('add_new_Role', 'Add', css_class='role_button')) self.helper.layout = Layout( Row( Column('name'), ) ) I'm using the form in my template like this : {% extends 'main.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="card col-md-6 ml-auto mr-auto"> <div class="card-body"> {% crispy role_form %} </div> </div> </div> <div id="role_list"> {% include 'role_list.html' %} </div> {% endblock %} {% block javascript %} <script type="text/javascript"> $(document).ready(function(){ $("form").removeAttr("method"); $('.role_button').attr("hx-post", '{% url "role_add" %}'); $('.role_button').attr('hx-target', '#role_list'); }); </script> {% endblock %} The CDN link is added in the main.html file. My understanding is that clicking the ADD button should trigger a POST request. However GET request is initiated, which makes me feel like the HTMX part did not work at all -
Get object URL from boto3, AWS S3, Django
I have a view in Django like this : f=request.FILES['image'] filename=str(f).split('.')[0] cloudFilename = 'blog/' + filename s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY) bucket = s3.Bucket('django-pnp-talk') bucket.put_object(Key=cloudFilename, Body=f) how can I get the URL from the recently object that I put into the bucket? -
Even though its a class why is AttributeError: 'function' object has no attribute 'as_view'
even though its a calss based func why is this attribute error popping up when i use login_required error Message path('active/<int:pk>', UpdateActiveStatus.as_view(), name="activeStatus"), AttributeError: 'function' object has no attribute 'as_view' views.py @login_required(login_url='/admin/') class UpdateActiveStatus(UpdateView): model = FutsalTimeline form_class = UpdateActiveStatus template_name = 'timeline.html' success_url = reverse_lazy('timeline') -
Django, How to filter context output from HTML template?
I have a ListView that sends context as news in the HTML template. The below code is supposed to slice the context array from the 4th element to until its end {% for post in news[4:0] %} ............ {% endfor %} But following error occurs Could not parse the remainder: '[4:]' from 'news[4:]' -
Annotation of Similar Article Tags In Django Admin
I want to display similar tags count in the Django admin Tag section like this: name | posts ------------------------------- business | 3 Currently in my Tag table I have something this. This different posts that have similar tags to them. name | post_id ------------------------------- business | 1 business | 2 business | 3 My models class Posts(models.Model): title = models.CharField(max_length=500, verbose_name='Post Title') class Tags(models.Model): name = models.CharField(max_length=500) date_created = models.DateField(auto_now_add=True, verbose_name='Date Created') last_modified = models.DateField(auto_now=True, verbose_name='Last Modified') post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts') I have this in the admin.py class TagAdmin(admin.ModelAdmin): list_display = ('name', 'post_count', 'date_created', 'last_modified') search_fields = ['name'] ordering = ['id'] readonly_fields=('date_created', 'last_modified') def post_count(self, obj): return obj.post_count def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(post_count=Sum("post")) return queryset admin.site.register(Tags, TagAdmin) This is how it looks in the admin panel name | post_count ------------------------------- business | 3 business | 3 business | 3 How do I achieve only displaying one instance of a tag name with all the posts that have that tag instead of the repetition above and instead the desired outcome below? name | posts ------------------------------- business | 3 -
Drf: authenticating without the USERNAME_FIELD
` extended from: Drf how to: simple-jwt authenticating without the USERNAME_FIELD I was tryna figure out how to authenticate a user with a field that is not set as the USERNAME_FIELD and faced some issues, it lets me input in the correct data fields, but it never authenticates I'm using this snippet from the previous questions answer: class MyTokenStudentSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['student_id'] = serializers.CharField(required=False) # self.fields['password'] = serializers.CharField(write_only=True, required=True) self.fields['password'] = PasswordField(trim_whitespace=False) username_field = 'student_id' auth_fields = ['student_id'] produces { "detail": "No active account found with the given credentials" } any modifications would be greatly appreciated. -
Annotate on Generic Relation
apologies, I'm fairly sure there's a way to do this with Q filters/F expressions but I can't quite get it right. I have a Generic Versioning Model, and several versionable models: class Version(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to=VERSIONED_OBJECTS_LIMIT ) object_id = models.PositiveIntegerField() source = GenericForeignKey("content_type", "object_id") object_uri = models.TextField(max_length=1024, null=True) version_number = models.IntegerField(default=1) is_latest = models.BooleanField(default=1) class Dataset(models.Model): versions = GenericRelation(Version) class DataModel(models.Model): versions = GenericRelation(version) I figured this approach would be wise as we version quite a few models. However, I'm struggling to create the annotation/query that would retrieve for me all model instances annotated by the latest version. For a given instance it is of course trivial, but I can't figure it out for the model writ large. latest_datasets = Dataset.objects.annotate(uri = version.uri).filter(versions__islatest=True) Obviously returns all datasets, since by design each dataset has at least one "is_latest" Version. Apologies -- maybe this is just bad db design, but I do think making "Version" a Generic abstraction made sense for our use case. So, if theres a way to get all instances of Model_x with the appended uri WHERE version.is_latest = True, I would love to know how. Thanks in advance, sorry for my ignorance. -
How to get user with POST Ajax call in django?
I'm trying to realize comments for products on site with AJAX, but faced the problem that I can not receive an author of comment in this case of code: new_comment.author = request.user I got this error in this case: "Exception Value: Object of type User is not JSON serializable" But without user I got parameters from back-end and have result 200, like this author "" content "dasda" created_at "2021-12-31T07:34:12.766Z" product 4 So the question how to be "author = request.user" can be serialized? Or it is can be realised only with Django Rest Framework? (I don't have experience in DRF, but know some things in theory) Can somebody advice please? def ajax_receiver(request): product = Product.objects.get(id=4) is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if request.method == 'POST' and is_ajax and request.user.is_authenticated: form = UserCommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) #new_comment.author = request.user new_comment.product = product new_comment.save() comment_info = { "author": new_comment.author, "content": new_comment.content, "created_at": new_comment.created_at, "product": product.id, } return JsonResponse({"comment_info": comment_info}, status=200) else: return JsonResponse({"success": False}, status=400) -
Django Python - .get function returns DoesNotExist matching query does not exist
I've been really stumped on the following issue.. I am trying to retrieve an order number after taking a stripe payment. Stripe returns a payment is completed and everything is working, on the success page I call the function below to retrieve the order number from the session table. The wierd thing is, even though it gives me a DoesNotExist error, it does find the right order number and returns the order number and all data is actually served. Function def get_order_number(session_id): order = session_order_table.objects.get(session_id=session_id) order_number = order.order_number return order_number success page function def success_page(request): summary_orders = None session_id = request.session["USER_SESSION_ID"] order_number = get_order_number(session_id) print('###############SESSION_ID######################') print(session_id) print(order_number) online_order = My_Cart_History_Model.objects.filter(order_number=order_number) .... error 1820bd97c5"\n },\n "type": "payment_intent.succeeded"\n}' 1x 777 test (Quality:VVS, Size: L, Color: yellow-gold) C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py:1416: RuntimeWarning: DateTimeField My_Cart_History_Model.transaction_date received a naive datetime (2021-12-31 07:21:41) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" Internal Server Error: /cart/my_webhook_view/ Traceback (most recent call last): File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\pwl-server\django\t7\cart\views.py", line 533, in my_webhook_view fulfil_order(request=request ,payload=payload,session=session) File "D:\pwl-server\django\t7\cart\views.py", line 594, in fulfil_order return … -
changing primary key from username to uuid on POSTGREQL gives: django.db.utils.ProgrammingError: column "username" is in a primary key
I have a postgresql database and I am making a migration to switch my pk from username to uuid. I already made a data migration file where I add a uuid to every row in my model it worked fine on sqlite but when I was testing it on postgresql I got an error. The error was "django.db.utils.ProgrammingError: column "username" is in a primary key" I am not sure where to begin to debug this thing. Here is the model, data migration, migration, and stack trace of the error: # models.py class UserInformation(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) username = models.CharField(max_length=100, unique=True, blank=True, null=True) # data migration 42 import uuid from django.db import migrations def set_uuid_for_all_user_information(apps, schema_editor): UserInformation = apps.get_model('accounts', 'UserInformation') for userInformation_user in UserInformation.objects.all(): userInformation_user.uuid = uuid.uuid4().hex userInformation_user.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0041_auto_20211227_2113'), ] operations = [ migrations.RunPython(set_uuid_for_all_user_information), ] # migration 43 (this is where the postgresqsl error occurs) trying to change pk from username to uuid from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('accounts', '0042_auto_20211229_2319'), ] operations = [ migrations.AlterField( model_name='userinformation', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='auth.user'), ), migrations.AlterField( model_name='userinformation', name='username', field=models.CharField(blank=True, … -
How to apply multiple field options to one field in Django
I'm using Django, is there a way to apply foreign key and ChartField to one field at the same time? Sometimes I want to allow the user to enter a value that is not in the foreign key. I've googled for a long time and found various ways, but I can't find a solution. Please help. [models.py] class Supporting(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=False, null=True) -
How to insert field in table from database using python script and print it in html page or print python result in html directly using pycharm django
so i'm new to django and python, i'm having a mini project to make a decision support system. so i already build a website, already connect it to the database and have the python code, now i'm having difficulties to push the result/target in python to existing field in table dataresponden from database and print it to html. the flow is like this: an user input a data (nama, umur, gejala, komorbid) and stored it in table dataresponden(nama, umur, gejala, komorbid, hasil_rekomendasi) in database. user didn't input hasil_rekomendasi because hasil_rekomendasi is the result from the decision support system. in python, i read query dataresponden as dataset, i set hasil_rekomendasi as a target and calculate the remaining column. so i get the result i want named hasil_prediksi, now the problem is i want to push hasil_prediksi to column hasil_rekomendasi in table dataresponden because when user input the data they don't input hasil_rekomendasi. after that i want print it in my html page. i tried this Execute a python script on button click but didn't work, i tried to use update table but it didn't work too, this is the code in hasil.html : <div class="modal-body text-center pb-5" id="hasilrekomendasi"> <div class="container"> <div … -
Github actions deploy django application to elastic beanstalk
I'm simply trying to deploy my django application to elastic beanstalk using github actions but keep getting these error: Warning: Environment update finished, but health is Red and health status is Degraded. Giving it 30 seconds to recover... Warning: Environment still has health: Red and health status Degraded. Waiting 19 more seconds before failing... Warning: Environment still has health: Red and health status Degraded. Waiting 8 more seconds before failing... Error: Deployment failed: Error: Environment still has health Red 30 seconds after update finished! This it the code I'm using below: name: AWS Deploy on: push: branches: - test-main-branch jobs: build: runs-on: ubuntu-latest steps: - name: Checkout source code uses: actions/checkout@v2 - name: Generate deployment package run: zip -r deploy.zip . -x '*.git*' - name: Get timestamp uses: gerred/actions/current-time@master id: current-time - name: Run string replace uses: frabert/replace-string-action@master id: format-time with: pattern: '[:\.]+' string: "${{ steps.current-time.outputs.time }}" replace-with: "-" flags: "g" - name: Deploy to EB uses: einaregilsson/beanstalk-deploy@v20 with: aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }} aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} application_name: project-pit environment_name: project-pit-cloud version_label: 12345 region: ap-southeast-2 deployment_package: deploy.zip - name: Deployed! run: echo App deployed The application is showing up in my s3 bucket but I still get a Degraded health … -
Get name From extra_field django allauth and save to name field on Users Model
I have Users Model like this from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db.models.signals import pre_save from django.dispatch import receiver # Create your models here. from users.manager import UserManager class Users(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # Setting field USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] # Setting Object Manager objects = UserManager() class Meta: abstract = False I need to get {"name": "Feri Lukmansyah",} from social_account model (from django allauth) and save to name field from Users Model, I already use signal like this from django.dispatch import receiver from allauth.socialaccount.signals import social_account_added, social_account_updated from .models import Users @receiver(social_account_added) @receiver(social_account_updated) def add_name_from_google(request, sociallogin, **kwargs): pass but I don't know how to use signal on django allauth, everybody can help me fix this problem? or have any example to use django allauth signal? -
How to Implement Django Loggers/Logging in the code?
As i am a newbie. I'm working on Django Rest Framework using ModelViewset. Can anyone help me out in explaining or understanding, how to implement the loggers/logging? Even i'm using the Django OAuth2 toolkit for authentication, so how can log a username & password? -
action.php page not found and failure to send data to MariaDB table
This is kind of a double question since the first issue correlates to the latter. My first issue is that the action attribute on my html form directing towards a file called action.php results in a 404 error during form submission and I am not sure how I would create a path in urls.py that would lead to the code in action.php being executed. My second issue is that once the first issue is fixed, action.php is supposed to send the data from the answers submitted in my html form into a MariaDB database I have configured. However, some of the code I have written is appearing on my webpage which leads me to believe that data wont be sent to my database table. Any help would be greatly appreciated. DATA TREE urls.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): context = {"name": "DUDE"} return render(request, "hello_page.php", context) hello_page.php {% extends "base.php" %} {% block content %} <?php //include('config.php'); $host = "localhost"; $username = "USER"; $password = "PASS"; $database = "donations"; $dbconnect=mysqli_connect($host, $username, $password, $database); if ($dbconnect->connect_error) { die("Database connection failed: " . $dbconnect->connect_error); } ?> <html> <h1> WHATS UP {{name}}!!!!!</h1><br> <form action="action.php" method = "POST"> <label … -
Image Display in Django
ERRORS: <class 'blog.admin.CategoryAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'image_tag', which is n ot a callable, an attribute of 'CategoryAdmin', or an attribute or method on 'blog.Category'. System check identified 1 issue (0 silenced). -
django redirects to non existing url
Two days ago I created a django project and it worked all right. But, now when I am working on another django project still when I run server it's redirecting me to the older project. I am using different virtual environment for both of them. Even after deleting the old one the issue is not resolved. Thanks in advance. -
Creating an autocomplete search form (probably w/ jQuery) using a comprehensive (huge) movie title list (Django project) from IMDBPy
I am in the early stages of retrieving IMDB data via the Python package IMDBPy (their site) (proj github). I have been referring to this nice IMDBPy implementation for help with aspects of what I'm doing here. Several of the queries that I'm using generate datasets that come in "nested dictionary" form, e.g. 'movie_1':{'title':'One Flew Over the Cuckoo's Nest', 'director': 'Milos Forman'...}. My early version of the title retrieval takes this form in VIEWS.PY: def index(request): imdb = IMDb() test_movies = {} for i in range(1100000, 1100015): test_movies[f'movie_{i}'] = imdb.get_movie(f'{i}') context = { 'test_movies':test_movies, } return render(request, 'index.html', context) And this in my INDEX.HTML template: <div id="search-part1"> <ul> {% for k1,v1 in test_movies.items %} {% for k2,v2 in v1.items %} {% if 'title' in k2 %} <li>{{v2}}</li> {% endif %} {% endfor %} {% endfor %} </ul> <input type="text" name="search" id="search" class="form-control" placeholder="Search for Movies"> </div> Right now, the HTML is just to show that I *can generate a list of these titles. My actual implementation of the dropdown from the search bar (via jQuery's Autocomplete), is a little further down the road at this point. Here is an example that they provide of the Autocomplete in action, in the … -
django how to set form ModelChoiceField drop down to required if specific value is selected from the previous drop down
I have the following form: class RegisterForm(UserCreationForm): company_role = forms.ModelChoiceField(queryset=CompanyRole.objects, empty_label='Select Company Role') office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office', required=False) location = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Select Location", required=False) class Meta: model = User fields = ["first_name", "last_name", "username", "email", "password1", "password2", "company_role", "location", "office"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['office'].queryset = Office.objects.none() Is it possible through this form to set office ModelChoiceField drop down to be required if the first item (id 1) is selected in company_role ModelChoiceField drop down and also if second item (id 2) is selected in company_role ModelChoiceField drop down then set location ModelChoiceField drop down to be required? If so would greatly apprecaite some help on how to do so. Thanks in advance