Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need query to return all document that contains a specific string in list
I need to perform a django query to return all document that contains a specific string in list, and this list is stored in dict. The filed is dict and each key in the dictionary contain a list type.. This sample of my document: { "collector_id" : 80, "market_info" : { "market_name_list" : [ "amazon", "souq" ], "key_2" : [ "item1_in_list" "item2_in_list" "item3_in_list" ] } } market_info is DictField. I tried a lot of query but all of them failed. query_set = myModel.objects.filter(market_info__contains= {'market_name_list': ['amazon']}) -
Ajax POST method to Django. Always results in "Not Ajax"
I have been trying to create an AJAX function which sends two JS variables, Score and Mistake, back to the Django backend and to update an extended user model with them. To do this I started with an AJAX function which looks like this: $(document).ready(function() { $("#test").submit(function(event){ event.preventDefault(); console.log("form submitted!"); $.ajax({ type:"POST", url:"/update/quiz/", data: { csrfmiddlewaretoken: window.CSRF_TOKEN, 'score': score, 'mistake' : mistake }, success: function(){ $('#message').html("<h2>Contact Form Submitted!</h2>") } }); return false; }); }); Views.py class Quiz(TemplateView): template_name='quiz.html' def post(self, request, *args, **kwargs): if request.is_ajax(): message = "Yes, Ajax!" else: message = "Not Ajax!" return HttpResponse(message) URLS.py from django.urls import path from home.views import HomepageName, Homepage, Quiz from . import views urlpatterns = [ path('quiz/', Quiz.as_view()), path('update/quiz/', Quiz.post), path('<slug:slug>/', HomepageName.as_view()), path('', Homepage.as_view()), ] And the template <form method='POST' id ='test'> {% csrf_token %} <input type='submit' value='Test button'/> <div id = 'message'>Initial text</div> </form> I've already tried to move around the URL routing and add a new URL thinking that would work but when the Submit button is clicked then it always loads a new page and then on that page it shows "Not Ajax!" I assume that it is doing the default HTML form action and not the AJAX since … -
How do I import external css and js files when using Django and Vue
I am using Django as API and VueJs frontend. I am using Django Webpack Loader to generate your static bundles without Django's staticfiles or opaque wrappers.. I am trying to convert my html template. What is the best approach to use external css and js files. <html lang="en"> <head> <meta charset="utf-8"/> <meta http-equiv="x-ua-compatible" content="ie=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <title>In plain Vue</title> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> </head> <body class="body-bg-white"> {% load render_bundle from webpack_loader %} <div id="app"> <app> </app> </div> {% render_bundle 'main' %} <script src="{% static 'js/jquery-3.2.1.js' %}"></script> </body> </html> How do i get this css and js file included in my webpack ? Thanks -
Add XML option to Export option on Django Admin
So am using Django Admin to export various models in different formats using the Django-import-export package. The only option that is missing is XML. Is there a way to add an XML option? Any guidance would be appreciated! Attached you will find a screenshot : According to this post XML is possible. -
String comparisson differences between Mysql and Postgres - white spaces, special chars and case
I'm building a Django application, and we decided to move from Mysql to Postgres. Now I'm facing a problem regarding string comparison. In Mysql, 'Área de Assentamento ' equals to (=) 'Area de assentamento', for a varchar(50) with utf8mb4_general_ci encoding field. The same does not apply Postgres. The closer I've reached is using iexact with .strip(). However, for special chars it still misses. I would like that myvar = 'Área de Assentamento ' r = Myobject.objects.get(field__iexact=myvar.strip()) could return a matching result also in postgres for field='Area de assentamento' Is there any way to achieve the same behavior from Mysql in Postgres? -
Django LoginView displays error messages on first page load
Using Django's built-in LoginView, I want to display an error message on incorrect login. However, the error message is displayed when the page first loads before input. In fact, it is always displayed. I want the error message to display only when the user enters invalid login details. urls.py from django.urls import path from django.contrib.auth.views import LoginView urlpatterns = [ path('login/', LoginView.as_view(template_name='login.html'), name="login"), ] login.html {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} <p>{{ error }}</p> {% endfor %} </div> {% endif %} <form method="post" action="{% url 'accounts:login' %}"> {% csrf_token %} <p><input type="text" name="username" autofocus="" required="" id="id_username" placeholder="username"></p> <p><input type="password" name="password" required="" id="id_password" placeholder="password"></p> <button type="submit" value="Login">Login</button> <a id="signup-btn" href="{% url 'accounts:signup' %}"">Don't have an account? Sign up</a> </form> Any help would be greatly appreciated. -
Setting up and deploying Cookiecutter-Django project on Heroku, with Docker
Please don't mark as duplicate. I know there is a similar question here: How to upload and deploy django cookiecutter project, with docker, to heroku? Hi friends! I am about to deploy a Cookiecutter application on Heroku. I am using Docker and git for version control. I am new to Docker and Cookiecutter so I am a bit confused with the documentation. What are the steps to follow? I am looking for some sort of guidance for setting up the environment and how to deploy it. I am pretty sure there is more to it then just following the git commands here, or is that enough? How to upload and deploy django cookiecutter project, with docker, to heroku? Or shall I just start here: https://cookiecutter-django.readthedocs.io/en/latest/deployment-on-heroku.html Any help would be very much appreciated... -
JSONDecodeError exception is generated only after reload Apache
I'm using django-fixture-magic to build a fixture file. My code calls merge-fixture to build that fixture out of a bunch of json files. The code generates a StopIteration exception only after reloading apache, with error: JSONDecodeError at <url> Expecting value: line 1 column 1 (char 0) In django-fixture-magic script, all files are read in a loop that calls json.loads(file.read()), and in decoder.py from python json library, the exception occurs. Debugging with some sys.stderr.write() I see that this exception occurs randomly in a specified file, that can change in every run. What is difficult to understand is that the problem does not happen after make a second request, and in others. Only when reloading apache. If it helps, follow the Apache config file: <VirtualHost *:443> ServerName <url> ServerAlias <url> WSGIProcessGroup nes DocumentRoot path/to/documentroot <Directory /> Options FollowSymLinks AllowOverride None </Directory> Alias /media/ path/to/media <Directory "path/to/directory"> Require all granted </Directory> SSLEngine on SSLCertificateFile /etc/apache2/ssl/wildcard.numec.prp.usp.cer SSLCertificateKeyFile /etc/ssl/private/wildcard.numec.prp.usp.key SSLCertificateChainFile /etc/apache2/ssl/ChainICPEDU.pem WSGIScriptAlias / path/to/wsgi.py application-group=%{GLOBAL} #WSGIDaemonProcess nes lang='en_US.UTF-8' locale='en_US.UTF-8' python-home=path/to/project Alias /static/ path/to/static ErrorLog ${APACHE_LOG_DIR}/nes/ssl_error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/nes/ssl_access.log combined I think it could be an Apache configuration issue, because the problem only occurs after reloading it, and not for following requests. To confirm that … -
How to access Django Model Instance's "absolute_url" in a Python function through a Queryset
How to access the value / string , from defined method - get_absolute_url , through a Django ORM Queryset , within a python function within the views.py . def get_absolute_url(self): """Returns the url to access a particular instance of the model.""" return reverse('model-detail-view', args=[str(self.id)]) Code above is a sample from the Mozilla developer Network . How to access - model-detail-view , for each instance of the model within below mentioned Queryset. The code i have below doesn't give any results , rather the ERROR == queryset = myModel.objects.get_absolute_url() AttributeError: 'Manager' object has no attribute 'get_absolute_url' Second try with the return value of the reverse method also fails with similar AttributeError. queryset = myModel.objects.model-detail-view() AttributeError: 'Manager' object has no attribute 'model-detail-view' Wanted to get individual - "model-detail-view" , strings and pass them to dataTable.js as part of a python DF , further passed on as JSON . -
serialization is not work properly in lower levels- django-rest-framework
my Comment model is like below: class Comment(models.Model): user = models.ForeignKey(User) content = models.TextField() parent = models.ForeignKey('self', related_name='answers') I want to serializer comment and all of its answers. So i've wrote this serializer: class CommentSerializer(ModelSerializer): user = UserSerializer(fields=('get_full_name',), allow_null=True) class Meta: model = Comment fields = ['user', 'content', 'answers'] depth = 10 now when I serialize a comment by this serializer, it works properly just for level 1 of the comment. the answers object shows all the data, such as user's password! or it shows 'parent' while I didn't include parent to the fields of Meta class of the serializer. the following is the output of this serializer: { "data": { "pk": 15, "user": null, "name": "rwqerweqr", "email": null, "content": "A", "approved": false, "created_at": "2019-03-31T23:16:44.980338+04:30", "answers": [ { "id": 14, "content": "B", "name": null, "email": null, "approved": false, "created_at": "2019-03-31T23:08:13.374350+04:30", "user": { "id": 3, "is_superuser": true, "email": "email@gmail.com", "phone": "+111111111111", "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=", "first_name": "Alex", "last_name": "Doe", "created_at": "2019-03-26T21:16:53.818407+04:30", "last_login": "2019-03-26T21:17:14.987512+04:30", "is_active": true, "is_staff": true, "groups": [], "user_permissions": [] }, "parent": { "id": 15, "content": "A", "name": "rwqerweqr", "email": null, "approved": false, "created_at": "2019-03-31T23:16:44.980338+04:30", "user": null, "parent": { "id": 13, "content": "C", "name": null, "email": null, "approved": false, "created_at": "2019-03-31T21:27:29.152248+04:30", "user": … -
Django, Celery: Retrieving a file generated asynchronously
I have a page (foo.com/process) where you can generate reports for data. Sometimes the amount of data that needs to be generated is large, so it takes a while. Thus I made a Celery task to handle the PDF generation side of things. The reports are generated when clicking on a PDF image: <i data-processid="{{process.id}}" data-filename="{{process.pdf}}" class="fas fa-file-download getPdf"></i> When you click on that FA icon, an AJAX POST request is sent to the Django view: $(".getPdf").on('click', function(event) { var thisId = $(this).data('processid'); var filename = $(this).data('filename'); $.post({ url: "{% url 'process' %}", // Points to foo.com/process data: { csrfmiddlewaretoken: "{{ csrf_token }}", id: thisId }, success: function(data) { ... handle sucess }, error: function(data) { ... handle error }, traditional: true }).done(); downloadPdf(filename); function downloadPdf(filename) { setTimeout(function() { window.location.href = filename; }, 10000); }; }); The AJAX function sends the request to the backend to start the Celery process to generate the PDF, and then immediately calls a downloadPfd function, which is simply a delayed function set to (what I thought was) the way to download a file through JavaScript. The timeout time is enough for the file to be generated. I'm getting a file not found, even though … -
Django Rest API image GET error (django.views.static.serve)
Here is my image api link : https://krisi-doctor.herokuapp.com/api/image/ when i post image file it successfully upload . when i try to check 4/5 hours later or do any change to heroku and try to check image at https://krisi-doctor.herokuapp.com/media/images/ it shows error . app model.py from django.db import models from krisi_user.models import krisi_user class problem_image(models.Model): full_name = models.CharField(max_length=250) email = models.CharField(max_length=100) image = models.ImageField(upload_to='images/') phone = models.CharField(max_length=50) krisi_user = models.ForeignKey(krisi_user,on_delete= models.CASCADE,null=True) def __str__(self): return self.full_name views.py from django.shortcuts import render from rest_framework import viewsets from .models import problem_image from .serializers import problem_image_serializer class problem_image_view(viewsets.ModelViewSet): queryset = problem_image.objects.all() serializer_class = problem_image_serializer app urls.py from django.urls import path , include from . import views from rest_framework import routers #image_router = routers.DefaultRouter('api/image/v1.0',views.problem_image_view) router = routers.DefaultRouter() router.register('image',views.problem_image_view) urlpatterns = [ path('',include(router.urls)), ] serializers.py from rest_framework import serializers #from rest_framework.exceptions import ValidationError from .models import problem_image class problem_image_serializer(serializers.ModelSerializer): class Meta: model = problem_image fields = ('full_name','email','image','phone') project urls.py from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('krisi_user.urls')), #path('',include('krisi_image_problem.urls')), path('api/', include('krisi_image_problem.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and settings.py """ Django settings for krisi_doctor project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this … -
Show snapshot of articles in news list
I have this news_list.html template which lists all articles in their entirety. Is there any way I can show these articles as a snapshot of the entire article. Ideally I'd like to show a thumbnail sized image, the title and the 1st 50 characters and have the user click into the article to view it all. Can this be done and if so, how? -
Delete table of unmanaged database from Django view
I´m in the need to delete a table from a second unmanaged database (no model representation) from one of my Django views. I´ve registered the second DB in my settings file like: DATABASES = { 'default': { ... }, 'ext_data': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'person_data', 'USER': 'username', 'PASSWORD': 'pass', 'HOST': 'example.com', 'PORT': '5432', } } Now I would use it with connections like (for the sake of simplicity from shell) $ python manage.py shell >>> from django.db import connections >>> conn = connections['ext_data'] >>> print(conn.introspection.table_names()) [u'test-2', u'test'] How would I f.e. drop the table 'test' from here? -
Update elasticsearch index
I am trying to get update my elasticsearch index with any changes in existing database. ie,my elastic search index should get synced with database my sample model.py goes like this # models.py class Car(models.Model): name = models.CharField() color = models.CharField() manufacturer = models.ForeignKey('Manufacturer') cartype =models.ForeignKey('Cartype') class Cartype(models.Model): type = models.CharField() model = models.CharField() class Manufacturer(models.Model): name = models.CharField() country_code = models.CharField(max_length=2) location = models.ForeignKey('Location') class Location(models.Model): country = models.CharField() class Ad(models.Model): title = models.CharField() description = models.TextField() created = models.DateField(auto_now_add=True) modified = models.DateField(auto_now=True) url = models.TextField() car = models.ForeignKey('Car', related_name='ads') from elasticsearch import Elasticsearch from elasticsearch_dsl import Search client = Elasticsearch() my_search = Search(using=client) cjsta = Index(settings.ELASTICSEARCH_INDEX_NAMES[__name__]) # See Elasticsearch Indices API reference for available settings cjsta.settings( number_of_shards=1, number_of_replicas=1 ) logger = logging.getLogger(__name__) @cjsta.doc_type class CarStageDocument(DocType): car = fields.ObjectField(properties={ 'name':fields.StringField(), 'color': fields.StringField(), 'manufacturer':fields.ObjectField(properties={ 'name': fields.IntegerField(), 'country_code': fields.StringField(), 'location': fields.ObjectField(properties={ 'country':fields.StringField(), }) }), 'cartype': fields.ObjectField(properties={ 'type': fields.StringField(), 'model': fields.StringField(), }), }) class Meta: model = Ad related_models = [Car,Cartype,Manufacturer,Location] fields = ['title','description','created','modified','modified','url'] ``` How my get_instances_from_related be like so that if i update type field in Cartype my elaticsearch index will also get updates ie, i should get the updated value of type if i run _search -
Inheritance between 2 django classes
I would like to inherite method from a first class to a second one separated in two different files. I'm getting a little issue according to arguments given in my method. I have a file named : main.py class CustomCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): template_name = '...' model = ... def get_context_data(self, **kwargs): """ Update the context data with query_string. """ context = super(CustomCreateView, self).get_context_data(**kwargs) context['title'] = _("Add new ") + str(self.model._meta.verbose_name) context['actual_page'] = get_actual_page(self.request) context['actual_search'] = get_actual_search(self.request) context['actual_sort'] = get_actual_sorting(self.request, self.default_sort_params[0]) context['actual_pagination'] = get_pagination(mylist, self.pk) return context def get_actual_page(request): actual_page = request.GET.get('page', None) ... return actual_page def get_actual_sorting(request, default): actual_sorting = request.GET.get('sorting', default) return actual_sorting def get_actual_search(request): q = request.GET.get('q', '') return q def get_pagination(mylist, pk): actual_pagination = [mylist[x:x + settings.PAGE_LIMIT] for x in range(0, len(mylist), settings.PAGE_LIMIT)] ... return actual_pagination And I have another file : views.py class MyFormView(PermissionRequiredMixin, CustomCreateView): def get_context_data(self, **kwargs): context = super(MyFormView, self).get_context_data(**kwargs) page_row_ids = self.request.session.get('result_recordset', []) my_pagination = context['actual_pagination'] actual_pagination, first_page, last_page, page_number = my_pagination(page_row_ids, pk) Question: In my first file, How I can write arguments in context['actual_pagination'] = get_pagination(mylist, self.pk) in order to insert any list when I will call this one ? Thank you very much -
Django Form clean sees Date objects as NoneType. POST method in views.py does see it as a date
So I am currently working on the project in Django. The user should be able to set start date and the end date, based on this set interval an analysis should be calculated. The current problem is, when the data comes to validation, it sees input data as an NoneType. Note: I did not upload the entire html code. Only form relevant code. forms.py from django import forms from tempus_dominus.widgets import DatePicker import datetime class AnalysisInformationForm(forms.Form): start = forms.DateField(help_text="Enter a date between 2019-03-01 and now.", input_formats=["%d/%m/%Y"], widget=DatePicker( options={ 'minDate': '2019-03-01', 'maxDate': datetime.datetime.utcnow().date().strftime("%Y-%m-%d") }) ) end = forms.DateField(help_text="Enter a date between the chosen start date and now", input_formats=["%d/%m/%Y"], widget=DatePicker( options={ 'minDate': '2019-03-01', 'maxDate': datetime.datetime.utcnow().date().strftime("%Y-%m-%d") }) ) def clean(self): cleaned_data = super(AnalysisInformationForm, self).clean() start = cleaned_data.get('start') end = cleaned_data.get('end') print(start, end) if start >= end: raise forms.ValidationError('Invalid dates input. The start day must be set earlier than the end date. ') return cleaned_data views.py def index(request): if request.method == 'POST': form = AnalysisInformationForm(request.POST) if form.is_valid(): pass else: form = AnalysisInformationForm() return render(request, 'stm/index.html', {'form': form}) index.html <head> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css"> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"><link> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> </head> {{ form.media }} <body> <div class="form-group"></div> {% load widget_tweaks %} <form … -
How to work with the formset in CBV at the Django?
I have a form ProductCreateForm. It is necessary to insert the form SpeciallyPriceForm inside it. I have a view for ProductCreateForm. But I don’t know how to process SpeciallyPriceForm in it either. class ProductsCreate(CreateView): model = Product form_class = ProductCreateForm http_method_names = ['get', 'post'] def get_form_kwargs(self): print('form') kwargs = super(ProductsCreate, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def get(self, request, *args, **kwargs): self.object = None ... return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): self.object = None form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): product = form.save(commit=False) product.user = self.request.user product.save() if self.request.is_ajax(): return JsonResponse({'success': True, 'location': location}) else: return redirect(location) def form_invalid(self, form): .... -
I am trying to execute the unix command from Django API python, but getting below Error: after installing Java
checked the installed java version : root@dev# cd /usr/lib/jvm root@dev:/usr/lib/jvm# ls default-java java-1.8.0-openjdk-amd64 java-8-openjdk-amd64 UnixCommand= 'java -cp dataflow-bundled-2.3.0.jar MsSqlMigrator runner=DataflowRunner' command= UnixCommand I have tried to execute either ways : 1) import os process=os.system(command) 2) process= subprocess.Popen(command) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) output = process.communicate() print(process) But showing Error : sh: 1: API/java: not found 32512 Internal Server Error Since I have tried to execute the same command directly in the Unix shell , it's working fine and I have set the Path in /etc/environment file as well : like : which java --> /usr/bin/java update in $JAVA_HOME and added the same in $PATH like export PATH=$PATH:$JAVA_HOME, still showing the same error. Since I have tried to execute the same command directly in the Unix shell , it's working fine and I have set the Path in /etc/environment file as well : like : which java --> /usr/bin/java update in $JAVA_HOME and added the same in $PATH like export PATH=$PATH:$JAVA_HOME, still showing the same error. UnixCommand= 'java -cp dataflow-bundled-2.3.0.jar MsSqlMigrator runner=DataflowRunner' command= UnixCommand I have tried to execute either ways : 1) import os process=os.system(command) 2) process= subprocess.Popen(command) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) output = process.communicate() print(process) Expected … -
show field name with [] icon in django template
Here is my data That I want to show in my django page template <QueryDict: {'department': ['cb6594f8-b7a3-4319-b413-9b5ec8abeebb'], 'icd_code': ['54654ICDCODE'], 'value[]': ['450', '500', '120'], 'page_type': ['abcd'], 'service_code': ['56XRFT'], 'csrfmiddlewaretoken': ['Hpg1qF9w2mP7ikJbj8NLLFcrygWdO9Q429cNKRHkIjm7B67BHOBGCNSR9DiAUAle'], 'billing_code[]': ['78984', 'AWEXZ67', 'POKIJH29'], 'key[]': ['Special', 'AC Room', 'first'], 'package_name': ['e2e9e4d3-0ebb-4343-96e3-710a6904057e']}> let this data is stored in variable name "formdata" Then if I want to show the department then just show using {{formdata.department}} But If I want to show the service_code then code should be Either {{formdata.service_code}} or {{formdata.service_code[]}} Or {% for service_bill in formdata.service_code %} {{service_bill}} {% endfor %} But Unable to show data using any above method Please suggest -
Django: prevent deleting child model unless parent model is deleted
I have 2 models (I left out the __str__ representation for the sake of simplicity). Customer: # models.py class Customer(models.Model): customer_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customer_name = models.CharField(max_length=128) and Device_group: # models.py class Device_group(models.Model): group_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customer_uuid = models.ForeignKey(Customer, on_delete=models.CASCADE) device_group_name = models.CharField(max_length=20) color = models.CharField(max_length=8) is_default = models.BooleanField(default=False) Each Customer can only have 1 Device_group that is default. I want to be able to prevent the default group from being deleted when the Customer still exists. However, when the Customer is deleted, all device groups, including the default group should be deleted. To prevent the default group from being deleted I use the pre_delete signal like this: # signals.py @receiver(pre_delete, sender=Device_group) def protect_default_group(sender, instance, **kwargs): if instance.is_default: raise ProtectedError('The default group cannot be deleted.', instance) This raises a ProtectedError and prevents deletion when the user tries to delete the default group from the Device_group model in Django Admin. To make sure all device groups, including the default group, are deleted upon deletion of the Customer, I tried to use another pre_delete signal to change the is_default field to False and delete the group like this: # signals.py @receiver(pre_delete, sender=Customer) def unprotect_default_group(sender, instance, **kwargs): default_group … -
Get query list parameter from Datatable in Django
I'm using DataTable with django and I'm trying to set up the serverSide option. Everything is working fine except the order parameter. Datatable is sending all the parameters to the backend in which the order comes like this: order[0][column]: 0 order[0][dir]: asc order[1][column]: 2 order[1][dir]: desc I'm trying to get all the order parameters in a list with the getlist() function but I'm getting everytime an empty list orders = request.GET.getlist('order[]') What am I missing? -
How to add Foreign Keys to Django Field History?
I'm trying to track Foreign Keys using django-field-history, but when I add it, it does additional queries on every page using the Model For example from field_history.tracker import FieldHistoryTracker class Author(models.Model): user = models.ForeignKey('auth.user) field_history = FieldHistoryTracker(['user']) will always give more queries on pages using Author, like so SELECT ••• FROM "auth_user" WHERE "auth_user"."id" = '2' 1239 similar queries. Duplicated 1235 times. I've tried using user_id instead of user in Field History Tracker, but it will always return None. Using user.id or anything like it just returns an error. I really need to keep that history data, but not at the cost of thousands of additional queries. Also, would really enjoy keeping django-field-history as my whole DB is using it, but I'm aware I might have to switch package, and if so, which one would you advise ? -
How do implement an import-export csv button to a CRUD table using Class-Based Views?
Basically what the title implies. How do I use Class-based Views to create an import/export button for my CRUD table? Using Function-based Views to do it was difficult enough. How does CBV compare? -
Django Python: Display Different Views for Different User Types by Retrieving Data in Wamp Server
I am newbie and I really need help in this problem. Can someone answer this and teach me how to do it in Django. I want to create a restaurant system which has 4 types of users (admin, customer, kitchen, and cashier) in Django. I already created MySQL user database by using Wamp Server. Meanwhile, I want to create a different views for each users. Is it possible to retrieve the data from MySQL for user login purpose and assign the different views for user login page in Django? I really need the helps. Thank you.