Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set default number of entries in Django formset modal table
I have a modal which displays a formset with a list of items (see screenshot) The default number of items is 10, which I want to change. I can't figure out where the settings are to change this. This is my forms.py: class AddTrackerForm(forms.Form): cubecontainerdetail = forms.CharField(required=False, widget=forms.HiddenInput()) boolean = forms.BooleanField(required=False) id = forms.IntegerField( required=False, label='id') name = forms.CharField( required=False, label='Name') school_year = forms.CharField( required=False, label='School Year') year = forms.CharField( required=False, label='Tracker Year') tracker_type = forms.CharField( required=False, label='Tracker Type') This is my views.py: class TrackersListView(ListView): """ View list of trackers """ model = EstablishmentCubeContainer template_name = 'trackers/trackers_list.html' def get_formset(self): tracker_formset = formset_factory(AddTrackerForm, extra=0) tracker_list = CubeContainerDetail.objects.filter(year=current_year) initial_formset = [] for tracker in tracker_list: data = { 'id': tracker.id, 'name': tracker.name, 'school_year': tracker.school_year, 'tracker_type': tracker.cubecontainertag.name, 'year': tracker.year, } initial_formset.append(data) return tracker_formset(initial=initial_formset) This my html : <form method="POST" action="{% url tracker_create_url establishment.id %}" id="trainer_form">{% csrf_token %} <div id="listview" class="tab-pane active display"> {{ form.management_form }} <table class="cell-border table table-striped map_table display nowrap table-condensed" id="tracker-list-table" style="width:100%;"> <thead> <tr> <th>Selected</th> <th>ID</th> <th>Name</th> <th>School Year</th> <th>Type</th> <th>Tracker Year</th> </tr> </thead> <tbody> {% for query in form %} <tr> <td> <input type="checkbox" value={{ query.boolean }}</td> <td>{{ query.id }}</td> <td>{{ query.name.value }}</td> <td>{{ query.school_year.value }}</td> <td>{{ query.tracker_type.value }}</td> … -
How to hide field that is foreing key in serializer based on a statement
This is my serializer class SparkleTemplateSerializer(serializers.ModelSerializer): notifications = NotificationTemplateSerializer(source='notificationtemplate_set', many=True) rules = RuleTemplateSerializer(source='ruletemplate_set', many=True) class Meta: model = SparkleTemplate fields = ['id', 'name', 'description', 'enabled', 'run_schedule', 'notifications', 'rules'] I need to show and hide "notifications" field which is foreign key as you can see, but that need to happen if some variable is true or false. This is how I tried to do it, by adding the code below to a serializer, but I guess it doesn't work cuz of the fields property in Meta def to_representation(self, obj): show = NotificationTemplate._meta.get_field('show') rep = super(SparkleTemplateSerializer, self).to_representation(obj) if show is False: rep.pop('notifications', None) return rep I also tried excluding "notifications" and creating another serializer, but that doesn't work cuz "notifications" has to be there, so I was getting errors. Thanks -
DRF | Serialize Django Model differently depending on a type field
I am coming back in to Django / DRF after a long while.... I have been going over an idea where I have a Django model, called "TheModel", which basically is sorta of a slightly abstract db model which can be associated to numerous types. From a backend business logic standpoint I don't see the need to have multiple models/db tables representing each of these types separately. My hope is this will allowing a user to send along query params to get the types of TheModel they want with the types that are associated with them. If it comes to it, I can just rethink them all as separate models if it doesn't make sense going forward. If TheModel can have types 'A', 'B', 'C' and they may slightly differing JSON return structure needs, what would be the best approach from a high level top -> down for this? In the views would I want to use a ViewSet instead of a ModelViewSet? In which I may just have plain python objects representing the types that reflect the data structure I need which I will convert to from TheModel, which then gets serialized on response? Should I ditch using a … -
How to see all the recent changes of admin panel, who did it and when?
I want to see all the recent actions that has been done, how can i see it? -
Sharing data between plotly dash and django views
I want to store some json data that returns from a django view in dcc.store on app startup. I'm new to django-plotly-dash. Is there any resources I can refer to solve this. Djnago View looks like this def renderPage(requests): data = load_data() context = {} context = { 'page_data' : data } return render(requests, 'dashboard.html', context) ``` Following is the code snippet of the layout app.layout = html.Div( [dcc.Location(id="url"), dcc.Store(id="page-data"), html.Div(id="page-content")], ) -
Django call_command("makemigrations") strange behaviour
python manage.py makemigrations from commandline and call_command("makemigrations") from the django app results in different behaviour. Whereas the commandline is the expected behaviour, the call_command("makemigrations") removes my model from the migration and after calling migrate also from the database. When I use the command line and type python manage.py makemigrations I receive: Migrations for 'rest_service': rest_service\migrations\0009_tour.py - Create model Tour then python manage.py migrate, I receive: Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, rest_service, sessions, tenants Running migrations: Applying rest_service.0009_tour... OK So everything is okay. After the startup of my testsuite, I can see my test database created by django. This looks as expected with a table for my model tour. But after running this inside my tests call_command("makemigrations") call_command("migrate", database="default") the model (tour) was removed from the database. if I run makemigrations again I get this Migrations for 'rest_service': rest_service\migrations\0011_tour.py - Create model Tour and after migrate this Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, rest_service, sessions, tenants Running migrations: Applying rest_service.0010_delete_tour... OK Applying rest_service.0011_tour... OK If i only use call_command("migrate", database="default") without the makemigrations it works, but this is not a satisfying solution. Why does makemigrations inside the django app behave different compared … -
Django REST framework POST request with dynamic field inside a nested field using Serializer
I want to send a POST request in an API with the two different data samples as below. The POST data has different schema on options key depending on the choice key. The keys inside options key differ except few common fields. I want to validate the fields with the help of Serializer too. How can I solve this? Case 1 { "name": "name1", "options": { "choice": "choice1", "common_option1": value1, "common_option2": value2, "choice1_option1": value3, "choice1_option2": value4 } } Case 2 { "name": "name2", "options": { "choice": "choice2", "common_option1": value5, "choice2_option1": value6, "choice2_option2": value7, "choice2_option3": value8 } } -
How to render the timedelta of a Django datetime field vs. now?
I do have a Model Vote that contains a DateTimeField which returns the date in the template like so: Sept. 22, 2021, 10:02 a.m. # Model class Vote(models.Model): created_on = models.DateTimeField(auto_now_add=True) I now want to render the time delta between now and the time stored in the Model in the template: # Template <div> voted {{ vote.created_on|datetime_delta }} ago</div> Should render for example: voted 16 hours ago or voted 3 days ago As far as I know there is no built-in solution to this in Django, thus I tried to create an individual template filter: # Template filter from django import template import datetime register = template.Library() # Output Django: Sept. 22, 2021, 10:02 a.m. # Output datetime.now(): 2021-09-22 12:56:57.268152 @register.filter(name='datetime_delta') def datetime_delta(past_datetime): datetime_object = datetime.datetime.now().strftime("%bt. %d, %Y, %H:%M %p") print(datetime_object) # prints Sept. 22, 2021, 13:20 PM So I somehow tried to create two time objects in the same structure to calculate the time delta but can't make it fit 1:1. Anyways, I don't know if this might be a working approach and neither do I know if there are smarter solutions to this? -
Custom tag to set a variable in Django template. Emptying the value out of context?
In my Django Template I want to set a variable, to use in a html tag. But, when I'm out the for loop, the variable is empty :( <select > <option value=""></option> {% for a_status in status %} {% for r in all_status_ressources %} {% if a_ressource.id == r.0 and a_status.name == r.1 %} {% setvar "selected" as selected_status %} id ressource : {{ r.0 }}, name status : {{ r.1 }} -> [{{ selected_status }}]<br> {% endif %} selected_status : "{{ selected_status }}" {% endfor %} end loop ---------> selected_status : "{{ selected_status }}" <option value="{{ a_status.id }}" selected="{{ selected_status }}">{{ a_status.name }}</option> {% endfor %} </select> And, now the debug trace : selected_status : "" id ressource : 2, name status : "my personnal status" -> [selected] selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" selected_status : "selected" end loop ---------> selected_status : "" So, when I'm out of the for loop, the varible is not set to be used in the html tag. Have you an … -
Django: How to "join" two querysets using Prefetch Object?
Context I am quite new to Django and I am trying to write a complex query that I think would be easily writable in raw SQL, but for which I am struggling using the ORM. Models I have several models named SignalValue, SignalCategory, SignalSubcategory, SignalType, SignalSubtype that have the same structure like the following model: class MyModel(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField() fullname = models.CharField() I also have explicit models that represent the relationships between the model SignalValue and the other models SignalCategory, SignalSubcategory, SignalType, SignalSubtype. Each of these relationships are named SignalValueCategory, SignalValueSubcategory, SignalValueType, SignalValueSubtype respectively. Below is the SignalValueCategory model as an example: class SignalValueCategory(models.Model): signal_value = models.OneToOneField(SignalValue) signal_category = models.ForeignKey(SignalCategory) Finally, I also have the two following models. ResultSignal stores all the signals related to the model Result: class Result(models.Model): pass class ResultSignal(models.Model): id = models.BigAutoField(primary_key=True) result = models.ForeignKey( Result ) signal_value = models.ForeignKey( SignalValue ) Query What I am trying to achieve is the following. For a given Result, I want to retrieve all the ResultSignals that belong to it, filter them to keep the ones of my interest, and annotate them with two fields that we will call filter_group_id and filter_group_name. The values of … -
What are the options to filter Enums values from Swagger documentation?
I'm using Django with drf-spectacular package to generate Swagger documentation. I was wondering is there any better approach to filter out some values from the Enum section inside Schema. Right now I've accomplished this using custom hook preprocess_schema_enums Enums are specified as a field in a models file hook.py def preprocess_schema_enums(result, generator, request, public): excluded = ['value1', 'value2'] enums_response = result['components']['schemas']['CustomEnum']['enum'] filtered = [res for res in enums_resoinse if res not in excluded] result['components']['schemas']['CustomEnum']['enum'] = filtered return result -
Django get queryset objects to call a function
I am trying to build APIs for a project in django, basically the code works in normal django but I am unfamiliar with Django rest Framework. Once the user uploads his image (post method), the ocr function needs to be called and the response should be the data returned by that OCR Function (extracted data from the image). The queryset is having id, name and image but I am unable to call ocr(). My code till now. api/models.py: from os import name from django.db import models from numpy import mod # Create your models here. # Create your models here. class PanCard(models.Model): name = models.CharField(max_length=255) image = models.ImageField() api/views.py: from django.db.models.query import QuerySet from django.http import request from pcard.forms import ImageUploadForm from django.conf import settings from numpy import generic from rest_framework import generics, status from rest_framework.decorators import api_view, renderer_classes from rest_framework.response import Response from .models import PanCard from .serializers import PanCardSerializer from .ocr import ocr class PanCardView(generics.ListCreateAPIView): queryset = PanCard.objects.all() serializer_class = PanCardSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() ############################################################################################## class PanCardViewDetails(generics.RetrieveUpdateDestroyAPIView): queryset = PanCard.objects.all() serializer_class … -
Chain two Django querysets preserving order
I have two querysets: promoted = Post.prefetched_objects.filter(account_type=AccountType.TOP_LEVEL).order_by("?") regular = Post.prefetched_objects.filter(account_type=AccountType.REGULAR_LEVEL).order_by("?") How to chain those two querysets? I need to return promoted on top but in random order and then regular ones in random order too. -
Django how to display all child objects under it's parent?
In my views I am filtering all parent parent objects. support_object = Contact.objects.filter(user=user,parent__isnull=True). In my html I am showing all parent objects but how to show if any parent have child objects. I want to show all child objects under it's parent. html {%for i in support_object%} parent{{i.name}} parent{{i.message}} #here I want to show all child message of parent {%endfor%} -
get model object value dynamically by iterating the django model
i want to fetch value dynamically in django model users = User.objects.all() for user in users: print(user.first_name) works fine # now how to make it dynamic fieldnames= "first_name" print(user.fieldnames) # but how to do this for making dynamic -
Variable value not as expected after setting it [closed]
Django app. I'm generating an excel report file. Different customers can add their own custom fields, and I'm trying to add these also to the report (like: weighing number = 75135, humidity = 54%), but the fields appear empty in the report (weighing number = "", humidity = ""). I set field_name=field.name and then try getting the value from dictionary with .get(field_name), but get None instead and print() statements show me that field.name = "weighing number" (expected value), while field_name = <MultilingualQuerySet [ <OrderRow: ORD017524: Item 1>, <OrderRow: ORD017490: Item 2> ]> (not expected value). field: ClientDefinedField for field in order_custom_fields: exportable_fields.insert( 5, { "name": field.name, "header": field.human_readable_name, "get_data": lambda row, field_name=str(field.name): row.order.extra_fields.get( "CLIENT_DEFINED_FIELDS", {} ).get(field_name), }, ) When converting it to a list list(row.order.extra_fields.get("CLIENT_DEFINED_FIELDS", {}).values())[0] I get the fields in the report filled, but incorrectly (like: weighing number = 75135, humidity = 75135). What may be the reason for this behavior? What would be an alternative way of achieving the expected result? -
Advice on using Django channels to recive high frequency data and save in db
I have recently started learning Django Channels and tried to use it in one of my application which receives frequent data (100-200 times/minute) from client and save in database. The following is the code for the receive function in WebSocket Consumer. def receive(self, text_data): text_data_json = json.loads(text_data) print('Data received',text_data_json) session = text_data_json["session"] user = text_data_json["user"] group = text_data_json["group"] strDate = text_data_json["strDate"] activity = text_data_json["activity"] # code to save the record in Django Model VAD VAD.objects.create(session=session,user=user,group=group,timestamp=strDate,activity=activity) I tried it in the development mode and it seems to be working. Consumer code is working fine, receiving data and saving in db. Before updating the server for it, I want to ask would this approach of having consumers to save data in database is good one. If there are some issues with this then could you please share your expert opinion on it. Also, could you please suggest a way to reduce the number of disk write due to saving data in db for each received record. Thank you in advance. -
How to deploy Django project on windows server?
I have to deploy django website on windos server. Please give me detailed steps how to accomplish this task. thanks in advance. -
How to trigger the action after bulk_create in Django ORM?
I want to process the table as an atomically correct one only after I collect all the required pieces. I see the possible solution as I check out different required chapters in a separate model after Model.objects.bulk_create(arr). How to mark these chapters after bulk_create in Django? -
How do I make reusable page fragments in Django?
I want to create sort of "fragments" that I can reuse on any page. I'm aware of the {% include %}, but the the goal here is to put some sort of logic in them. Basically, they should act like mini-views. (?) An article recommendation block here, for example, must have some logic attached to it (querying the models maybe) and I must be able to put it in any page I want. I feel like the solution there is very simple and I'm just too confused about something :) -
Use JS onclick to pass some data to Django views.py?
Templates <div class="products__header--search-result"> <ul> {% for product in products %} <li onclick="change('{{ product.id }}')"><a href="#">{{ product.name }}</a></li> {% endfor %} </ul> </div> <script> function change(foo) { $.ajax({ url: {% url 'dashboard' %}, data: { 'foo': foo, }, }); } </script> views.py myRequets = request.GET.get('foo') But myRequets return 'None' How can I fix this? Is there a better way to pass values to views.py? -
Please help.I'm getting form.is_valid() false
I'm doing a upload file functionality and getting a form.is_valid() as false and aslo getting GET request instead of POST request This is my view @require_http_methods("POST") def userlistfileupload(request): ''' This function is created to upload userlist ''' form = UserlistUploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(reverse('account:userlist')) else: form = UserlistUploadFileForm() return render(request, 'auth/upload_userlist.html',{'form':form}) This is my form class for upload file. class UserlistUploadFileForm(forms.Form): ''' This function is created for Userlist file upload functionality ''' userlistfile = forms.FileField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'post' self.layout = Layout( 'userlistfile', ) self.helper.add_input(Submit('submit' , 'Upload Userlist')) def clean_file(self): f = self.cleaned_data("file") if not f.endswith('.csv'): raise forms.ValidationError('Please Upload csv file only.') This is my template : Upload_userlist.html {% extends "base.html" %} {% load crispy_forms_tags %} {%load permission_tags%} {%block title%}Upload User List{%endblock%} {% block content %} {% if user|has_role:'posh_admin' %} <div class="row"> <div class="col"></div> <div class="col"> <h3 class="text-center">Upload Userlist</h3> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} </form> </div> <div class="col"></div> </div> {% endif %} {% endblock %} This is my userlist.html part. I have used crispy forms please check <h5>User List</h5> </div> <div class align="right"> <a class="btn btn-primary " href = {% static 'userlist_template.csv' %}>Download template</a> <a … -
How to create dynamic form using JSONSchemaField based on ID passed from the form request in Django?
The form is rendering properly if I give ID as a static value in forms.py, it wont render properly when I use the ID that I got from form call views.py def assetAddJsonView(request,pk): form = AssetAddjsonForm(id = pk) context = { 'form': form } return render(request, 'asset_add_json.html', context) forms.py from django_jsonforms.forms import JSONSchemaField class AssetAddjsonForm(Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop('id') super(AssetAddjsonForm, self).__init__(*args, **kwargs) type_json_schema = Types.objects.values_list('details').get(id=1) type_json_schema = list(type_json_schema)[0] add_asset = JSONSchemaField(schema = type_json_schema, options = options) Instead of passing id=1 I want to pass the value I got in self.request I referred the link that I mentioned here Django app generating forms dynamically from JSON? Thanks in advance -
Display labels of ModelMultipleChoiceField
How to display the labels of the choices in a ModelMultipleChoiceField ? This is the form : class MakeAnAppointmentForm(forms.Form): time_slot = forms.ModelMultipleChoiceField(queryset = None, widget=forms.CheckboxSelectMultiple()) def __init__(self,*args,**kwargs): date = kwargs.pop('date') super().__init__(*args,**kwargs) self.fields['time_slot'].queryset = Appointment.objects.filter(date = date).values_list('time_slot', flat = True) self.fields['time_slot'].label = "date" But it displays this : And I want this : in accordance to this : TIMESLOT_CHOICES = (('0', '09:00 - 09:30'), ('1', '09:30 - 10:00'), ('2', '10:00 - 10:30'), ('3', '10:30 – 11:00')... How is this possible ? Thank you. -
Django annotate count unique user from 2 tables
Is it possible to do an annotate count on technically 2 different tables, but same FK? Example: queryset = ModelName.objects .annotate(mileage_emp_count=Count('mileageclaim__user',distinct=True)) .annotate(general_emp_count=Count('expenseclaim__user', distinct=True)) For instance using this, is User A has a mileage and an expense claim, they will appear in both queries. So I will have result of 2 if i add them together. What i need to do, is get a total of 1 unique user instead. Is it possible without a lot of extra checks?