Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django can't save parent id of child objects
I am tying to save parent id when the forms will be save but I am not understanding where I am doing mistake. I am using <input type="hidden" name="parent" id={{i.sno}}> for save parent id and I can see the id number if I inspect html from browser. models.py class Contact(MPTTModel): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='contact_user') parent =TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') sno = models.AutoField(primary_key=True,) #my others fields.... forms.py class TicketForm(forms.ModelForm): class Meta: model = Contact fields = ['message','parent','sno','existing_customer','technical_service'] views.py def SupportPageView(request): if request.method == "POST": support_form = TicketForm(request.POST or None) if support_form.is_valid(): isinstance = support_form.save(commit=False) isinstance.user = request.user isinstance.name = request.user.first_name isinstance.email = request.user.email isinstance.save() name = request.user.first_name messages.add_message(request, messages.INFO, f'{name} Thanks for your message. We will get back to you very soon') return redirect('contact:support-ticket') else: support_form = TicketForm() user = request.user support_object = Contact.objects.filter(user=user) context = {"support_form":support_form,'support_object':support_object} return render(request,"contact/support.html",context) HTML {%for i in support_object%} <form method="POST"> {%csrf_token%} <textarea name="message" class="form-control" style="height: 150px;"></textarea><br> <input type="hidden" name="parent" id={{i.sno}}> <button type="submit" class="btn btn-info">Submit</button> </form> {%endfor%} my forms is saving as a parent but I want they will save as child. -
How can I show last 4 posts in django?
I try to show last 4 posts with Django by using Class-Based Views, but No data (post) shows on page. that's code: views.py : class PostList(ListView): model=Post paginate_by=10 context_object_name='all_posts' ordering=['-created_at'] latest=model.objects.order_by('-created_at')[:4] templates/post_list.html : {% for post in latest %} <div class="col-sm-12 col-md-6 col-lg-3" > <!-- cards--> <div class="card "> <img src="{{post.image.url}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{post.title}}</h5> <p class="card-text">{{post.content}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> <!-- ends cards--> </div> {% endfor %} my thanks -
Count every hit with django-hitcount
Is there a way to make Django hitcount module count every hit? Currently, it counts once for a single IP but I want it to every hit. How can I achieve this? -
django getting values from form
I need to filter the table by column and value, nothing better comes to my mind (I'm new in django) view def get_queryset(self): column = self.request.GET.get('column') condition = self.request.GET.get('condition') queryset = Table.objects.all() if condition == 'contains' and column == 'title': queryset = Table.objects.filter( title__icontains=self.request.GET.get('title') ) elif condition == 'greater' and column == 'quantity': queryset = Table.objects.filter(quantity__gt=self.request.GET.get('title')) elif condition == 'greater' and column == 'distance': queryset = Table.objects.filter(distance__gt=self.request.GET.get('title')) elif condition == 'lower' and column == 'quantity': queryset = Table.objects.filter(quantity__lt=self.request.GET.get('title')) elif condition == 'lower' and column == 'distance': queryset = Table.objects.filter(distance__lt=self.request.GET.get('title')) elif condition == 'equals' and column == 'quantity': queryset = Table.objects.filter(quantity__exact=self.request.GET.get('title')) elif condition == 'equals' and column == 'distance': queryset = Table.objects.filter(distance__exact=self.request.GET.get('title')) return queryset i knew it looks like **** please give me more elegant idea) there my table the idea is as follows, the user selects a column and the condition by which the table will be filtered thanks -
try to implement the live search by using django and AJAX
I am new to the Django and AJAX. I am trying to implement "live search" function by using django framework and the AJAX. This function will search the applications by using the name. The application model has its title. Then user can use search bar to make live search, which will show up results when you type the title. However, I did not figure out how it works. Hopefully someone can give me a hint. It will be appreciated if someone can help. JQuery $('document').ready(function(){ $('#search').keyup(function(e){ let csrftoken = '{{ csrf_token }}'; $.ajax({ type : 'POST', headers:{'X-CSRFToken':csrftoken}, url: "{% url 'search' %}", data: { 'search_text': $('#search').val() }, success: function(data){ console.log(data); $('html').load(data); } }); }); }); View.py @login_required(login_url='login') @allowed_users(allowed_roles=['student']) def search(request): data = dict() if request.method == "POST": search_text = request.POST["search_text"] if search_text is not None: applications = Application.objects.filter(user=request.user, title=search_text) data['result'] = applications print(data) return JsonResponse(data) However, in the view.py , the "data" cannot print out Also, is there another way to pass "applications" to the HTML and update the webpage? Since this code does not work for the live search -
django can't reverse match url from template
I ma having difficulty reverse matching a url, getting the error: NoReverseMatch at /patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/ Reverse for 'treatment_detail' with no arguments not found. 1 pattern(s) tried: ['patient/(?P<patient_id>[^/]+)/$'] The url is: /patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/ (the string is the 'apatient_id' and changes each time the user submits the 'add' page) urls.py is app_name = "patient" urlpatterns = [ path( route='add/', view=views.PatientAddView.as_view(), name="patient_add"), path( route='<patient_id>/', view=views.TreatmentTemplateView.as_view(), name='treatment_detail'), ] html <form action="{% url 'patient:treatment_detail' %}" method="get"> <input type="submit" class="btn btn-primary" value="get_doc" name="get_doc"> </form> views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context If I have 'patient:patient_add' instead of 'patient:treatment_detail' it works fine so the issue seems to be about the route="<patient_id>"/ In urls.py -
Django-Filter Nested Serializer MultipleObjectsReturned
I have created an drf app and which includes nested relations. enter image description here As shown below I put the relations in my parent serializer.Then I am using it as an list and retrieve method supported by modelviewset enter image description here -
Django Filter on Distinct with orderby created at
How can I filter with distinct and order by IncomingCallRecording.objects.filter( ).order_by("lead_id","-created_at").distinct("lead_id") Problem Order by is not working with created at Is there an alternative solution that might help -
OSError('Tunnel connection failed: 403 Forbidden')))
Am trying to initiate a request to an API (https://theteller.net/documentation#theTeller_Standard) but i keep getting this error. The idea is that will take details of the user and pass it to my views.py to send a request to to make payment and be redirected back to my website. This is the error ProxyError at /vote/test/robert-yenji/ HTTPSConnectionPool(host='test.theteller.net', port=443): Max retries exceeded with url: /checkout/initiate (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden'))) this is my code views.py def nomination_payView(request, slug): if request.method == 'GET': model = get_object_or_404(Nomination, slug=slug) template_name = 'Payment.html' context = { 'nomination': model } return render(request, 'Payment.html', context) elif request.method == 'POST': amount = (str(int(request.POST['amount']) * 0.5) + '0').replace('.', '') zeros = '0' * (12 - len(amount)) amount = zeros + amount email = request.POST['email'] desc = request.POST['desc'] url = 'https://test.theteller.net/checkout/initiate' transaction_id = random.randint(100000000000, 999999999999) data = { "merchant_id": "TTM-00000740", "transaction_id": transaction_id, "amount": amount, "redirect_url": f"http://127.0.0.1:8000/process-payment/{slug}/{amount}", "apiuser": "halotech5d525bfd6ead3", "API_Key": "ZDQ2OGEyZDNjN2YzMDY5ZDVkY2MyM2U5YTRiMGI0N2Q=", "email": email, # you would need to change this to the actual users email "desc": desc, # this as well... } encoded = base64.b64encode( b'halotech5d525bfd6ead3:ZDQ2OGEyZDNjN2YzMDY5ZDVkY2MyM2U5YTRiMGI0N2Q=') # change this as well headers = { 'Content-Type': 'application/json', 'Authorization': f'Basic {encoded.decode("utf-8")}', 'Cache-Control': 'no-cache' } res = requests.post(url, data=json.dumps(data), headers=headers).json() … -
Django date field enable/ highlight only certain dates
My files are as below : Forms.py class FilterDaywiseNew(forms.Form): search_Day = forms.DateField(widget=NumberInput(attrs={'type': 'date'}),required=True,initial=datetime.date.today) Views.py def DayWiseFilterPage(request): form = FilterDaywiseNew() return render(request, 'agelist.html',{'form': form}) agelist.html <form method="post" action="SearchDisplay" id="searchFilterForm"> <div class="form-row"> <div class="col-md-8 mb-0"> {{ form.search_Day|as_crispy_field }} </div> </div> </form> My rendered html is like this <div id="div_id_search_Day" class="form-group"> <label for="id_search_Day" class=" requiredField"> Search day<span class="asteriskField">*</span> </label> I have a bunch of dates, that I would want to populate the datefield with, so that only these dates are enabled/ highlighted/ can be selected, like this Solutions given use JQuery to do this. I dont want to use JQuery. Is there a way this can be achieved? Thanks, -
Case insensitive search doesn't work on Django (Postgres) with non-latin characters
PostgreSQL 13.4 Django 3.2 MacOS 11.2 I try to implement a search function for finding a model instance by the "name" field. models.py class LatestConfiguration(models.Model): # Primary key name = models.CharField(verbose_name='Имя', max_length=150, unique=True, primary_key=True) Database encoding is UTF8: ➜ ~ psql <DB_NAME> -c 'SHOW SERVER_ENCODING' server_encoding ----------------- UTF8 (1 row) Database contains records, eg: Бухгалтерия для Казахстана, редакция 3.0 I try to search a model instance like that: LatestConfiguration.objects.filter(name__icontains='Бух') the output is ok: >>> LatestConfiguration.objects.filter(name__icontains='Бух') <QuerySet [Бухгалтерия для Казахстана, редакция 3.0]> I lower-cased the first letter in 'Бух' to 'бух' and repeated the search >>> LatestConfiguration.objects.filter(name__icontains='бух') <QuerySet []> so now I get an empty queryset but I shouldn't I also tried Q-objects: Q(name__istartswith='бух') but didn't get any results Tried to use postgres full text search by adding: 'django.contrib.postgres', to INSTALLED_APPS in settings.py and repeated searching this way: >>> LatestConfiguration.objects.filter(name__icontains='бух') <QuerySet []> Anyone else got the same error? -
Heroku can't load my css file because its a mimetype
I deployed my website it all works and main css loaded but for some reason my another css refusing to load in the console it say Refused to apply style from '......' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. This is my setting.py Am i missing something ? MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_DIRS = [ BASE_DIR / "static", BASE_DIR / 'media', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn') TEMP = os.path.join(BASE_DIR, 'media_cdn/temp')