Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST, multiple querysets in one GET
I have the following two models: models.py: from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True) project = models.ForeignKey('Project', on_delete = models.SET_NULL, null = True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id The Userprojects 'user' and 'project' field point to the Usermodel and the Projectmodel above. Right now I have this view: class GetUserDataByNameView( APIView, ): def get(self, request, username): if User.objects.filter(username = username).exists(): uid = User.objects.get(username = username).id queryset = Userproject.objects.filter(user_id = uid) readSerializer = GetUserDataSerializer(queryset, many = True) return Response(readSerializer.data) else: return Response({"status": "error", "data":"no user with this username"}, status = 200) and this serializers from rest_framework import serializers from .models import Project from .models import Userproject class ProjectSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length = 500, required = True) descriptor = serializers.CharField(max_length = 1000, default = None) class Meta: model = … -
Django DataTable with Dynamic Models
I want to read a csv or text file then create a DataTable to allow users to search and filter the loaded file. I currently have pre-defined models for sample csv files but the challenge is not knowing what file format (columns) the user will load to view and query. Is there a way to simply load a file (csv or text) in Django then interact with the data (DataTables preferred) via the browser? Thanks I currently use https://github.com/morlandi/django-ajax-datatable and it's great but requires models to be pre-defined. -
Saving the all checkbox data in the database in django
I have created multiselect dropdown check in the UI part but only checkbox selection is saving in the database. For example: If user selects US, France, Germany in country dropdown checkbox only US is getting saved in the database. I don't know where I'm going wrong. views.py: def homeview(request): userb = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() if request.method == 'POST': userb = Userbase() userb.company_code = request.POST.get('company_code') userb.Area = request.POST.get('area') userb.country = request.POST.get('country') # userb.Netdue_Date = request.POST.get('datefilter') userb.From_Date = request.POST.get('from_Date') userb.To_Date = request.POST.get('to_Date') userb.Predicted_Paid_days = request.POST.get('Predicted_Paid_days') userb.PBK_Desc = request.POST.get('PBK_Desc') userb.Vendor_Name = request.POST.get('Vendor_Name') userb.Reference = request.POST.get('Reference') userb.Payment_Term = request.POST.get('Payment_Term') userb.save() return render(request, 'home.html', {'userb':userb,'table_data':table_data}) html: <div class="form-group col-sm-9" style="margin-left: 19px; font-size: 17px;"> <label for="myMultiselect">Country</label> <div id="myMultiselect" class="multiselect"> <div id="mySelectLabel" class="selectBox" onclick="toggleCheckbox()"> <select class="form-select"> <!-- <select class="selectpicker"> --> <option>Select Country</option> </select> <div class="overSelect"></div> </div> <div id="mySelectOptions" name="country"> <label for="id_country_0"><input type="checkbox" name="country" id="id_country_0" onchange="checkboxStatusChange()" value="US" /> US</label> <label for="id_country_1"><input type="checkbox" name="country" id="id_country_1" onchange="checkboxStatusChange()" value="EMEA" /> EMEA</label> <label for="id_country_2"><input type="checkbox" name="country" id="id_country_2" onchange="checkboxStatusChange()" value="ASIA" /> ASIA</label> <label for="id_country_3"><input type="checkbox" name="country" id="id_country_3" onchange="checkboxStatusChange()" value="LATAM" /> LATAM</label> <label for="id_country_4"><input type="checkbox" name="country" id="id_country_4" onchange="checkboxStatusChange()" value="UK" /> UK</label> <label for="id_country_5"><input type="checkbox" name="country" id="id_country_5" onchange="checkboxStatusChange()" value="Ireland" /> Ireland</label> </div> </div> -
Display Charts based on year select in django
I am using django=3.0.0 as my backend. I have years in my database as a datetimefield and I want to put it as an option for my select button which will change the charts dynamically in chartjs. Do I have to make a filter for this or is there any other way to put my years in chartjs. Can anyone guide me how to do this? -
Django insert OTP code to display div on website
I am reading about Django otp framework and I've implemented it in my Django admin login panel. I was following steps from this site. However, I am wondering if it is possible to implement something like this directly on website. You have content that is visible for all logged in users but in order to show div[class="supercontent"] that is on the bottom of the page user has to click this div, provide phone nunmber and insert the code that will be sent on this number. -
Passing WSGI Request with eval()
I have functions to call that come in as string so I use def sayHi(parameterA, request): print("Hi") string_function_name = "sayHi" def call_dynamic_function(A, request): eval(string_function_name+"(parameterA='{}',request='{}')".format(A, request)) call_dynamic_function(A= string_function_name, request=request) The request I am trying to pass in is Http WSGI Request. However I get an error in trying to do so. SyntaxError: invalid syntax -
How to add pagination to search result page in Django?
Here is my code but it not working. I have added this code on m search result page for articles. i don't know whether i have done a mistake {% if all_searched_article.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ all_searched_article.previous_page_number }}" tabindex="-1"><i class="fa fa-angle-left"></i></a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1"><i class="fa fa-angle-left"></i></a> </li> {% endif %} {% for num in all_searched_article.paginator.page_range %} {% if all_searched_article.number == num %} <li class="page-item active"><a class="page-link" href="#">{{ num }}</a></li> {% elif num > all_searched_article.number|add:"-3" and num < all_searched_article.number|add:"3" %} <li class="page-item"><a class="page-link" href="?page={{ num }}">{{ num }}</a></li> {% endif %} {% endfor %} {% if all_searched_article.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ all_searched_article.next_page_number }}"><i class="fa fa-angle-right"></i></a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" ><i class="fa fa-angle-right"></i></a> </li> {% endif %} </ul> </div> -
Django looses session data
This is a very strange phenomenon which i have. My site works properly most of the time. But, from time to time (in the same session), some session info is not saved. i've added at the end of my view: request.session.modified = True and in my settings, added: SESSION_SAVE_EVERY_REQUEST = True Also tried in the view: request.session.save() Still - nothing helps. From time to time, session information is not stored. i look at the Dbase and i see that it is indeed not saved. im using django session with cached_db and PickleSerializer. Any idea? -
Async Django Rest Framework Examples
Does anyone have any examples on how I can make my DRF modelviews async? Reading the Django docs there is talk of making the views call() method async but I cannot find any examples of how I would do that. Also is there any examples of unit testing my async api call? I've been using unittest to run my tests, which doesn't support testing a coroutine? -
No file was submitted. Django Rest Framework React js
I have this model in django where it have a imageField and it works when I tested it on Postman but when I try to integrate it on React the payload message is that there's no file submitted. Here is my code: models.py class File(models.Model): ... def upload_to(instance, filename): return "posts/{filename}".format(filename=filename) class UploadedFile(File): file = models.ImageField(_("Image"), upload_to=upload_to) views.py class FileUploadedCreate(APIView): permission_classes = [permissions.IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) serializer = FileUploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() return response.Response(serializer.data, status=status.HTTP_200_OK) else: return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class FileUploadSerializer(serializers.ModelSerializer): class Meta: model = UploadedFile fields = "__all__" react code ... const [uploadFile, setUploadFile] = useState(null); const onChange = (e) => { if ([e.target.name] == 'image') { setUploadFile({ file: e.target.files[0] }); } console.log(e.target.files); }; useEffect(() => {}, [uploadFile]); const handleUpload = () => { if (uploadFile) { if (selectedFolder !== 0) { let formData = new FormData(); formData.append('image', uploadFile); let url = 'http://localhost:8000/classroom/resources-file/upload'; axios .post(url, formData, { headers: { 'content-type': 'multipart/form-data', }, }) .then((res) => { console.log(res.data); }) .catch((err) => console.log(err)); console.log(uploadFile.file, uploadFile.file.name, selectedFolder); } else { alert('Please select folder for your file'); } } }; .... return ( <input accept='image/*' name='image' onChange={onChange} id='upload-file-button' type='file' /> <button onClick={handleUpload}> Submit </button> Please help … -
Show multiselectfield value in Bootstrap 4 multiselect dropdown in Django template
I am following this answer for the multi-selecting dropdown. I am using django-multiselectfield to collect data in the DB model. I want to show value in bootstrap multi-selecting dropdown but getting the below result I am seeking this result These are my code snippet model.py from django.db import models from multiselectfield import MultiSelectField class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Person(models.Model): obj=Country.objects.all() TEAM=tuple((ob,ob) for ob in obj) name = models.CharField(max_length=124) southasia=MultiSelectField(max_length=200, choices=TEAM) def __str__(self): return self.name views.py from django.http import JsonResponse from django.shortcuts import render, redirect, get_object_or_404 from .forms import PersonCreationForm from .models import Person def person_create_view(request): form = PersonCreationForm() if request.method == 'POST': form = PersonCreationForm(request.POST) if form.is_valid(): form.save() return redirect('person_add') return render(request, 'miracle/index.html', {'form': form}) forms.py from django import forms from .models import Person class PersonCreationForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) template {% load crispy_forms_tags %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <title>Dependent Dropdown in Django</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script> </head> <body> <h2>Person Form</h2> <form method="post"> {% csrf_token %} {{ … -
How to call another websocket function in django channels consumer functions?
I have following code in consumers.py def websocket_receive(self,event): print(f'[{self.channel_name}] - Recieved message - {event["text"]}') async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': event.get('text') } ) def websocket_message(self,event): print(f'[{self.channel_name}] - message Sent - {event["text"]}') self.send({ 'type':'websocket.send', 'text':event.get('text') }) I want to call the message function whenever a message is recieved so in websocket_recieve function I have addes 'type': 'websocket.message', but I don't know why websocket_message function is not being called? I am new to django channels. any help will be appreciated. -
How to configure multiple language in my django model?
Here I want to give users to select languages while creating model objects. For this I tried like this. Is this way there will be any problems ? And I think I should have to migrate MyModel each time if new language option gets added in the project setting ? What any other options would be better for this scenario ? note: I don't want to use third party packages. settings import os gettext = lambda s: s LANGUAGES = [ ("en-us", gettext("English")), ('de', gettext('German')),] models def get_project_languages(): languages = settings.LANGUAGES languages_choices = [] for lang in languages: languages_choices.append((lang[0], lang[1])) return languages_choices language_choices = get_project_languages() class MyModel(models.Model): language = models.CharField(choices=languages_choices) content = models.TextField() -
how to access template variables in ajax jquery in javascript using Django template
I have got a javascript containing ajax jquery which refreshes a template based on the data returned as shown below - =============================================================== product-filter.js is below code $(document).ready(function(){ $(".ajaxLoader").hide(); $(".filter-checkbox").on('click',function(){ var _filterObj={}; $(".filter-checkbox").each(function(index,ele){ var _filterVal=$(this).val(); var _filterKey=$(this).data('filter'); _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){ return el.value; }); }); //Run Ajax $.ajax({ url:'/filter-data_b/1', data: _filterObj, dataType: 'json', beforeSend: function(){ $(".ajaxLoader").hide(); }, success:function(res){ console.log(res); $("#filteredProducts_b").html(res.data); $(".ajaxLoader").hide(); } }) }); =============================================================== I am able to get this working with /filter-data_b/1 where 1 is brand_id which is hard-coded and I want to know how to get this from the template where product-filter.js is called from the /filter-data_b/1 code in views.py and urls.py is as shown below urls.py urlpatterns = [ path('', views.home,name='home'), path('brand_product_list/<int:brand_id>', views.brand_product_list,name='brand_product_list'), path('filter-data_b/<int:brand_id>',views.filter_data_b,name='filter_data_b'), ] ================================================================= views.py is def filter_data_b(request,brand_id): colors=request.GET.getlist('color[]') categories=request.GET.getlist('category[]') brands=request.GET.getlist('brand[]') sizes=request.GET.getlist('size[]') flavors=request.GET.getlist('flavor[]') allProducts=ProductAttribute.objects.filter(brand=brand_id).order_by('-id').distinct() if len(colors)>0: allProducts=allProducts.filter(productattribute__color__id__in=colors).distinct() if len(categories)>0: allProducts=allProducts.filter(category__id__in=categories).distinct() if len(brands)>0: allProducts=allProducts.filter(brand__id__in=brands).distinct() if len(sizes)>0: allProducts=allProducts.filter(productattribute__size__id__in=sizes).distinct() if len(flavors)>0: allProducts=allProducts.filter(productattribute__flavor__id__in=flavors).distinct() t=render_to_string('ajax/product-list_b.html',{'data':allProducts}) return JsonResponse({'data':t}) =========================================================================== -
Django Bootstrap modal update form not showing data
I have created 2 modals in separate html files to handle creation and update of the applicant status. Both modals are triggered on the same page, the applicant detail, and are showing the form, and the update form is not displaying the data, even though the clickable button shows the correct link. applicant_detail.html <div class="row mb-1"> <div class="col"> <h4>Applicant Status</h4> </div> <div class="col col-auto"> <a href="#applicantStatusCreate" class="btn btn-primary text-white float-end" data-bs-toggle="modal"> Add Applicant Status </a> {% include 'recruitment/applicant_status_create.html' %} </div> </div> <!---Applicant Status Start---> {% for status in applicant_status_detail %} <div class="card mb-4"> <div class="card-body p-4"> <div class="row"> <div class="col-xl-5"> <h5>{{ status.applicant_status }}</h5> <ul class="personal-info"> <li> <div class="title">Status Date</div> <div class="text">{{ status.status_date|date:"M d, Y" }}</div> </li> <li> <div class="title">Rating</div> <div class="text">{{ status.rating }}</div> </li> </ul> </div> <div class="col-xl-7"> <a href="{% url 'recruitment:applicant_status_edit' pk=status.id %}" class="edit-icon float-end" data-bs-toggle="modal" data-bs-target="#applicantStatusUpdate"> <i class="fas fa-pencil-alt"></i> </a> {% include 'recruitment/applicant_status_edit.html' %} </div> </div> <div class="row"> <div class="col-xl-6"> <ul class="personal-info"> <li> <h6>Notes</h6> <div>{{ status.notes|safe }}</div> </li> </ul> </div> </div> </div> </div> {% endfor %} applicant_status_create.html <div class="modal fade" id="applicantStatusCreate" tabindex="-1" role="dialog"> <div class="modal-dialog modal-dialog-centered"> <form method="post" action="{% url 'recruitment:applicant_status_create' %}"> {% csrf_token %} {{ form.media }} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Add Applicant Status</h5> <button type="button" … -
drf-yasg hide title property
So as shown in the image, is there any way to hide the 'title' property foreach item? I don't really see the purpose of these titles. -
Django+gunicorn+nginx upload large file connection reset error
I am trying to upload a large file (approx 4GB) to my django website. I use the regular file upload method described in the django docs. I am serving the website with Nginx -> Gunicorn -> Django on EC2 instance. Problem Uploading till 1GB files works fine. It works fine for smaller files but when I try to upload a file of 2GB or more I get a connect reset error in chrome. Logs & specs There are nothing informative in logs I can find. Versions: Django==3.2.4 Nginx==1.20 Config snippet: nginx.conf: ( in the http block) client_max_body_size 4G; client_body_buffer_size 4096M; client_body_timeout 300; Am I missing any django configuration? Hope somebody is able to shed some light on the cause and fix. Thanks for your time. -
Dependent/Chained Dropdown List with Django not working
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. I follow the Article (https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html) but not working. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. Because he cannot find me gruppo_single and therefore does not start the rescue if 'gruppo_single' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) print("<----------ciao sono qui ------>", gruppo_id) self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id) except (ValueError, TypeError): pass else: print("<----------errore ------>") models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda … -
How to update user status (multiple user at a time used checkall ids)?
my concern is user is selecting all id's and update the user status(eg :status='assign')? im getting this url with multiple ids(when i checkall) http://127.0.0.1:9000/assignagent/id/20,21,22,23,24,25,26,27 this is my actual url path('assignagent/id/int:pk',views.SciBulkAssignView.as_view(),name='assignagent') views.py class SciBulkAssignView(UpdateView): login_url = 'login' model = Sci1stKey fields = ['id','projectId','status'] initial = {'status': 'assign'} template_name = 'all_adminhtmlpages/updatesci_details.html' success_url = reverse_lazy('reassigntickets') and another view i tried also # def assignagent(request, id): top = get_object_or_404(Sci1stKey, id=id) top.status ='assign' top.save(update_fields=['status']) return redirect('assigntickets') this is my html and js code im selecting all ids need to update the status of id( checkboxes) <input type="button" class="main" value="selectall" onclick="checkAll()" name="inputs"> <button type="button" value="deselectAll" class="main" onclick="uncheckAll()">Clear</button> <script type="text/javascript"> // Select all check boxes : Setting the checked property to true in checkAll() function function checkAll(){ var items = document.getElementsByName('brand'); var checkedValue = []; for (var i = 0; i < items.length; i++) { if (items[i].type == 'checkbox') items[i].checked = true; checkedValue.push(items[i].value) ; } console.log(checkedValue); url = '/assignagent/id/' + checkedValue; window.location.replace(url); } // Clear all check boxes : Setting the checked property to false in uncheckAll() function function uncheckAll(){ var items = document.getElementsByName('brand'); for (var i = 0; i < items.length; i++) { if (items[i].type == 'checkbox') items[i].checked = false; } } </script> -
How to get and render out foreign key objects depending on a boolean in the base model?
I do have two models with a foreignkey relationship: class Poller(models.Model): """ Main Model to describe Poller objects """ created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(Account, on_delete=models.SET(get_deleted_user)) is_active = models.BooleanField(default=True) headline = models.CharField(max_length=100) class PollerBookmark(models.Model): """ A model that contains bookmarks made to a poller """ poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='PollerBookmark') user = models.ForeignKey(Account, on_delete=models.CASCADE) is_bookmarked = models.BooleanField(default=True) created_on = models.DateTimeField(auto_now_add=True) I now want to render out all Poller objects that have is_bookmarked = True in the PollerBookmarkmodel. # views.py .. poller_bookmarks = PollerBookmark.objects.filter(user__username=username).filter(is_bookmarked=True) context = { 'poller_bookmarks': poller_bookmarks } .. # Template {% for poller_bookmark in poller_bookmarks %} {{ poller_bookmark.poller.headline }} {% endfor %} But the headline isn't rendered out, although the context contains a legit queryset of PollerBookmarks. -
Use one modal for all entries javascript
I'm trying to send the id of the object that we select to edit in the form action. let edit_buttons = document.querySelectorAll(".edit-modal"); for(var i = 0; i < edit_buttons.length; i++) { edit_buttons[i].addEventListener("click", function(e) { console.log(`${this.getAttribute("data-id")}`) console.log(`{% url 'users:edit' pk=1 %}`) document.querySelector("form").setAttribute("action", "{% url 'internal-users:edit-product' pk=${this.getAttribute("data-id")} %}"); }) } {% for object in object_list %} <tr> <td class="border-0 size-13 text-gray-dark">{{object.name}}</td> <td class="border-0 size-13 text-gray-dark">{{object.surname}}</td> <td class="border-0 size-13 text-gray-dark">{{ object.type }}</td> <td class="border-0 size-13 text-gray-dark"> {{ object.status_label }} </td> <td class="border-0 size-13 text-gray-dark"> <button class="btn btn-gray text-gray size-13 edit-modal" data-id="{{ object.pk }}" data-toggle="modal" data-target="#editModal">Edit</button> </td> <td class="border-0 size-13 text-gray-dark"> <button class="btn btn-gray text-gray size-13" onclick="location.href='{% url 'internal-users:products' pk=object.pk %}'">Details</button> </td> </tr> {% endfor %} <form method="POST" action=""> {% csrf_token %} <input type="hidden" id="object_id"> <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content p-4"> <div class="modal-header border-0"> <h5 class="modal-title size-20" id="exampleModalLabel">Edit Product</h5> </div> <div class="modal-body"> <div class="row no-space"> <div class="col-12"> <label>Name</label> <input type="text" name="name" id="name" value="Name" /> </div> </div> <div class="row no-space mt-3"> <div class="col-12"> <label>Status</label> <input type="radio" name="status" id="active" /> <label for="active" class="inline">Active</label> <input type="radio" name="status" id="inactive" class="ms-2" /> <label for="inactive" class="inline">Inactive</label> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-yellow new-button">Save</button> </div> </div> … -
Time difference between extraction of encrypted and unencrypted data
Suppose I have two models class Student(models.Model): name = models.CharField(max_length = 60,blank= False,) subject = models.CharField(max_length = 60,blank=False) marks = models.IntegerField(default =0,blank=True) teacher = models.CharField(max_length = 60,blank=False) and another model class EncryptedStudent(models.Model): name = models.CharField(max_length = 60) subject = pgcrypto.EncryptedCharField(blank=False) marks = pgcrypto.EncryptedIntegerField(default = 0,blank= True) teacher = pgcrypto.EncryptedCharField(blank=False) Now I want to query on the database. Will there be any time difference? How to evaluate for any time difference? I am using pgcrypto module . Here is the github link. -
Django Form 'readonly' widget invalidates 'initial'
In short: I have an app where a user inputs workouts. Before they add exercises to their workout, they must submit a 'readiness' questionnaire with 5-10 questions, rating each low-high. Models: Model with the question set (ReadinessQuestion), and model that stores readiness_question, rating and the Workout it belongs to (WorkoutReadiness). Form: I've made a ModelForm into a formset_factory. When I set the 'readiness_question' form field widget to be 'readonly', this makes my form invalid and ignores my 'initial' data View: I want to create a view where the 5-10 Questions from ReadinessQuestion are in a list, with dropdowns for the Answers. I have set initial data for my form (each different question) the user selects the 'rating' they want for each readiness_question a new Workout is instantiated the WorkoutReadiness is saved, with ForeignKey to the new Workout How my page it looks now (nearly how I want it to look): https://imgur.com/a/HD1l3oe The error on submission of form: Cannot assign "'Sleep'": "WorkoutReadiness.readiness_question" must be a "ReadinessQuestion" instance. The Django documentation is really poor here, widget=forms.TextInput(attrs={'readonly':'readonly'}) isn't even on the official Django site. If I don't make the readiness_question 'readonly', the user has dropdowns which they can change. #models.py class Workout(models.Model): user … -
store API data to the database in Django [closed]
I'm trying to save the retrieve API data from the endpoint to the database in Django but I'm getting as error as TypeError at / string indices must be integers when I print the API data it shows "class" Views.py def homeview(request): userb = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() if request.method == 'POST': userb = Userbase() userb.company_code = request.POST.get('company_code') userb.Area = request.POST.get('area') userb.country = request.POST.get('country') # userb.Netdue_Date = request.POST.get('datefilter') userb.From_Date = request.POST.get('from_Date') userb.To_Date = request.POST.get('to_Date') userb.Predicted_Paid_days = request.POST.get('Predicted_Paid_days') userb.PBK_Desc = request.POST.get('PBK_Desc') userb.Vendor_Name = request.POST.get('Vendor_Name') userb.Reference = request.POST.get('Reference') userb.Payment_Term = request.POST.get('Payment_Term') userb.save() print(type(table_data)) data = json.dumps(table_data) print(data) new_data={ "stage" : data["stage"], "region" : data["region"], "area" : data["area"] } user = Userbase.objects.create( **new_data) user.save() return render(request, 'home.html', {'userb':userb,'table_data':table_data}) API data: [{'id': 163, 'stage': 'stage1', 'region': 'NORTHAMERICA', 'area': 'US'}] -
Django Model Admin
How I can display in the Model Admin only the login user and not all Users? Models.py user = models.ForeignKey(User,db_column="user",null = True, on_delete = models.SET_NULL) Admin.py def get_queryset(self, request): qs = super(Museum_ItemAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) The problem is when logging in as "Peter" I can see and manage all users. The question is how I can see only Peter and not be able to see or change any other users? Thanks a lot in advance