Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django; Cannot upload image and form data is invalid
I'm new to django and I am practicing with it now. I am creating image uploading system, but I cannot upload image uisng form even though I can post and save data through admin. Here is my code. models.py class Item(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='item', max_length=255) price = models.DecimalField(max_digits=4, decimal_places=1) description = models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=models.CASCADE) forms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['title', 'image', 'price', 'description'] widgets = {'text': forms.Textarea(attrs={'cols': 80})} views.py def sell_item(request): if request.method != 'POST': form = ItemForm() else: form = ItemForm(data=request.POST) if not form.is_valid(): raise ValueError('invalid form') new_item = form.save(commit=False) new_item.user = request.user new_item.save() return HttpResponseRedirect('mainapp:index') return render(request, 'mainapp/sell.html', {'form': form}) here is html code of the part. <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <br /> <button type="submit" class="btn btn-success">submit</button> </form> When I fill out the data and submit them, it raises ValueError. form looks good so I guess there is a problem with how to save the image data or html code but I cannot understande how to fix this. Please help. -
Django admin to add fields automatically from javascript function
I have a signup form that works great. One feature of it is users can press "Add more +" and have more identical "instrument" and "level" select fields created. The django admin only shows the first "instrument"/"level" data and not the further ones created from the javascript function. How can I adjust my django admin model to create further fields when the javascript function is called? I appreciate any help I get. HTML <!-- Instrument Exp. --> <div> <label>What instruments do you want to teach?</label> <div class="items"> <div class="form-inline justify-content-center" id="ins"> <!-- Instrument 1 --> <div> {{ form.instrument }} </div> <!-- Level 1 --> <div> {{ form.level }} </div> </div> </div> <!-- Add More --> <div class="text-center" id="add_more"> <button type="button" class="no_link" onclick="add_instrument()">Add more +</button> </div> </div> Javascript var i = 0; var original = document.getElementById('ins'); function add_instrument() { var clone = original.cloneNode(true); clone.id = "ins" + ++i; original.parentNode.appendChild(clone); } admin.py fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name', 'avatar', 'country', 'child_first_name')}), ('Experience', {'fields': ('instrument', 'level')}), ('Permissions', {'fields': ('student', 'parent', 'teacher', 'admin', 'staff', 'active')}), ) -
django vue js & Highcharts asynchronously fetching data from JSON
I'm currently Using django,highcharts, and JQuery to build a simple data visualization web app. I just moved from JQuery to Vue Js and I'm confused on how vue js to fetch JSON data from certain url. Here is my code: Template <!doctype html> <html> <head> <meta charset="utf-8"> <title>Django Highcharts Example</title> </head> <body> <div id="container" data-url="{% url 'async_chart_data' %}"></div> <script src="https://code.highcharts.com/highcharts.src.js"></script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $.ajax({ url: $("#container").attr("data-url"), dataType: 'json', success: function (data) { Highcharts.chart("container", data); } }); </script> </body> </html> Views.py def chart_view(request): return render(request,'chart.html') def chart_data(request): dataset = Passenger.objects.values('embarked')\ .exclude(embarked='')\ .annotate(total=Count('embarked'))\ .order_by('embarked') port_name = dict() for choices_tuple in Passenger.PORT_CHOICES: port_name[choices_tuple[0]] = choices_tuple[1] #Hicharts visualization config pie_chart = { 'chart' : {'type':'pie'}, 'title' : {'text' : 'PELABUHAN'}, 'series': [{ 'name' : 'Tempat Berangkat', 'data' : list(map(lambda row: {'name' : port_name[row['embarked']], 'y' : row['total']},dataset)) }] } return JsonResponse(pie_chart) Models.py from django.db import models class Passenger(models.Model): MALE = 'M' FEMALE = 'F' SEX_CHOICES = ( (MALE, 'male'), (FEMALE, 'female') ) CHERBOURG = 'C' QUEENSTOWN = 'Q' SOUTHAMPTON = 'S' PORT_CHOICES = ( (CHERBOURG, 'Cherbourg'), (QUEENSTOWN, 'Queenstown'), (SOUTHAMPTON, 'Southampton'), ) name = models.CharField(max_length=100, blank=True) sex = models.CharField(max_length=1, choices=SEX_CHOICES) survived = models.BooleanField() age = models.FloatField(null=True) ticket_class = models.PositiveSmallIntegerField() embarked = models.CharField(max_length=1, choices=PORT_CHOICES) def __str__(self): return … -
Django-sitegate, not sure where to set settings mentioned in documentation
I am trying to install and configure django-sitegate as a simple user registration form, as it fits my requirements perfectly. In the documentation, it mentions: Add the sitegate application to INSTALLED_APPS in your settings file (usually ‘settings.py’). Make sure TEMPLATE_CONTEXT_PROCESSORS in your settings file has django.core.context_processors.request. For Django 1.8+: django.template.context_processors.request should be defined in TEMPLATES/OPTIONS/context_processors. I added sitegate to my installed apps, but I am unsure where to how to set TEMPLATE_CONTEXT_PROCESSORS as this variable is not already in any of my settings files (searched with recursive grep), and I can't find an example on how to set it. As I am on django 1.1.13, the part about defining django.template.context_processors.request would apply to me, but I also can't find anythong on how to do that. The file at TEMPLATES/OPTIONS/context_processors does not exist, and other files I found called context_processors were all different from each other and overwhelming. How can I find more information to explain the staps in the sitegate documentation more clearly, or what would be the best way to approach this problem? -
Self-referential aggregation in django
Is it possible to write a self-referential aggregation in django? For example, given the following model definition: from django.db import models class Match(models.Model): match_id = models.BigIntegerField(primary_key=True) start_time = models.DateTimeField() league = models.ForeignKey(League, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete.models.CASCADE) I would like to annotate each Match object with the number of prior matches. (And ultimately with other conditions, e.g., prior matches with a given team playing.) My initial thought was something like: from django.db.models import Q, F, Count matches = Match.objects.filter(team__name='xyz') matches.annotate( prior_matches=Count('match_id', filter=( Q(start_time__lt=F('start_time') )) ) Unfortunately, this seems to give prior_matches=0 for all objects. This question suggests following a foreign key and using the reverse relationship, but that seems clumsy, and it's also got two problems: It's not strictly equivalent. For example, the following snippet works, but will do a count of prior matches within a given league rather than overall. I guess you could hack around this by creating a placeholder model which all Match objects have as a foreign key, but that doesn't seem ideal. matches.annotate( prior_matches=Sum(Case( When(start_time__lt=F('league__matches__start_time'), then=1), default=0, output_field=models.IntegerField() )) ) The provided count is relative to all prior matches in the database, not just those in the filtered queryset. For example, the above code finds … -
How to get values from one model to appear in another in Django,
I am new to Django so please be kind -_^. I have two models "cats" and "litters". Litters contain two elements with names. I have a bunch of Cats. I want it so as a user, I can associate any cat with a litter according to the litter names existing in the litter model. How do I make that happen? (I have attempted "one-to-many", "many-to-many" and "reverse relations"...I am NEW to DJANGO so I don't claim that any of those attempts where done correctly. Here is my current models.py ... class Litter(models.Model): name = models.CharField(max_length=255) notes = models.CharField(max_length=2048, blank=True, null=True) created = models.DateTimeField(blank=True, null=True) modified = models.DateTimeField(blank=True, null=True) def save(self, *args, **kwargs): # Save time Litter object modified and created times self.modified = datetime.datetime.now() if not self.created: self.created = datetime.datetime.now() super(Litter, self).save(*args, **kwargs) def __str__(self): return self.name class Cat(models.Model): litter_mates = models.ManyToManyField(Litter) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) MALE = 'M' FEMALE = 'F' CAT_TYPE = ( ('O','Orphan'), ('P','Pregnant'), ('N','Nursing') ) Orphan = 'O' Pregnant = 'P' Nursing = 'N' name = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=True, null=True) reference_id = models.CharField(max_length=255, blank=True, null=True) short_name = models.SlugField(max_length=255, blank=True, null=True, help_text="This name is auto generated from the name and reference … -
Queryset model for logged in user
Is there a way to query a model for a logged in user that will be ever-present throughout their session? In other words, I want to show model details to a user on every page that requires authentication without having to repeat the queryset on every view and repeat the template language in every template. Pretty much how you can access user attributes like first and last name throughout an authenticated session; I want to do the same for a model or two. -
Async Object is not iterable. Issue with Django 2.0.3, OpenCV and Celery
My problem statement is as follows: I need to capture live video feed and detect faces out of it. I am using dlib library currently to do it. I have written a view in Django which when called captures the frame and proceed as required. Now I want to automate this task i.e whenever a person walks infront of the frame it should be captured automatically [or maybe I can set a 5 second interval and discard the frame if not recognized] For this I tried to implement celery and rabbitmq Here's my view : Views.py import detect as dt def capture(request): user_context = {} try: p = dt.delay() id_of_the_person, face_crop = p cv2.imwrite('/some_path/.media/image.jpg', face_crop) face_addition_object = FaceAddition.objects.get(id_of_the_person=id_of_the_person) if face_addition_object is None: face_addition_object = None obj_live_feed = LiveImagesCaptured.objects.create(live_image_captured=File( open('/some_path/.media/image.jpg', 'rb')), addfaces_entry=None) # noqa obj_live_feed[0].save() else: obj_live_feed = LiveImagesCaptured.objects.create(live_image_captured=File( open('/some_path/.media/image.jpg', 'rb')), addfaces_entry=face_addition_object), obj_live_feed[0].save() except: # noqa pass image_live_qs = LiveImagesCaptured.objects.filter(created_at__lte=datetime.now()).order_by('-created_at')[:10] user_context['images_object'] = image_live_qs return render(request, 'base.html', user_context) I am importing dt.delay() from another file called tasks.py @shared_task def detect(): img = cam.frame bbs = dlib_detector(img) for bb in bbs: h_face = bb.bottom() - bb.top() w_face = bb.right() - bb.left() if h_face > 150 and w_face > 150: shape = sp(img, bb) … -
how pass user id from view to Form's init method?
I have reviewed many questions/answers for hours and applied many techniques but I couldn't pass the user id to the form init() method, it always gives errors like "init() got an unexpected keyword argument 'request'". Anyone knows the reason? Form: class ChildChoreForm(ModelForm): class Meta: model = ChildChore exclude = ('child',) fields = '__all__' def __init__(self, , *args, **kwargs): self.request = kwargs.pop('request', None) super(ChildChoreForm, self).__init__(*args, **kwargs) self.fields['chore'].queryset = Chore.objects.filter(created_by=self.request.user) View: class ChildChoreUpdate(UpdateView): model = Child success_url = reverse_lazy('children-list') form_class = ChildChoreFormSet def get_form_kwargs(self): kwargs = super().get_form_kwargs() if hasattr(self, 'object'): kwargs.update({'request': self.request}) return kwargs -
Allow "ObjectCreated" event notification from my zappa app
I'm creating a zappa app so I can perform a lambda function when an object is created in my S3 bucket. At the moment, when trying to update my zappa app via zappa update dev I get this error: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the GetBucketNotification operation: Access Denied I've configured my AWS credentials on my Mac system so I assume the error is from my Bucket policy not allowing this event notification. Here's my bucket policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "Allow All", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::****-bucket/*" }, { "Sid": "Deny All Actions On All But Media and Static Unless Defined User", "Effect": "Deny", "NotPrincipal": { "AWS": "arn:aws:iam::***********:root" }, "Action": "s3:*", "NotResource": [ "arn:aws:s3:::****-bucket/media/*", "arn:aws:s3:::****-bucket/static/*", "arn:aws:s3:::****-bucket/media_thumbnail/*" ] } ] } Any my CORS config: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Here is my zappa_settings.json: { "dev": { "aws_region": "us-east-2", "django_settings": "zappatest.settings", "profile_name": "default", "project_name": "zappatest", "runtime": "python3.6", "s3_bucket": "zappa-*******", "vpc_config" : { "SubnetIds": [ "subnet-******", "subnet-*******", "subnet-*******" ], "SecurityGroupIds": [ "sg-******" ] }, "events": [{ "function": "zappatest.lambda_function", "event_source": { "arn": "arn:aws:s3:::*****-bucket/media/", "events": [ "s3:ObjectCreated:*" ] } }] } } Is the … -
Paho-mqtt client on Django
Good morning everyone I need a guide on how to configure an mqtt subscriber in a Django app and thus receive messages from CloudMQTT. I try to make a prototype IoT of low energy consumption, for the measurement of temperature and humidity. If someone can refer me to a project with which I can be guided, it would be very helpful. -
Form.cleaned_data ignores select field in Django
I'm building a registration form in Django 2.0 but form.is_valid() never evaluates to True since apparently the areas multiple selection form field throws a 'field is required' error despite one or more options being selected and I'm struggling to figure out why. Here are some relevant code snippets: models.py class Area(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey('self', null=True, default=None, on_delete=models.SET_NULL) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) headline = models.CharField(max_length=120) slug = models.SlugField(max_length=150, unique=True) bio = models.TextField(max_length=1000) areas = models.ManyToManyField(Area) activities = models.ManyToManyField(Activity) rate = models.CharField(max_length=25) status = models.CharField(max_length=2, default='IN') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) forms.py class RegisterForm(ModelForm): class Meta: model = Profile fields = ['headline', 'bio', 'areas'] views.py @login_required @user_passes_test(account_is_verified, login_url='verify_account', redirect_field_name=None) def register(request): if request.method == 'POST': form = RegisterForm(request.POST) areas = form.cleaned_data.get('id_areas') if form.is_valid(): return HttpResponse("Form is valid.") else: context = {'form': form, 'areas': Area.objects.all().order_by('name').filter(status=1), 'error': True} return render(request, 'register.html', context) else: form = RegisterForm() context = {'form': form, 'areas': Area.objects.all().order_by('name').filter(status=1)} return render(request, 'register.html', context) register.html template <form method="post"> <div class="form-body"> <span class="form-heading font-weight-bold">{% trans 'Register' %}</span> {% csrf_token %} <div class="fieldWrapper"> <label for="{{ form.areas.id_for_label }}" class="form-label">{% trans 'Select one or more areas' %}</label> <select id="{{ form.areas.id_for_label }}" name="{{ form.areas.id_for_label }}" class="form-control form-field" multiple="multiple" autofocus> {% for … -
Django form not displaying Datepicker and Timepicker
Hi Djangonauts, I am new to Django. Please forgive any mistakes in code or logic. I am using django-bootstrap-datepicker-plus from the below repository to add a datepicker to my code. https://github.com/monim67/django-bootstrap-datepicker-plus. I have done a pip install. I have done pip install django-bootstrap-datepicker-plus. I have added this in my settings INSTALLED_APPS = [ 'bootstrap_datepicker_plus', ] also added BOOTSTRAP4 = { 'include_jquery': True, } However it is not working. I have all my code below. I am also not able to add DecimalField and IntegerField in my form as that gives errors. But right now I am more focused on the Datepicker. I have attached images of how it should display and how it is displaying. What am I doing wrong here Forms.py from django import forms from .models import Event from bootstrap_datepicker_plus import DatePickerInput, TimePickerInput class EventForm(forms.ModelForm): class Meta: model = Event fields = ('price', 'stock', 'date', 'time_from', 'time_to', 'event_choice') widgets = { 'price': forms.NumberInput(), # I want to add forms.DecimalFied but it gives me a 'DecimalField' object has no attribute 'attrs' error 'stock': forms.NumberInput(), # I want to add forms.IntegerField but it gives me a 'IntegerField' object has no attribute 'attrs' error 'date': DatePickerInput(attrs={'class': 'datepicker'}),# This datepicker is not … -
Retrieving a Django model with only a subset of related objects
I'm attempting to retrieve a specific Django model with only a subset of its related objects that match a certain criteria. For example, I want to get a specific Restaurant, and return all of the Pizzas served at this restaurant that are vegetarian. For example, if I have a Restaurant named Papa's Pizza that serves some pizza. Let's say I have a Pizza model like this: class Pizza(models.Model): ... type = models.CharField(...) restaurant = models.ForeignKey('Restaurant', related_name='pizzas_offered') ... And Papa's Pizza offers the following Pizzas: Margherita (type='vegetarian') Pepperoni (type='carnivore') Pineapple-Only (type='vegetarian) I'd like to retrieve the Papa's Pizza model with only the Margherita and Pineapple-Only pizzas in the pizzas_offered field. How would I go about accomplishing this? If it helps at all, I'm also using Django Rest Framework, so if you have any experience with that and the functionality might exist in a Serializer rather than in the model, that will work too. Thank you very much! -
How can I display an auto-scrolling window of real-time data on my HTML page?
I have a very simple view like this; index.html <body> <div id="liveFeed"> </div> </body> views.py def index(request): return render(request, 'index.html') Additionally, I have another process running which is writing lines to a named pipe (let's call it /var/run/fifo), something like this; producer.sh #!/bin/bash count=1 mkfifo /var/run/fifo while true do echo "test line $count" > /var/run/fifo count=$((count + 1)) sleep 1 done While "producer.sh" is running, I can watch what it's writing to the pipe by doing something like this; $> while true; do cat /var/run/fifo; done test line 1 test line 2 test line 3 test line 4 test line 5 However, instead of reading from the pipe and just printing it out, I'd like to somehow send this output to the "liveFeed" div in index.html, have it show only the most recent N lines at once, and automatically scroll up to hide old entries and show new ones, all without refreshing the page. I just want the "liveFeed" div to update whenever "producer.sh" writes to the pipe. I know that's probably a very broad question-- I'm just not really sure where to start here. What's the right approach to make something like this work? -
`{% include "blah.html" with x="..." only %}` with default value for x
In a template, I am using an include like this: {% include "blah.html" with x="..." only %} and I can use x in blah.html. Now, I would like blah.html to set a default value for x if it is not passed by the "parent" template: {% include "blah.html" only %} Since there is apparently no builtin template tag to set a variable in a template, I don't know how this could be achieved... -
Django: 500 Internal Server Error When Deploying to Heroku (UncompressableFileError)
On Heroku, when DEBUGE is set to False, I get a 500 Internal Server Error. UncompressableFileError at / 'stylesheets/bootstrap.2cf288023762.scss' could not be found in the COMPRESS_ROOT '/static/artist_notify/sass' or with staticfiles. Request Method: GET Request URL: http://domain.io/ Django Version: 1.11.6 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.5 Python Path: ['/app', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages', '/app'] Server time: Sat, 23 Jun 2018 22:25:22 +0300 Installed Applications: ['core', 'accounts', 'notifications', 'faq', 'tinymce', 'dal', 'dal_select2', 'registration', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'django_extensions', 'compressor', 'widget_tweaks', 'crispy_forms', 'channels'] I have removed DISABLE_COLLECTSTATIC from my config vars, and have also added the WhiteNoise Middleware as per other threads. However it doesn't help. -
Django clean's ValidationError not showing when form.is_valid() called
I'm trying to show my ValidationError from clean_MY_VALUE in the template. template <form action="{% url 'MY_VIEW_CLASS' MY_ARG %}" method="POST">{% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> {{ form.errors }} {{ form.non_field_errors }} views.py def MY_VIEW_CLASS(request, MY_ARG): MY_ARG = "query to check for silly conditions" if request.method=='POST': form = MY_FORM(request.POST) if form.is_valid(): MY_VALUE = form.cleaned_data['MY_VALUE'] # do more stuff forms.py class MY_FORM(forms.Form): MY_VALUE = forms.CharField( required = True, max_length = 70, ) def __init__(self, *args, **kwargs): self.MY_ARG = kwargs.pop('MY_ARG', None) super(MY_FORM, self).__init__(*args, **kwargs) def clean_MY_VALUE(self): data = self.cleaned_data['MY_VALUE'] MY_ARG = self.MY_ARG if MY_VALUE and MY_ARG == True: raise ValidationError("this is the error message.") if any(self.errors): return self.errors # return the cleaned data return data Debug What's weird is that when I debug, I cannot see the ValidationError I just created in errors. (Pdb) raise forms.ValidationError("That is causing an error.") *** django.core.exceptions.ValidationError: ['That is causing an error.'] (Pdb) self.errors {} -
How to use clever_selects Django?
I would to do chained list using clever_selects in Django, my form is the following region_granularity = ChoiceField(choices=[('', _(u'Select a gender'))] + list(REGION)) choices_region = ChainedChoiceField(parent_field='region_granularity', ajax_url=reverse_lazy('ajax_chained_names'), empty_label=_(u'Select name')) my views : def kpi(request): if not request.user.is_authenticated: return redirect("login") form = KPIViewForm(request.POST or None) if form.is_valid(): region_granularity = int(form.cleaned_data['region_granularity']) choices_region = int(form.cleaned_data['choices_region']) return render(request, 'app1/kpi.html', locals()) else: request1 = request.POST print (form.errors, len(form.errors)) return render(request, 'app1/kpi.html', locals()) When I put {{ form.choices_region }} in the template, I have this error render() got an unexpected keyword argument 'choices' in this line. Any hepl please !! it's urgent -
Django throws error: '_io.BytesIO' object has no attribute 'name'
CODE: user_photo = UserPhoto.objects.get(user=request.user) data = request.FILES['file_300'] input_file = BytesIO(data.read()) image_open = Image.open(input_file) image_crop = image_open.crop((1, 1, 200, 200)) image_resize = image_crop.resize((300, 300), Image.ANTIALIAS) image_file = BytesIO() image_resize.save(image_file, 'JPEG') data.file = image_file user_photo.file_300 = data user_photo.save() Traceback: Traceback (most recent call last): ... some lines removed ... File "D:\pythonDev\project\upward\chatkaboo\authapp\ajax_views.py", line 256, in upload_user_photo user_photo.save() ... some lines removed ... File "D:\pythonDev\interpreters\forMultichat\lib\site-packages\django\core\files\uploadedfile.py", line 67, in temporary_file_path return self.file.name AttributeError: '_io.BytesIO' object has no attribute 'name' This code is that crops requested image file and save the image file. This code works well when file is: https://drive.google.com/open?id=1cc5_mOjqfOx6vvfR1yEEpxWH6YmdaX-m But It throws above traceback when file is: https://drive.google.com/open?id=1pyeK9kcqQ_oOObX82gZCtC7HHng4YSNN Question: How can I fix it? Is there are difference between my above two image files? -
Djngo admin inline through one to one field
Item has foreign key to User and User has OneToOne to Profile. I have admin for Profile. How can I show all items as inlines? I do not have foreign key from Profile to Item, so I need something like user__itemset but it seems it can't be used in Django admin. -
django/jquery: is SortElements Jquery plugin discontinued?
I am trying to sort my table differently when I click on different table headers. this is my table: <table class="table display table-striped table-bordered" id="employee-table" cellspacing="0"> <thead> <tr> <th id="id_header">ID</th> <th id="name_header">Name</th> <th id="job_title_header">Job Title</th> <th id="years_experience_header">Years Experience</th> <th id="department_header">department</th> </tr> </thead> <tbody id="table-body"> {# we use a partial here because the list of employees is going to be used again in the employee_create function #} {% include 'employees/partial_employee_list.html' %} </tbody> </table> this is the partial_employee_list.html {% for worker in workers %} <tr class='workerRow'> <td>{{ worker.id }}</td> <td>{{ worker.name }}</td> <td>{{ worker.job_title }}</td> <td>{{ worker.years_experience }}</td> <td>{{ worker.department }}</td> <td> <button type="button" class="btn btn-warning btn-sm js-update-employee" data-url="{% url 'employee_update' worker.id %}"> <span class="glyphicon glyphicon-pencil"></span> Edit </button> </td> <td> <button type="button" class="btn btn-danger btn-sm js-delete-employee" data-url="{% url 'employee_delete' worker.id %}"> <span class="glyphicon glyphicon-trash"></span> Delete </button> </td> </tr> {% empty %} <tr> <td colspan="7" class="text-center bg-warning">No Employees</td> </tr> {% endfor %} this is the javascript function: var table = $('#employee-table'); $('#id_header, #name_header, #job_title_header, #years_experience_header, #department_header') .wrapInner('<span title="sort this column"/>') .each(function(){ var th = $(this), thIndex = th.index(), inverse = false; th.click(function(){ table.find('td').filter(function(){ return $(this).index() === thIndex; }) .sortElements(function(a, b){ return $.text([a]) > $.text([b]) ? inverse ? -1 : 1 : inverse ? … -
Django and ChartJS
I'm trying to understand if it it's possible to incorporate dynamic data into a Django Chart JS architecture. I went through a couple of tutorials and ultimately got Django to work with ChartJS and it's very good when I'm able to hard code values and then display the related graphs. What I'm ultimately trying to do is this same exercise with dynamic data from my database. I found this identical question in SO, https://stackoverflow.com/questions/47575896/dynamic-chart-using-django-and-chart-js#= but it wasn't answered by anyone. This is exactly what I'm trying to achieve. I've explore serializers a bit, do I need to serialize the data first? Thanks in advance for your thoughts and feedback. -
Django filter and select date only from datetime
Here is my code on clicking post button on form new_date = request.POST.get('depart_date') from datetime import date c = Schedule.objects.filter(bus_id=request.POST.get('bus'), depart_time__date=date.new_date).count() print(request, c) In my select query, I want to check depart time of selected bus from datetime field. But on checking this, I need to select date only to filter with new_date. On submitting my form, django error show as follows; type object 'datetime.date' has no attribute 'new_date' -
How to change the default time format in django models
I have a DateTimeField with auto_now_add=True and everything work except when i try to use that date in a template i get a date which is in the format of 'June 23, 2018, 4:33 p.m.' but the date that I need should be formatted like this DD-MM-YY / hh:mm. Any suggestions ?