Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Strategy to make django models with lots of memberfunctions more manageable?
I have a huge model because of its many member functions. I would like to organize the functions into separate classes according to their purpose, so everything is a bit more organized. Using OneToOneField is not a good option for me, because my app heavily relies on query caching (with cacheops). And I noticed that getting the latest version of a data object (from db) may be attached to a an outdated OneToOneField (from cache). Also, the number of data members is not a problem, only the number of member functions. So I would prefer to use just one data model. For example, I could do it this way: # models.py class MyModel(models.Model): # members # separate member functions class CustomModelFunctions: @staticmethod def some_function(my_model_instance): # logic # call the function on the my_model obj # instead of calling my_model.some_function() CustomModelFunctions.some_function(my_model) This works, but the problem is that these functions can not be used in django templates, since the my_model argument can not be passed. For example, I don't see how I could replace the following template code: {% if my_model.some_function %} Does anyone know a workaround for this? Or a different approach to organize models with a lot of member … -
How to make Django custom user restrict middleware?
urls.py path('panel/', include('panel.urls')), path('', include('base.urls')), non superadmin user restrict to access panel.urls superadmin user allowed panel.urls middllware.py # panel/middleware.py from django.shortcuts import redirect from django.urls import reverse class AdminRestrictMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path.startswith('/panel/'): if request.user.is_authenticated: if not request.user.is_superuser: # If the user is not an admin, redirect them to a restricted page return redirect(reverse('restricted_access')) else: # If the user is not logged in, redirect them to the login page return redirect(reverse('login')) response = self.get_response(request) return response -
Django data getting saved in wrong model Why its saving the Model B,C data in model A
I have 3 django models CustomerDetail CarrierForm InfluencerModel When i am trying to save data in CarrierForm or InfluencerModel through different different page's forms its getting saved in model CustomerDetail Why its happening tell me what i am doing wrong? Here is Model class CustomerDetail(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) message = models.TextField(null=False, blank=False) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class CarrierForm(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) upload_resume = models.FileField(null=False, blank=False) message = models.TextField(null=True, blank=True) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class InfluencerModel(models.Model): full_name = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) contact_number = models.CharField(max_length=10, null=False, blank=False) instagram_id = models.CharField(max_length=50, null=False, blank=False) message = models.TextField(null=True, blank=True) visited_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email Here is Views class HomeView(CreateView): success_url = reverse_lazy('home') model = CustomerDetail template_name = 'home/home.html' fields = ['full_name', 'email', 'contact_number', 'message'] def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) context['files'] = HomeVideoAndImage.objects.all() context['galleryImages'] = HomeGallery.objects.all() context['reviewImages'] = Review.objects.all() return context class CarrierFormView(CreateView): model = CarrierForm template_name = 'home/carrier.html' fields = ['full_name', 'email', 'contact_number', 'upload_resume', 'message'] def get_context_data(self, *args, **kwargs): context = super(CarrierFormView, self).get_context_data(*args, **kwargs) … -
django two factor OTP in DRF
I want to protect one route in a project on DRF, but there are features, an example of implementation that I have not found on the Internet. The structure of logic is like this bellow Implement Two-Factor Authentication (2FA): Integrate a third-party service like Google Authenticator for generating verification codes. When a user tries to access the sensitive route, prompt them to enter a verification code along with their credentials. Verify the entered code with the code generated by the Google Authenticator or similar service. Email Verification: Maintain a list of email addresses that are allowed to access the sensitive route. Compare the email address of the authenticated user (request.user.email) with the list of allowed email addresses. If the user's email is in the allowed list, send a verification code to their email address. Prompt the user to enter the verification code received via email. Verify the entered code against the code sent to the user's email. Granting Access: If the user successfully completes both steps of authentication (2FA and email verification), grant them access to the sensitive route. Otherwise, deny access to the route. If anyone has encountered a similar implementation, please give me some direction -
connection failed: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
i am getting an error connecting to sql cloud during deployment to google cloud, in my sql cloud, IP public is 34.66.xx.xxx enter image description here but when I run code ./cloud-sql-proxy <connection_name> then feedback: 2024/03/05 22:53:02 Authorizing with Application Default Credentials 2024/03/05 22:53:03 [django-ecommerce-416314:us-central1:django-ecommerce-instance] Listening on 127.0.0.1:5432 2024/03/05 22:53:03 The proxy has started successfully and is ready for new connections! in my setting code django setting, I config database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '34.66.xx.xxx', 'PORT': '5432', } } more detail: I can run server on UI server but when LOGIN, REGISTER,... related with DB it not active. What need I do now? Thanks! I tried change config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '5432', } } results returned: enter image description here but when I run with config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'shopeedb', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '34.66.xx.xxx', 'PORT': '5432', } } results returned: 502 bad gate way Nginx -
Mypy with Django: type[MyModel] has no attribute "objects" [attr-defined]
After coding my Django model and adding a method which uses the "objects" manager, Mypy continues to show the error (command: "mypy ."): models.py:168: error: "type[MyModel]" has no attribute "objects" [attr-defined] How to solve that? -
Backend vs Frontend approach for upload of large files to remote storage
I am creating a software involving content delivery. It involves upload of large video files(100GB+). I understand that in general for file upload you can use the input element of html and upload it to the backend and from there you upload it to your storage. But this involves 2 uploads for 1 file and involves loading your large file into in-memory database in your backend. Im wondering if one could save some bandwidth and time, space and computation by somehow directly uploading from the frontend. What is the industry standard for dealing such a scenario? I've seen ways to upload large files from backend using multipart uploads using AWS sdk, but so far, I couldn't find a way to directly upload using HTML + JavaScript from the frontend itself(without loading the file into the in-memory database). I am using Django for backend, Angular for frontend and AWS s3 for storage. -
How to resolve a "DuplicateColumn" error when running Django migrations?
I'm encountering an issue while running migrations in my Django project. Here's the error message I'm receiving: psycopg2.errors.DuplicateColumn: column "order_address" of relation "orders_order" already exists This error seems to be related to the migrations process. I have checked my migration files and ensured that I'm not explicitly adding the "order_address" column multiple times. However, the error persists. What could be causing this error, and how can I resolve it? -
Not printing required data from json available data
[This is the source code. Here I iterate through a bunch of json entries and try to print only a few.] (https://i.stack.imgur.com/KUlfj.png) the last few empty columns are where I tried to print some specific data. It isn't printing it at all. The entries are supposed to be printed on a html page. I had tried to iterate through 'output' which had 2 json entries. I wish to print only a few specific values from each json entry but when i specified and ran the django webapp, it didn't print anything. -
csrf token is showing as text in the browser
enter image description herei am very new to django. i am trying to create a login form in django but when i write the csrf_token line after the tag it is showing in the browser view. everything is very confusing for me i don't know what to do. the tutorial that i watch on youtube only pass the csrf_token but don't say anything much. {% csrf_token %} Email Password Sign In Change Password this is a very simple form that i styled using tailwindcss and the csrf token is being shown. also my app has other errors. it does not run on the development server -
Error creating a closure table in Django: 'ForeignKey' object has no attribute 'column'
I have a Jobs model and need a closure table job_hierarchies schema looks like below Table job_hierarchies { account_id int [not null] ancestor int [not null, ref: > jobs.id] descendant int [not null, ref: > jobs.id] level int [not null] } I tried creating model & migration for JobHierarchy as below Model # api/models/job_hierarchy.py from django.db import models from .base import BaseModel from api.models import Job class JobHierarchy(BaseModel): account_id = models.IntegerField(null=False) ancestor = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='ancestor_jobs', db_column='ancestor_id') descendant = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='descendant_jobs', db_column='descendant_id') level = models.IntegerField(null=False) class Meta: db_table = 'job_hierarchies' Migration looks like below # Generated by Django 5.0.2 on 2024-03-08 04:28 from django.db import migrations, models def add_foreign_keys(apps, schema_editor): JobHierarchy = apps.get_model('api', 'JobHierarchy') Job = apps.get_model('api', 'Job') schema_editor.add_field( JobHierarchy, models.ForeignKey(Job, on_delete=models.CASCADE, related_name='ancestor_jobs', db_column='ancestor_id'), ) schema_editor.add_field( JobHierarchy, models.ForeignKey(Job, on_delete=models.CASCADE, related_name='descendant_jobs', db_column='descendant_id'), ) class Migration(migrations.Migration): dependencies = [ ('api', '0002_create_jobs'), ] operations = [ migrations.CreateModel( name='JobHierarchy', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('account_id', models.IntegerField()), ('level', models.IntegerField()), ], options={ 'db_table': 'job_hierarchies', }, ), migrations.RunPython(add_foreign_keys), ] When I run make migrations, I get below error File "/app/api/migrations/0009_create_job_hierarchies.py", line 8, in add_foreign_keys schema_editor.add_field( File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/schema.py", line 730, in add_field "name": self._fk_constraint_name(model, field, constraint_suffix), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/schema.py", line 1708, in _fk_constraint_name [field.column], ^^^^^^^^^^^^ AttributeError: … -
stripe transfer method in django
i am working on project where i want to transfer amount to multiple stripe customers i have used the stripe transfer method but i am getting the following error Error: Request req_FlLAHrjOxkd4IO: You have insufficient available funds in your Stripe account. Try adding funds directly to your available balance by creating Charges using the 4000000000000077 test card. See: https://stripe.com/docs/testing#available-balance here is my code charge = stripe.Charge.create( amount=5000, currency="usd", source='tok_visa', description="Adding funds to test account" ) charge_id = charge.id # Assuming you have defined 'total_charges', 'user.id', 'seller_amount', and 'referral_amount' earlier in your code session = stripe.PaymentIntent.create( amount=total_charges, currency="usd", transfer_group=f"ORDER10_{user.id}", ) stripe.Transfer.create( amount=seller_amount, currency='usd', destination='acct_1OrzGLI3hFSHp0X5', transfer_group=f"ORDER10_{user.id}", ) stripe.Transfer.create( amount=referral_amount, currency='usd', destination="acct_1OrzPRI5g3KKKWKv", transfer_group=f"ORDER10_{user.id}", ) -
Django not sending rendered array to Angular
I'm trying to build an API with Django that recieves an image, applies a filter and returns the image with the filter to the frontEnd, that it's made with Angular. But when I call the API my model does recieve the image but doesn't apply the filter and doesn't return the modified image. And it whe using the method POST doesn't return anything, not even an error This is my models.py: def apply_filter(noisy_image, kernel): smoothed_image = np.zeros_like(noisy_image) for channel in range(noisy_image.shape[2]): for row in range(noisy_image.shape[0] - kernel.shape[0] + 1): for col in range(noisy_image.shape[1] - kernel.shape[1] + 1): sub_matrix = noisy_image[row:row + kernel.shape[0], col:col + kernel.shape[1], channel] smoothed_image[row + 1, col + 1, channel] = np.sum(sub_matrix * kernel) fig, ax = plt.subplots() ax.imshow(smoothed_image.astype(np.uint8)) ax.axis('off') return fig def default_image(image_array): # Load image fig, ax = plt.subplots() ax.imshow(image_array.astype(np.uint8)) ax.axis('off') # Hide axes return fig def suavizado1(image_array): kernel_size = 12 kernel = np.ones((kernel_size, kernel_size)) / (kernel_size ** 2) noise = np.random.normal(0, 10, size=image_array.shape) noisy_image = image_array + image_array * noise return apply_filter(noisy_image, kernel) This is my views.py: def processImage(request): if request.method == 'POST': uploaded_file = request.FILES['image'] filter_name = request.POST.get('filter') image_path = default_storage.save('uploaded_images/' + uploaded_file.name, ContentFile(uploaded_file.read())) print(image_path) #Load image imagen = Image.open(image_path) image_array = np.array(imagen) … -
Django email html format not
`html = """\ <html> <head></head> <body> <p>Hi Team,<br><br> Reminder:<br> Please check if Domain listed below need to be renewed.<br><br> {0} </p> </body> </html> """ www = get_data_from_db() week_old = 14 d = [] for domain in www: days = compute_days(domain) if int(days) <= int(week_old): d.append("{0} is expiring in {1} days.<br>".format(domain, days)) print(d) html = ('\n'.join(d)) print(html) part2 = MIMEText(html, 'html') msg.attach(part2)` Hi, just started learning python/django not long ago. This project is to add a reminder/notification to the company by sending out email. I came across this problem where I am unable to correctly display the html with value. If I change my code at html = html.format('\n'.join(d)) It will display the html with 1 value where the actual result is 2 value. Missing the another one. If I use code above, it will only display 2 value but missing the html. What am i missing here? -
Null field returning required
I set a referral field on my django model to null but everytime I try to register without passing in a parameter it says that the field is required for registration. I've tried different approaches to try to solve it but still no fix. I want users to be able to register without using a referral code #models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, username, email, password, is_staff, is_superuser, address, **extra_fields): now = timezone.now() if not username: raise ValueError(('The given username must be set')) email = self.normalize_email(email) user = self.model(username=username, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, address=address, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): return self._create_user(username, email, password, False, False, True, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): user = self._create_user(username, email, password, True, True, **extra_fields) user.is_active = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=250, blank=True) last_name = models.CharField(max_length=250, blank=True) email = models.EmailField(('email address'), unique=True) username = models.CharField(max_length=50, unique=True, blank=False, default='username') profile_picture = models.ImageField(upload_to='Pictures', blank=True) created_at = models.DateField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) referral_code = models.CharField(max_length=10, unique=True, blank=True, null=True) referred_by = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) referred_users_count = models.IntegerField(default=0) #subscription_start_dates = … -
Django async nested model loading
I have models: class ObjectA(models.Model): alias = models.CharField(max_length=50) objectb = models.ForeignKey(ObjectB, on_delete=models.PROTECT) class Meta: db_table = "objecta" class ObjectB(models.Model): name = models.CharField(max_length=50) objectc = models.ForeignKey(ObjectC, on_delete=models.PROTECT) class Meta: db_table = "objectb" class ObjectC(models.Model): name = models.CharField(max_length=50) class Meta: db_table = "objectc" In my ViewSet function I want to get ObjectA and then get name from referenced ObjectC. In synchonious django I would do get_object_or_404(ObjectA, alias="My alias").objectb.objectc.name But this in async Django throws me an error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I found a solution which does not look very clean to me: from django.db.models.query import aprefetch_related_objects from django.shortcuts import get_object_or_404 get_objecta_model = sync_to_async(get_object_or_404, thread_sensitive=True) objecta = await get_objecta_model(ObjectA, name=alias) await aprefetch_related_objects([objecta], "objectb__objectc") objecta.objectb.objectc.name -
Pivot table with hierarchical indexes?
Using pandas 2.0.3. I know this may sound simple but i dont know how to make it work. I'm using pandas pivot table to rearrange a table to match a template. Here's the current code I'm using: x = pd.pivot_table(df, index=['locality', 'name', 'type', 'method'], columns='mineral', values='mineral_value', fill_value=0).reset_index() With this code I'm getting this data structure: However, I need to add a hierarchy with the columns mineral and method, so it looks something like this: I've been trying multiple ways but I just haven't been able to get it. I've tried to add x = pd.pivot_table(df, index=['locality', 'name', 'type', 'method'], columns=['mineral', 'method'], values='mineral_value', fill_value=0).reset_index() TypeError: keys must be str, int, float, bool or None, not tuple Any idea? thanks in advance -
Sending a custom error Through the API to appear in flutter
I have a functioning flutter front to register users that consumes a Django-rest-framework API. With 3 fields (Username,Email and Password). I'm trying to add a snack-bar that shows up when the user fills a field incorrectly according to my validations. this is what i tried : if (response.statusCode == 200) { // Request was successful print('Signup successful!'); // You can perform any other actions here, such as navigating to a new screen } else { // Request failed print('Failed to signup. Error: ${response.statusCode}'); final Map<String, dynamic> errors = jsonDecode(response.body); String? key = errors.keys.first; String value = errors[key][0]; print(value); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('$value'), backgroundColor: Colors.red, duration: const Duration(seconds: 2), ), ); } } catch (error) { // Handle any exceptions that occur during the API call print('Error while signing up: $error'); // You can display an error message to the user or perform other error handling actions } } For some reason when the password field or username field are Wrong i get a : Failed to signup. Error: 500 Error while signing up: FormatException: Unexpected character (at character 1). and when the email field is invalid i get the wrong error message (Enter a valid email address) . I'm still … -
How can I eliminate the segfaults that occur in working code only when debugging with ipdb?
I am using: Python: 3.11.0 Django: 4.2.8 djangorestframework 3.14.0 sqlite: 3.38.5 When I'm debugging and I use 'n' to go over a method, I sometimes get a segfault where there is no problem running the code normally. I can move my 'ipdb.set_trace()' to immediately after the call that caused the segfault, rerun the test and continue debugging but this is tedious. One cause I've tracked, is under the django reverse function. Here, the <URLResolver <module 'rest_framework.urls' from '/home/paul/wk/cliosoft/sosmgrweb/venv/lib/python3.11/site-packages/rest_framework/urls.py'> (rest_framework:rest_framework) 'api-auth/'> causes the segfault when its _populate method is invoked. I could start upgrading everything but this is a large application with many dependencies and I'd like to be confident that this problem will be eliminated if I go down that road. Does anyone know what the cause of this is and how I can resolve it? -
create choices dynamically in django
I'm trying to populate choices in django form dynamically, the choices cames from an external API. My model so far: from django.db import models class MyModel(models.Model): choice_field = models.CharField(max_length=100, choices=()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) api_url = 'http://api.com' response = requests.get(api_url) if response.status_code == 200: data = response.json() options = [(option['value'], option['label']) for option in data] self._meta.get_field('choice_field').choices = options however, it is not working, can someone help me? -
Why is my stopwatch adding fixed amount of time when I refresh?
I have a Vue.js Script is Adding time to my stopwatch once I refresh the page - Always adds an additional 6 hours. The script is simply a button that tracks time when clicked, and post the time to a django model once stopped. I am able to track time fine, but when I refresh the page, I come back to seeing 6 hours added to my stopwatch: Vue.js Script: var NavbarApp = { data() { return { seconds: {{ active_entry_seconds }}, trackingTime: false, showTrackingModal: false, timer: null, entryID: 0, startTime: '{{ start_time }}' } }, delimiters: ['[[', ']]'], methods: { startTimer() { fetch('/apps/api/start_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) => { return response.json() }) .then((result) => { this.startTime = new Date() this.trackingTime = true this.timer = setInterval(() => { this.seconds = (new Date() - this.startTime) / 1000 }, 1000) }) }, stopTimer() { fetch('/apps/api/stop_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' } }) .then((response) => { return response.json() }) .then((result) => { this.entryID = result.entryID this.showTrackingModal = true this.trackingTime = false window.clearTimeout(this.timer) }) }, discardTimer() { fetch('/apps/api/discard_timer/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token … -
How to Efficiently Create and Maintain SQL Indexes in Django with PostGIS?
I'm working on a Django project that utilizes PostGIS for spatial data. Currently, I'm considering creating a SQL index for the created_at field to improve query performance. The created_at field is configured with auto_now_add=True, meaning it automatically captures the timestamp when an object is created. However, I'm unsure about the best practices for creating and maintaining SQL indexes in Django with PostGIS. Here are my specific questions: What is the recommended approach for creating SQL indexes in Django with PostGIS? Does creating an index for the created_at field significantly improve querying performance in Django? What are the potential maintenance tasks associated with managing SQL indexes in Django with PostGIS? I would appreciate any insights, advice, or best practices from experienced Django developers or those familiar with working with PostGIS. Thank you! -
Django: Mocking an external api call in the save method of a model
I want to test a modelform using pytest in two modes: without the need to call the external API used in the save method by generating an error when the API is offline so I can test the validation I created Here's my code: trips/models.py class Place(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, related_name="places") day = models.ForeignKey( Day, on_delete=models.SET_NULL, null=True, related_name="places" ) name = models.CharField(max_length=100) url = models.URLField(null=True, blank=True) address = models.CharField(max_length=200) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) objects = models.Manager() na_objects = NotAssignedManager() def save(self, *args, **kwargs): old = type(self).objects.get(pk=self.pk) if self.pk else None # if address is not changed, don't update coordinates if old and old.address == self.address: return super().save(*args, **kwargs) g = geocoder.mapbox(self.address, access_token=settings.MAPBOX_ACCESS_TOKEN) self.latitude, self.longitude = g.latlng return super().save(*args, **kwargs) def __str__(self) -> str: return self.name trips/forms.py class PlaceForm(forms.ModelForm): class Meta: model = Place fields = ["name", "url", "address", "day"] formfield_callback = urlfields_assume_https widgets = { "name": forms.TextInput(attrs={"placeholder": "name"}), "url": forms.URLInput(attrs={"placeholder": "URL"}), "address": forms.TextInput(attrs={"placeholder": "address"}), "day": forms.Select(attrs={"class": "form-select"}), } labels = { "name": "Name", "url": "URL", "address": "Address", "day": "Day", } def __init__(self, *args, parent=False, **kwargs): super().__init__(*args, **kwargs) if parent: trip = parent else: trip = self.instance.trip self.fields["day"].choices = ( Day.objects.filter(trip=trip) .annotate( formatted_choice=Concat( "date", Value(" (Day … -
Cant get Django Date Widget to show in form
I am attempting to get a date field in a form to display as a date with date picker. For some reason, the field will not display as a date type. The model field: registration_date = models.DateField(null=True, blank=True) The form: class VehicleQuickAdd(forms.ModelForm): class Meta: model = Vehicle fields = ['license_plate', 'internal_id', 'affiliated_company', 'registration_date', 'active_since', 'registration_certificate',] widgets = { 'registration_date': forms.DateInput(attrs={'type': 'date'}) } The HTML: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Add Vehicle{% endblock title %} {% block content %} <div class="section-container container-fluid"> <div class="general-form pl-md-5 pr-md-5"> <h2>Add Vehicle</h2> <form action="" method="post"> {% csrf_token %} {% crispy form %} </br> <input class="btn btn-success" type="submit" value="save"> </form> </div> </div> {% endblock content %} When I look at the element in the page it says type="text" <input type="text" name="registration_date" class="dateinput form-control" id="id_registration_date"> Any ideas about why this isn't working? -
Annotations returning pure PK value instead of Django HashID
In my application the user can assume one of 3 different roles. These users can be assigned to programs, and they can be assigned to 3 different fields, each of those exclusevely to a role. In my API I'm trying to query all my users and annotate the programs they are in: def get_queryset(self): queryset = ( User.objects .select_related('profile') .prefetch_related('managed_programs', 'supervised_programs', 'case_managed_programs') .annotate( programs=Case( When( role=RoleChoices.PROGRAM_MANAGER, then=ArraySubquery( Program.objects.filter(program_managers=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), When( role=RoleChoices.SUPERVISOR, then=ArraySubquery( Program.objects.filter(supervisors=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), When( role=RoleChoices.CASE_MANAGER, then=ArraySubquery( Program.objects.filter(case_managers=OuterRef('pk'), is_active=True) .values('id', 'name') .annotate( data=Func( Value('{"id": '), F('id'), Value(', "name": "'), F('name'), Value('"}'), function='concat', output_field=CharField(), ) ) .values('data') ), ), default=Value(list()), output_field=ArrayField(base_field=JSONField()), ) ) .order_by('id') ) return queryset This works (almost) flawlessly and gives me only 5 DB hits, perfect, or not... The problem is that I'm using Django HashID fields for the Program PK, and this query returns the pure integer value for each Program. I've tried a more "normal" approach, by getting the data using a SerializerMethodField: @staticmethod def get_programs(obj): role_attr = …