Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django paginator returning same data on seperate pages
Problem: I am developing an application in django that uses paginator for the list page of a model, it is set to display 25 instances of the model per page, when i view the first page everything works fine but when i move to the second page it shows some values from the first again. Details: snips of list for the first and second page First: https://imgur.com/tyY5xu0 Second: https://imgur.com/UcGWEFN (note CO01, 4 and 5 appear again) Views.py: def view_jobs(request): query_results = Job.objects.select_related('contract').order_by('-active', '-order_date') paginate = Paginator(query_results, 25) page_no = request.GET.get('page') page_obj = paginate.get_page(page_no) context = {"query_results": page_obj} return render(request, 'view_jobs.html', context) view_jobs.html: <table id="PageTable" class="table table-striped"> <thead> <tr> <th class="dropdown"> <a class="dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <h6>Number</h6> </a> </th> </tr> </thead> <tbody> {% for item in query_results %} <td> <small>{{ item|filter_prep:"order" }}</small> {% if item.help_text %} <small style="color: grey">{{ item.help_text }}</small> {% endif %} {% for error in item.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </td> </tr> {% endfor %} </tbody> </table> <div class="pagination"> <span class="step-links"> {% if query_results.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ query_results.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ query_results.number }} of {{ query_results.paginator.num_pages }}. </span> {% if query_results.has_next %} <a href="?page={{ … -
create() takes 1 positional argument but 2 were given in python
models.py class UserAttributes(models.Model): airport = models.ForeignKey('airport.Airport', related_name='user_attributes_airport', on_delete=models.SET_NULL, null=True, blank=True) location = PointField(blank=True, null=True) user = models.ForeignKey( 'users.AerosimpleUser', related_name='user_attributes', on_delete=models.CASCADE, null=True, blank=True) views.py class LocationViewSet(viewsets.ModelViewSet): serializer_class=LocationRetrieveSerializer http_method_names = ['get', 'post', 'patch', 'put'] def get_permissions(self): switcher = { 'create': [IsAuthenticated], 'list': [IsAuthenticated], 'retrieve': [IsAuthenticated], 'update': [IsAuthenticated], 'partial_update': [IsAuthenticated], } self.permission_classes = switcher.get(self.action, [IsAdminUser]) return super(self.__class__, self).get_permissions() def get_queryset(self): return UserAttributes.objects.filter( airport__id=self.request.user.aerosimple_user.airport_id).order_by('pk') serializers.py class LocationRetrieveSerializer(serializers.ModelSerializer): class Meta: model = UserAttributes fields = '__all__' def create(self, validated_data): if UserAttributes.objects.filter(user_id=self.context["request"].data['user'],airport_id=self.context["request"].data['airport']).exists(): obj=UserAttributes.objects.get(user_id=self.context["request"].data['user']) obj.location=self.context["request"].data['location'] obj.save() return obj user_attributes = UserAttributes.objects.create(validated_data) return user_attributes what changes should i make -
Serializer create() methods sends 2 queries to DB
I have a serializer class MappingSerializer(ExtendedModelSerializer): default_landing_page_url = serializers.URLField(read_only=True) class Meta: model = models.Mapping fields = ('id', 'name', 'settings', 'campaign','default_landing_page_url') def create(self, validated_data): instance = super().create(validated_data) profile_id = instance.settings.integration.profile_id instance.default_landing_page_url = helpers.get_landing_page_url(profile_id, instance.campaign) instance.save() return instance In this case, there is a 2 queries into db,first when calling super().create(validated_data) and second is instance.save(). How can I avoid doing 2 queries with the same logic. I could add extra field validated["default_landing_page_url"] = helpers.get_landing_page_url(profile_id, instance.campaign) and then call super().create() but in this case I can't reach profile_id, which can be accessible only after instance is created -
Getting invalid Signature in django JSONWebTokenAuthentication for valid token
I keep getting invalid signature [Error 401:Unauthorized] when i try to authenticate user bearer token. My LoginSerializer generates jwt token for me and validates the user but when i try to use that token to access other Api endpoints, i get invalid signature error. UserLoginSerializer.py class UserLoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=255, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): email = data.get("email", None) password = data.get("password", None) user = authenticate(email=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password is not found.' ) try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) update_last_login(None, user) except CustomerUser.DoesNotExist: raise serializers.ValidationError( 'User with given email and password does not exists' ) return { 'email': user.email, 'token': jwt_token } In my settings.py, I set settings for the JWT authentications. JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_SECRET_KEY': 'SECRET_KEY', 'JWT_GET_USER_SECRET_KEY': None, 'JWT_PUBLIC_KEY': None, 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': timedelta(days=30), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': False, 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=30), 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_AUTH_COOKIE': None, } In views.py, I have UserLoginView class to Retrieve user and fetch the token. class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = … -
values from views not getting rendered in HTML page using Django in pycharm IDE
I have copied a project on which I was working on using normal editor to Pycharm IDE so that I can debug further while developing the site. But when I run the project in pycharm, values are not getting rendered in HTML file but was when using editor. In pycharm, I have created venv and installed all the libraries. As a result, website also opens when python manage.py runserver is ran. But the values which I submit in the form, the values are not getting rendered somehow in html page. HTML snippet is given below. <div class="order-1 text-center sticky-top chartbutton border-bottom shadow-sm"> <form action="{% url 'trend' %}" method="post"> {% csrf_token %} {{ new_prodform }} <input type="submit" value="Submit"> </form> </div> <script type="text/javascript" class="var-class"> var prod_name, end_date; prod_name = '{{prod_name}}'; <!-- prod_name value is null here after submit --> end_date = '{{end_date}}'; <!-- end_date value is null here after submit --> </script> <script type="text/javascript" src="{% static 'trend/chart_plot.js' %}"></script> Views.py: if request.method == 'POST': filled_form = ProductForm(request.POST) if filled_form.is_valid(): product = filled_form.cleaned_data['product'] new_spform = ProductForm() prod_milestone = main_query_script(product) #some function to retrieve and return trend details in dict form context_dict.update(sp_milestone) context_dict.update({'new_prodform':new_prodform}) return render(request, 'trend/chart.html', context=context_dict) else: form = ProductForm() context_dict.update({'new_prodform':form}) return render(request, 'trend/chart.html', … -
Can't make migrations to django app after i added a new field to one of the models
So, this was my Category model before: class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title I had run makemigrations and migrate commands and the app was working just fine Then i had to add one more field to the model: class Category(models.Model): restricted = models.BooleanField(default=False) title = models.CharField(max_length=20) def __str__(self): return self.title Now when i run makemigrations, it gives the following error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: events_category first it gave "no such column" error, but i don't really care about the data right now so i deleted the sqlite file and all migrations and started over, that's when this error showed up The model has been set up as a foreign key in another model called Post: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default=DEFAULT_EXAM_ID) # and other fields... Can someone please help me perform migrations properly after i added this field?? -
How To Assign User in The Same Category To Each Other
I have had issues with this code and i seriously need help. I want to assign user to another user in the same payment category like a queue. There will be a sending users and a receiving user- the sending user will request for a payment of the amount in my category (for example $5, $10, $15) then the system will automatically assign the user to another user requesting to receive a payment in that category. Lets say it will be a queue and it will be first come first serve. user to user payment and a category to category user pairing or assigning to pay each others. please take a look at my code from django.db import models from django.contrib.auth.models import User from collections import deque d = deque('receiving') m = deque('sending') class PaymentCategory(models.Model): price = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, ) class Senders(models.Model): amount = models.ForeignKey(PaymentCategory, on_delete=models.CASCADE) class Receivers(models.Model): amount = models.ForeignKey(PaymentCategory, on_delete=models.CASCADE) class Payment(models.Model): senders = models.ForeignKey(Senders, on_delete=models.CASCADE) receivers = models.ForeignKey(Receivers, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE) def __init__(self, request, receivers=None, senders=None, *args, **kwargs): super(Payment).__init__(*args, **kwargs) if self.senders.paymentcategory.price == receivers.paymentcategory.price: senders.amount = receivers.amount def join_payment_users(self, request, receivers=None, senders=None, ): receiving_user = request.senders.user.amount sending_user = request.receivers.user.amount all_receiving_user = receivers.user … -
uwsgi process taking lots of memory
I'm working with Django + uwsgi and below are some main settings uwsgi [uwsgi] pythonpath=/usr/local/server chdir=/home/server env=DJANGO_SETTINGS_MODULE=conf.settings module=server.wsgi master=True pidfile=logs/server.pid vacuum=True max-requests=1000 enable-threads=true processes = 4 threads=8 listen=1024 daemonize=logs/wsgi.log http=0.0.0.0:16020 buffer-size=32000 When I try to get a excel file from my server the memory of one uwsgi process is growing fast and after seconds of time, browser get a Nginx 504 timeout but the memory is still growing. The file was about 30M generated by 450k rows data in my db. top -p 866 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 866 soe 20 0 7059m 5.3g 5740 S 100.8 33.9 4:17.34 uwsgi --ini /home/smb/work/soe_server Main logic codes from openpyxl.writer.excel import save_virtual_workbook from django.http import HttpResponse ... class ExcelTableObj(object): def __init__(self, file_name=None): if file_name: self.file_name = file_name self.wb = load_workbook(file_name) else: self.wb = Workbook() def create_new_sheet(self, title='Sheet1'): new_ws = self.wb.create_sheet(title=title) def write_to_sheet(self, sheetname, datas, filename): ws = self.wb[sheetname] for data in datas: ws.append(data) self.wb.save(filename) def update_sheet_name(self, sheetname): ws = self.wb.active ws.title = sheetname def append_data_to_sheet(self, sheetname, data): ws = self.wb[sheetname] ws.append(data) def save_file(self, file_name): self.wb.save(file_name) self.wb.close() def get_upload_file_data(self, name=None): if name: ws = self.wb.get_sheet_by_name(name) else: ws = self.wb.worksheets[0] rows = ws.max_row cols = ws.max_column file_data … -
Reactifying a Django Project
I have a huge Django project that was built over the years with more than 50 apps. It is starting to show it's age, and i would like to use React for the front end. This will be a colossal task, that will take over 6 month of development I believe. My question is, is it possible to start "Reactifying" the project slowly? Like using React for certain url's/pages and use Django templates for the rest? This way we can still update the project normally, and slowly add React to the project. -
django - How to reuse a field from an existing table for django user authentication
A bit of information about Github repositories, libraries, blogs, etc. that might be helpful is fine. If you know of a better way to do this, please give me any advice you can. I'm not familiar with the concept of django or English, so I may be wrong about some things. ○Purpose: I would like to use the values of the existing TABLE fields (*1-3) in the existing DB being used in the existing system as is for user authentication (login with ID and password). If possible, I would like to make it expandable for later use. ○Other restrictions: In the current situation, if the authentication process can be performed and information such as EmployeeId can be used while logging in, we think there is no problem. (Adding/updating/deleting user information can be done using the existing system or by the administrator directly hitting the DB. We believe that the ability to add, update, and delete user information on the django side is temporarily unnecessary.) Since the django system is not running yet, you can delete all you want from the DB migration history, standard django tables, etc. We don't want to use the standard django tables or create additional tables … -
Accessing lists inside a dictionary with Django Template tags
Bit stuck on how to access list values within a dictionary. I've tried the following answers to no avail: Access Dictionary Value inside list in Django Template Accessing items in lists within dictionary python I am passing in through my view.py file the following: context = {'checkoutList': CheckoutList, 'cartItems': cartItems} return render(request, 'posts/checkout.html', context) A queryset I am trying to access is Checkoutlist, and is as follows: {'id': [30, 6], 'title': ['Lorem Ipsum', 'another title'], 'location': ['Multiple Locations', 'city2'], 'imageurl': ['/media/image/img.jpg', '/media/image/img.jpg'], 'url': ['/products/lorem-ipsum', '/products/another-title']} I am trying to access the list values in my Checkout.html page but I can't figure out how. Currently I can get the key and the entire list value, see below: {% for key, value in checkoutList.items %} {{key}} {{value}} {% endblock %} This is returning the key values and the entire list, not the values inside the list. id [30,6] title ['Lorem Ipsum', 'another title'] etc.. What I am actually after is the values in the list on each for loop first iteration 30 lorem ipsum multiple locations second iteration 6 another title city2 etc How do I get the values like this? -
Can anyone Help us integrate Power Bi embed with Python Django Framework
We have Built an application using Python Django Framework, now need to Integrate the Power Bi Embed in the same application. all the Available resources are made for Flask. and we are not able to use the logic in Django. -
Cannot force an update in save() with no primary key. in django?
#admin.py from django.contrib import admin from studetails.models import Branches admin.site.register(Branches) #models.py from django.db import models class Branches(models.Model): STATUS = ( ('ACTIVE', 1), ('INACTIVE', 0) ) id = models.AutoField(primary_key=True) branchname = models.CharField(max_length=50) pro_pic = models.FileField(null=True) status = models.CharField(max_length=30, choices=STATUS) What is the save option I have to place in this model as I am not getting this error? -
Django template large data pagination link issue
I am using the django paginator in my template. Its working ok with less data, but not working good when there's large numbers of pages. Pagination links code is given bellow: <div class="paginationWrapper mt-3"> {% if match_list.paginator.num_pages > 1 %} <ul class="pagination"> {% if match_list.has_previous %} <li> <a href="?p={{ match_list.previous_page_number }} {% if request.GET.search %}&search={{ request.GET.search }} {% endif %}" class="page-link"><i class="fas fa-angle-double-left"></i></a> </li> {% endif %} {% for j in match_list.paginator.page_range %} {% if match_list.number == j %} <li class="active"><a class="page-link" href="#">{{ j }}</a></li> {% else %} <li><a href="?p={{ j }}{% if request.GET.search %}&search={{ request.GET.search }} {% endif %}" class="page-link">{{ j }}</a></li> {% endif %} {% endfor %} {% if match_list.has_next %} <li> <a href="?p={{ match_list.next_page_number }} {% if request.GET.search %}&search={{ request.GET.search }}{% endif %} " class="page-link"><i class="fas fa-angle-double-right"></i></a> </li> {% endif %} </ul> {% endif %} </div> After this i am gettin the links in my template like : what i actually want is i want to display only 10 links after that ... to show more can anyone please help me relatred this i am stuck here -
Django model double reverse lookup 2 times cause duplicates, how to optimize
The context: We have a database (Postgresql) schema(model) as follow So each job can have Only one organization Many Job recruiters Additionally the organization attached to job can have Many Organization recruiters as well What we want as a query: Jobs with organization with public attribute as true OR Jobs that have Job Recruiter as current user OR Jobs that it's organization has Organization Recruiter as current user What did we tried & the duplicate problem This is the queryset we did Job.objects.filter( organization__is_public=True, job_recruiters__user_id=user.id, organization__organization_recruiters__user_id=user.id ) The problem is that the queryset can contain duplicates (Imagine the case that organization has a recruiter that is this user but also user is the job recruiter of this job) from the underlying join of PostgreSQL What we tried to solve the problem Adding .distinct() This does solve the problem but is very slow(400ms+) and resource intensive for the database when the queryset is expected to return 10K+ results Finding jobs id with each of the condition, append them, filter out duplicates and make a call of id__in filter like this job_list_org_public = Job.objects.filter(organization__is_public=True) job_list_job_recruiter = JobRecruiter.objects.filter(recruiter__user_id=user.id) job_list_organization_recruiter = ..... combined_job_id = distinct(job_list_org_public + job_list_job_recruiter + job_list_organization_recruiter) return Job.objects.filter(id__in=combined_job_id) Still this one … -
Unable to create JSONField in django with MYSQL
I have UserModel (already created) and I want to add another field in the model of type JSONField. extra_data = JSONField() Migration: # Generated by Django 2.0.5 on 2021-03-19 05:55 from django.db import migrations, models import django_mysql.models class Migration(migrations.Migration): dependencies = [ ('lead', '0043_merge_20210317_1339'), ] operations = [ migrations.AddField( model_name='claim', name='extra_data', field=django_mysql.models.JSONField(), ), ] When I run command python manage.py migrate It throws django.db.utils.ProgrammingError: BLOB, TEXT, GEOMETRY or JSON column 'extra_data' can't have a default value I'm using django==2.0.5 djangorestframework==3.8.2 django-mysql==3.5.0 python==3.6.5 MySQL Server version: 8.0.22 -
Show different Lessons inside different Modules in Learning Management System using Django
The Project is about LMS. Students are able to learn from courses uploaded by instructors assigned by the Superadmin. I want to get all lessons related to one Module. for example Module A should have lesson a and lesson b while Module B should have lesson c and lesson d respectively. Module A and B are Modules inside a Course created by Super Admin. Lesson a, b, c and d are added by instructors via the Django admin dashboard. myapp/Models.py class Course(models.Model): name = models.CharField(...) class Module(models.Model): name = models.CharField(...) course = models.ForeignKey(Course, ...) class Lesson(models.Model): name = models.CharField(...) module = models.ForeignKey(Module, ...) myapp/views.py def Module(request, pk): template = 'myapp/name_of_template.html' module = get_object_or_404(Module, id=pk) lessons = lesson.module_set.all() context = {'lessons': lessons} return render(request, template, context) myapp/urls.py from django.urls import path from . import views urlpatterns = [ path('module/<int:pk>/', views.moduleDetails, name="module_detail"), ] myapp/module.html <div class="accordion accordion-flush" id="accordionFlushExample"> {% for module in modules %} <div class="accordion-item"> <h2 class="accordion-header" id="flush-heading-{{module.id}}"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapse-{{module.id}}" aria-expanded="false" aria- controls="flush-collapse-{{module.id}}"> {{module.name}} </button> </h2> <div id="flush-collapse-{{module.id}}" class="accordion-collapse collapse" aria- labelledby="flush-heading-{{module.id}}" data-bs-parent="#accordionFlushExample"> <div class="accordion-body"> <ol type="1"> {% for lesson in lessons %} <li><a href="{% url 'lesson_detail' lesson.pk %}">{{lesson.name}}</li></a> {% endfor %} </ol> </div> </div> </div> My … -
How I use jquery ajax pagination in my django blog Project?
I would like to implement pagination in django using jquery ajax. Here is my views.py like that: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import blog def home(request): blogs = blog.objects.all() page = request.GET.get('page', 1) paginator = Paginator(blogs, 5) #number of blogs you want to paginate try: blogs = paginator.page(page) except PageNotAnInteger: blogs = paginator.page(1) except EmptyPage: blogs = paginator.page(paginator.num_pages) return render(request,'home.html', {'blogs':blogs} And my pagination.py is like following: <nav aria-label="Page navigation example"> <ul class="pagination justify-content-start mt-3"> {% if not blogs.has_previous%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">Previous</a> </li> {% endif %} {% if blogs.has_previous%} <li class="page-item"> <a class="page-link" href="?page={{blogs.previous_page_number}}" tabindex="-1">Previous</a> </li> {% endif %} {% if blogs.has_previous%} <li class="page-item"><a class="page-link" href="?page={{blogs.previous_page_number}}">{{blogs.previous_page_number}}</a></li> {% endif %} <li class="page-item"><a class="page-link" href="#">{{blogs.number}}</a></li> {% if blogs.has_next%} <li class="page-item"><a class="page-link" href="?page={{blogs.next_page_number}}">{{blogs.next_page_number}}</a></li> {% endif %} {% if blogs.has_next%} <li class="page-item"> <a class="page-link" href="?page={{blogs.next_page_number}}">Next</a> </li> {% endif %} {% if not blogs.has_next%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">Next</a> </li> {% endif %} </ul> I could not find any broad step to step tutorial/guide about on this matter. Devs! Please tell me how to implement pagination in django using jquery ajax? Thanks in advance. -
How I can conver the video duration in django to the hourse and minutes and seconds in django
I get the video duration when the user upload the form by VideoFileClip but it's appear by seconds how I can divide this seconds on minutes and hourse whith seconds if 'submit_v_form' in request.POST: print(request.POST) V_form = Video_form(request.POST, request.FILES) if V_form.is_valid(): instance = V_form.save(commit=False) video = request.FILES['video'] clip = VideoFileClip(video.temporary_file_path()) instance.video_duration = clip.duration instance.author = account instance.save() V_form.save_m2m() V_form = Video_form() video_added = True if instance.save: return redirect('home') -
Tutorial: please help rewrite form on classes?
I can't rewrite the mysite/polls form into classes.help me. I get different errors every time. <!-- detail.html --> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Vote"> </form> # forms.py: from django import forms from .models import Choice class VoteForm(forms.ModelForm): choices = [(ch.pk, ch.choice_text) for ch in Choice.objects.filter(pk=pk)] choices = tuple(choices) choice_text = forms.ChoiceField(widget=forms.RadioSelect(choices=choices)) class Meta: model = Choice fields = ['choice_text'] # views.py# class DetailView(generic.FormView, generic.DetaildView): model = Question template_name = 'polls/detail.html' form_class = VoteForm def get_queryset(self): """ Excludes any questions that aren't published yet. """ return Question.objects.filter(pub_date__lte=timezone.now()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) #context["pk"] = self.pk #context["form"] = VoteForm() return context #def get(self, request, *args, **kwargs): #form = VoteForm(pk=kwargs['pk']) #return super().get(self, request, *args, **kwargs) How do you bind it all together? How get question_id (pk) in form, how mix with detaild view, how correct check validation this form? I'm confused. Help please. Is it possible? -
How to design a versatile views.py function in django
def equipment_instance_detail(request, *args, **kwargs): pk = kwargs.get('pk') equipment_instance = get_object_or_404(EquipmentInstance, pk=pk) dataset = OpeningData.objects.all().order_by('date').values('date', 'equipment_temperature') categories = list() temperature_series = list() for entry in dataset: categories.append('%s' % entry['date']) temperature_series.append(entry['equipment_temperature']) context = {'categories': json.dumps(categories), 'temperature': json.dumps(temperature_series), 'equipment_instance': equipment_instance} return render(request, 'webapp/equipment_instance_detail.html', context=context) So this function takes in an equipment instance and renders a graph for it. The code above is a function that is configured to make a time series plot using chart.js for a piece of equipment (heat press). The problem is depending on what type of equipment instance it is, the code and visuals could be different. For example, right now, I have two types of equipment: Heat Press and Microscope. Each piece of equipment has instances of itself which can have data associated with it. A heat press may only use a time series chart while a microscope could use a histogram and a scatter plot. The difference between the two types of equipment instances will require unique code and probably unique templates. While there are only two equipment instances now, there could be hundreds in the future. I want something that can handle the massive differences. I could use a gigantic if statement that asks if the … -
Django_tables2 in a tabbed html view with Charts.js?
so I'm trying to get Charts.js and django_tables2 in a tabbed view system where you can click on the different tabs to display dynamic data in either Charts.js or django_tables2, all in the same URL. So far I have Charts.js working the way I want it in one URL, I have Django_tables2 working the way I want it in another URL, and I have the HTML tabbed view system working along with an AJAX call. The part I'm struggling with is combining the Charts.js and djano_tables2 into one URL. Has anybody succeeded doing this before? I've hit so many walls trying to do this. I tried simply putting the code from data_list.html into my charts.html and restructuring my views but this lead me down a path of endless errors. I'm just really not sure how I could combine these two into one URL. This is my code so far: views.py # For initial rendering of HTML tabbed views and user input search fields @api_view(('GET',)) def ChartForm(request, *args, **kwargs): form = SearchForm(request.GET) context = { 'form': form } return render(request, "charts.html", context) # AJAX calls this view with new parameters, this view filters the results, returns JSON object class apiChart(APIView): def … -
How to use django markdown editor to mention or tag users
I am building a BlogApp and I found django-markdown to tag user using @. BUT i didn't find any tutorials to implement in Application. HERE is the the django-markdown-editor. I found using django-markdown-editor in THIS answer. WHY USE MARKDONN ?` Because it is used to tag users using @ and I am trying to implement it in my BlogApp I have no idea how to use this. Any help would be Appreciated -
How to get slope of variables and intercept from a stored(serialized using python pickle) ML model
I am a newbie to machine learning and python. I have a Python code snippet which loads stored ml model and predict with new inputs. mlModel = pickle.load(open('linear_model4.pickle','rb')) request_body = request.body.decode('utf-8') parsed_request = makePredictionInput(json.loads(request_body)) rb=json.loads(request_body) print(parsed_request) result = mlModel.predict(parsed_request) It uses 5 inputs for prediction. Is there a way to get the slopes and intercept from above loaded model sothat i can form the equation as y = intercept + slope1variable1+ slope2variable2+ slope3*variable4+..... -
How can change DateTimeField Format in django models.py file
change datetime "2019-08-19T11:26:44Z" to this "2019-08-19 11:26:44"