Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" -
Django Model fields - Imagefield and filefield
Does django saves files and images directly into database or in some local storage, and saves only path in database? (In imagefield and filefield) -
(django) context data not rendering to html
I have a dropdown menu where the user can select the orderID of a taxi ride, and the total distance travelled for that specific order ID will be rendered to the html. The total distance is already in my MySQL database and only needs to be rendered to the frontend, but I'm calling the variable and its not working. I've managed to get it to print to the terminal, but it's showing on my html file and I'm pretty sure I'm calling the variable wrong. Everything else renders, just not {{ total_distance}}. Any pointers? views.py def home(request): # limit query results to first 50 orders just to maximise performance orders = Distance.objects.all().order_by("order")[:50] if request.method == "POST": # code only enters if statement when an item from the dropdown menu is selected print("POST") order_id_selected = request.POST.get("order_id_selected", None) if order_id_selected: start_lat = Distance.objects.values_list( 'start_lat').filter(order_id__exact=order_id_selected) start_long = Distance.objects.values_list( 'start_long').filter(order_id__exact=order_id_selected) end_lat = Distance.objects.values_list( 'end_lat').filter(order_id__exact=order_id_selected) end_long = Distance.objects.values_list( 'end_long').filter(order_id__exact=order_id_selected) total_distance = Distance.objects.values_list( 'total_distance').filter(order_id__exact=order_id_selected) print(order_id_selected) print(total_distance) return render(request, 'base.html', { 'orders': orders, 'dropdown_menu': order_id_selected, 'total_distance': total_distance, }) else: # current view defaults to else print("not working") return render(request, 'base.html', { 'orders': orders, }) base.html <div class="container"> <div class="row"> <div class="col-9"> <div class="order"> <br> <h2>View and calculate … -
Failing to Use Foreign Key in Django-Forms & Getting Errors
I am making an application which will accept the inventory information like serial number and every other details and then I am making another form which will validate the entries from the previous form. I tried multiple resolution which were available on the same error but nothing is helping out here. I am pasting the code here. If there is anything else required, please do comment models.py/inventory_app from django.db import models #from reservation_app.models import Reserve class Form1(models.Model): item = models.CharField(max_length=125) quantity = models.IntegerField(default=0) vendor = models.CharField(max_length=125) inward = models.IntegerField(default=1234) sno = models.ManyToManyField(max_length=100, to='reservation_app.Reserve') date = models.DateField() date_received = models.DateField() def __str__(self): return self.item If I uncomment the line : #from reservation_app.models import Reserve I am getting error of circular import as ImportError: cannot import name 'Form1' from partially initialized module 'inventory_app.models' (most likely due to a circular import) (C:\Users\satharkar\Desktop\altiostar\inventory\inventory_app\models.py) models.py/reservation_app from django.db import models from inventory_app.models import Form1 # Create your models here. class Reserve(models.Model): company = models.CharField(max_length=125) sno = models.ForeignKey(to='inventory_app.Form1', null=True, on_delete= models.SET_NULL) date_req = models.DateField() All my changes created a huge mess, previously I was able to take input from models.py/inventory_app and was able to see it in models.py/reservation_app and now this is not the case. I am … -
Custom decorator with message
I have custom decorator as shown below def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin_login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_staff, login_url=login_url, redirect_field_name=redirect_field_name ) if view_func: return actual_decorator(view_func) return actual_decorator it works and redirect to the login if user is not staff, here how can I add a message informing user to login as staff -
Django-allauth how to redirect to pervious page after login
I'm using Django-allauth , I can successfully redirect it to home page by adding this in settings.py: LOGIN_REDIRECT_URL = '/home' But is there anyway I can redirect it to pervious page? -
Counting. Django query optmization, Django ORM
can you tell me how to optimize these queries? What is the most efficient way? I want to render all values separately in a view. I attached the screenshot from django-debug-toolbar. I want to learn best practices. I as I see in the docs, this gives a dictionary rather than raw values. How would I pass these querysets in context? In my HTML I have a .js chart with data = [ {{ author_bsc_count }}, {{ author_bsc_count }}...] django-debug-toolbar-SQL-photo # These queries give the totals for each degree. authors = Author.objects.all() author_student_count = authors.filter(degree='Student').count() author_bsc_count = authors.filter(degree='BSc').count() author_msc_count = authors.filter(degree='MSc').count() author_phd_count = authors.filter(degree='PhD').count() # These queries give the manuscript totals for each volume. volumes = Manuscript.objects.all() volume_5 = volumes.filter(citation_volume='5').count() volume_4 = volumes.filter(citation_volume='4').count() volume_3 = volumes.filter(citation_volume='3').count() volume_2 = volumes.filter(citation_volume='2').count() volume_1 = volumes.filter(citation_volume='1').count() # These queries give the manuscript totals for each section. algology_total = volumes.filter(section__title='Algology').count() mycology_total = volumes.filter(section__title='Mycology').count() geography_total = volumes.filter(section__title='Geography').count() entomology_total = volumes.filter(section__title='Entomology').count() arachnology_total = volumes.filter(section__title='Arachnology').count() floristics_total = volumes.filter(section__title='Floristics').count() mammology_total = volumes.filter(section__title='Mammology').count() -
How can django-rest return a serializer error in the correct format for the frontend?
I don't like how django-rest returns a serialization erros JSON. For instance, if two fields are not provided in the request body, the default JSON response is the following: { "title": [ "This field is required." ], "contract_recipients_data": [ "This field is required." ] } I have read about custom exception handling, but I am not sure how can I flatten this error response. I would like for the error message to contain only a string so that my frontend app can handle it better ( how can the frontend handle this dynamic JSON? It seems difficult and not scalable). -
Adding two functions in one input tag
I am trying to add two two functions in one input tag. BUT failed many times. What i am trying to do ? There are two functions in different input tags in my HTML template. One for add tag by , . AND second for autocomplete. I am trying to add them together, So i can use autocomplete and add tag at same time. home.html #This function is for `autocomplete`. <form> <label for="product">Product</label> <input type="text" name="product" id="product"> </form> </form> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#product").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> #This function is for `add tag` <b>Add Tags </b> <input type="text" data-role="tagsinput" class="form-control" name="tags"> <br> What have i tried ? I see an answer that if i add semicolons at the end of the both tag then it will work BUT it didn't work for me. <form> <label for="product">Product</label> <input type="text" name="product" id="product"; data-role="tagsinput";> </form> I don't know what to do. Any help would be Appreciated. -
django update form not all fields are autofill with existing data
iam a noobie in django, A query is why not all the fields are loading in the existing form when I click update .. Except for the profile pic, none of the fields related to the model ( eg, Mobile address, Skill ) are loading, what to change in the form. can someone guide me on how to load the remaining field data in the form? Model : class Mechanic(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) profile_pic= models.ImageField(upload_to='profile_pic/MechanicProfilePic/',null=True,blank=True) address = models.CharField(max_length=40,null=True,blank=True) mobile = models.CharField(max_length=20,null=True,blank=True) skill = models.CharField(max_length=500,null=True) salary=models.PositiveIntegerField(null=True) status=models.BooleanField(default=False) @property def get_name(self): return self.user.first_name+" "+self.user.last_name @property def get_id(self): return self.user.id def __str__(self): return self.user.first_name View @login_required(login_url='adminlogin') def update_mechanic_view(request,pk): mechanic=models.Mechanic.objects.get(id=pk) print(mechanic) user=models.User.objects.get(id=mechanic.user_id) userForm=forms.MechanicUserForm(instance=user) mechanicForm=forms.MechanicForm(request.FILES,instance=mechanic) print('mechanicForm',mechanicForm) print('userForm', userForm) mydict={'userForm':userForm,'mechanicForm':mechanicForm} if request.method=='POST': userForm=forms.MechanicUserForm(request.POST,instance=user) mechanicForm=forms.MechanicForm(request.POST,request.FILES,instance=mechanic) if userForm.is_valid() and mechanicForm.is_valid(): user=userForm.save() user.set_password(user.password) user.save() mechanicForm.save() return redirect('admin-view-mechanic') return render(request,'vehicle/update_mechanic.html',context=mydict) Forms class MechanicUserForm(forms.ModelForm): class Meta: model=User fields=['first_name','last_name','username','password'] widgets = { 'password': forms.PasswordInput() } class MechanicForm(forms.ModelForm): class Meta: model=models.Mechanic fields=['address','mobile','profile_pic','skill'] Update mechanic.html {% extends 'vehicle/adminbase.html' %} {% load widget_tweaks %} {% block content %} <head> <style media="screen"> input[type=text], select,input[type=number] ,input[type=password], textarea{ width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } input[type=submit] { width: 100%; background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px … -
Visual Studio Code Django debugging breakpoints not triggered on Views and Templates
I am facing a debugging issue with VsCode where it's failing to trigger any type of breakpoints (standard or log), but specifically on View calls and Templates. Breakpoints in other parts of the Django project structure work correctly. For example in this code sample: class HomeView(TemplateView): template_name = "home/home.html" def get(self, request, *args, **kwargs): return render(request, self.template_name, {}) A breakpoint on template_name = "home/home.html" will be triggered successfully when the Class is constructed. However a breakpoint on return render(request, self.template_name, {}) will never trigger (I would expect it to trigger when the user navigates to the URL this class renders). A few things I have already tried: Disable all other VsCode extensions aside from Python, Jupiter, and Pylance Revert to a 4-month-old (I'll explain why 4 months below) version of VsCode, the Python extension, PyLance, and Django Creating a function-based view of the above (which also doesn't trigger the breakpoint) Create a brand new Django project (been able to reproduce this on a brand new project, and two other existing projects) The 4-month-old timeline was because the last time I was working with Django and debugging Views was about 4 months ago so figured I would try those versions. I … -
Django - Limiting Selections Based on ManyToMany Association
Am a front end guy interface guy. Tried learning to program some time ago but gave up. Giving it another shot using Python/Django this time around. Going well. Been trying to overcome the following issue for the last few days. Tried applying possible solutions anywhere I could find them but no luck so far. I have a user model with a manytomany association with a region. A user can manage many regions. I have a site model where the logged in user can create a site and that site has a foreign key with one region. I am looking to limit the selections in the siteform drop down so it only shows the regions identified through the manytomany relationship on the user model. The form will be used on my sitecreate view. Absolutely any help that you can provide would be invaluable. I have no hair left. # users.models from worker.sites_projects.models import Region ... class User(AbstractUser): ... region = models.ManyToManyField( Region, blank=True ) # sites_projects.models ... class Region(models.Model): name = models.CharField("Region", max_length=25) class Site(TimeStampedModel): site_name = models.CharField("Site Name", max_length=200) ... region = models.ForeignKey( Region, ... ) # sites_projects.forms ... ... class SiteForm(forms.ModelForm): ... # region = forms.ModelChoiceField(queryset=Region.objects.all()) # def __init__(self, … -
How to install socket.io in Django Project?
I am building games with Django. But I have one problem https://pypi.org/project/django-socketio/ I follow this guide. But It's not working. As you can see, there are many issues. if you have experience to building socket.io sample, please share me, If so, I am really really thanks. -
Django Admin Inline Link to Specific Queryset?
Following the Django Polls app tutorial, you end up with 2 models as follows: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) The Choice model can be registered with the Django Admin Site, but then you are browsing all Choice objects for all Question objects and this gets cumbersome very quickly. The Choice model could be inlined using InlineModelAdmin so that only related Choice objects appear directly on the Question change page. Though if the number of choices gets large, this can also get quite cumbersome. I'm wondering if there is instead a way to link to the list of related Choice objects from the Question page? -
Django Postgres Exclusion Constraint with ManyToManyField
I would like to use Django Exclusion Constraint with ManyToManyField. Unfortunatelly, so far my efforts were futile. This is my appointment model: from django.contrib.postgres.constraints import ExclusionConstraint from django.contrib.postgres.fields import DateTimeRangeField, RangeOperators class Appointment: patients = models.ManyToManyField(Patient, related_name='appointments' , blank=True ) datetimerange = DateTimeRangeField(null=False, blank = False ) doctor = models.ForeignKey(Doctor, related_name='doctor_appointments') class Meta: constraints = [ ExclusionConstraint( name='unique_doctor', expressions=[ ('datetimerange', RangeOperators.OVERLAPS), ('doctor ', RangeOperators.EQUAL), ], ), ExclusionConstraint( name='unique_patients', expressions=[ ('datetimerange', RangeOperators.OVERLAPS), ('patients', RangeOperators.CONTAINED_BY) ], condition= Q(is_archived=False) & Q(is_cancelled=False) ) ] Unfortunatelly this doesn't work. The first constraint that references the Doctor works perfectly, but the second one gives me this error during migration: return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "patient_id" named in key does not exist return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column "patient_id" named in key does not exist This has been bogging me for quite some time. Any help appreciated.