Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django : can we use if else inside Sum function with annotation?
i want to set a condition to my Sum function inside annotate this is my models.py class MyModel(models.Model): name = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.IntegerField() price = models.IntegerField() class Prodcut(models.Model): name = models.CharField(max_lenth=20) cost = models.IntegerField() price = models.IntegerField() my views.py MyModel.objects.values('name__name').annotate( income=( Sum(((F('price')*F('order')) - ( (F('name__price')+F('name__cost'))*F('order')) ),output_field=IntegerField())),quantity=( Sum(F('order')) )) i dont want to use .filter(income__gt=0) because it stops quantity from counting and i dont want to counting income to those products which loss its sold for example i make a post on MyModel(name=mouse ,order=2,price=20) and in my Product model i have these information for mouse product Product(name=mouse,cost=4,price=10) , when i calculate to find income for this product : (2 *20) - ((4+10)*2) => 40 - 28 = 12 , but sometimes happen the result will be a negative price when (2*10) - ((4+10)*2) => 20 - 28 = -8 *i use mysql v:8 for database i want to prevent negative numbers to add to my income with respect the other columns quantity -
How to get First 4 object from Django Queryset
I want the first four Objects from a Django Database Queryset !! I am trying to do that by slicing it like this [:4] song = Song.objects.all()[:4] but it is not working it is taking all the querysets. Whole Code:- def index(request): song = Song.objects.all() return render(request, 'musicbeats/index.htm', {'song': song}) HTML code:- {% for i in song %} <div style="padding-left: 2%; padding-top: 1%;"> <div class="card" style="width: 18rem;"> <h5 class="card-title">{{i.name}}</h5> </div> </div> {% endfor %} -
How do I create models and views for this html template? Django
Hey Guys I wanted to create a view and model for my HTML template that has AJAX and JQUERY , how ever i am not sure on how to implement the formsets... Link : https://hasteb.in/lisimiye.xml I posted my html code there and can anyone show me how do i create a model and views for that? -
How to add multiple types of objects in a class
Here, is the problem when I try to add multiple objects to context through get function it is not showing pagination and when views.py is like below code then I am unable to add multiple objects of different models. Ex: I want to add two models like Items and Ads to my Homepage class then how can I do this. Views.py class HomeView(ListView): model = Item paginate_by = 12 template_name = "home.html" home.html <div class="card-body text-center"> <a href="" class="grey-text"> <h5>{{ item.get_category_display }}</h5> </a> <h5> <strong> <a href="{{ item.get_absolute_url }}" class="dark-grey-text">{{ item.title }} <span class="badge badge-pill {{ item.get_label_display }}-color">{{item.tag}}</span> </a> </strong> </h5> <h4 class="font-weight-bold black-text"> <strong> {% if item.discount_price %} <del>Rs. {{ item.price }}</del><br> Rs. {{ item.discount_price }} <span class="badge badge-pill danger-color">{{item.dis_per}}% off</span> {% else %} {{ item.price }} {% endif %} </strong> </h4> </div> -
How to download data in excel sheet through django api
class Task(models.Model): name=models.CharField(max_length=20) address=models.CharField(max_length=50) def __str__(self): return str(self.name) #viewset plan=Task.objects.all() b=[] for i in plan: b.append({ "name":i.name, "address":i.address, }) return Response({"data":b}) output should be 0 name:address 1 Ashu:Gurgaon -
How to get deterministic value from Channels.object.all()?
On my Django backend I'm sending list of available TV channels. They are rarely changed so I'm creating another url that hashes all /Channels.object.all()/ channels' data to hash/checksum value so that client side just compares checksum/hash value and only update list of channels when there is a change. I made a following function however hash value is different while data is still the same. class ChannelViewCheck(APIView): def get(self, request, format=None): channels = Channel.objects.all() return Response(hash(channels)) -
Impossible to access Heroku config vars from python code
I am trying to deploy my django app on Heroku, but the issue is that I cannot access my config vars from python code. Here are my config vars (obfuscated for obvious reasons) $ heroku config --remote production === myapp Config Vars DATABASE_URL: postgres://<removed> DJANGO_DEBUG: 0 GOOGLE_APPLICATION_CREDENTIALS: <removed> SECRET_KEY: <removed> Now, in my django settings.py, the code import os os.environ["DJANGO_DEBUG"] results in an error because the key "DJANGO_DEBUG" is nowhere to be found in the dictionary os.environ. My question is: how can I access Heroku config variables in production? I have tried the package python-decouple, but it is not able to access the config vars neither. (Locally, my variables are put in a .env file and are accessible with the help of the package python-decouple) Thank you for your help! -
Search through django model input boxes dependent on previous input
I want to build a form with choice dropdowns (ModelChoiceField or Choicefield). If you select a particular option the next choice dropdown box will only be populated with options that relate to the first choice A row/entry in the model would include fields class Course(models.Model): curriculum = models.CharField(null=False, blank=False, max_length=150, verbose_name='Name of Curriculum') name = models.CharField(null=False, blank=False, max_length=150, verbose_name='Name of Course') level_study = models.CharField(null=False, blank=False, max_length=150, verbose_name='Level of Study') So if you select a particular curriculum only subject names from that curriculum show up in the next dropdown. ........................................................................................................ If there's a better solution than a chain of dropdown option-selects or the way I've organized the model and logic. I'm more than willing to hear about it. -
Display python list as table in html
I am struggling to format my list as a table in html (I am using django). Usually, I can easily achieve this by a for loop, like this: <tbody> {% for item in lyrics %} <tr> <td>{{lyrics}}</td> </tr> {% endfor %} But this gives me the whole list in every table cell. If I do it like this... <tr> <td>{{lyrics.0}}</td> <td>{{lyrics.1}}</td> </tr> ...it works. But obviously I don't want to write it out for all n items. I was hoping I can do something like... {% for i in lyrics.i % } {{lyrics.i}} But that didn't work either. The following works in terms of getting the results neatly below each other, but obviously it's not a table: <ol class='lyrics-list'> {{ lyrics|unordered_list }} </ol> My list comes from my view: lyrics = models.Song.objects.get().lyrics_as_list() -
mezzanine field injection and admin config
I am developing on django mezzanine right now and used the instructions provided here I wanted to add a file field to "page" object (actually all of the objects). but I can't see it on the admin page, although I checked the procedure and found out: my file field does exist on db. (creation was correct apparently) the "page_fieldsets" is correctly changed in the admin. but at the end I can not see the field in the admin page and being so confused about it. this is the "myapp/admin.py" from django.contrib import admin from copy import deepcopy from mezzanine.pages.admin import PageAdmin from mezzanine.pages.models import Page # Register your models here. page_fieldsets = deepcopy(PageAdmin.fieldsets) page_fieldsets[0][1]["fields"].insert(-2,"pagefile") class MyPageAdmin(PageAdmin): fieldsets = page_fieldsets admin.site.unregister(Page) admin.site.register(Page,MyPageAdmin) -
creating an api to update postgres db with a json or yaml payload
I decided to ask this here after googling for hours. I want to create my own API endpoint on my own server. Essentially I want to be able to just send a yaml payload to my server, when received I want to kick off my python scripts to parse the data and update the database. I'd also like to be able to retrieve data with a different call. I can code the back-end stuff, I just don't know how to make that bridge between hitting the server from outside and having the server do the things in the back-end in python. Is django the right way? I've spent a couple days doing Django tutorials, really cool stuff, but I don't really need a website right now but whenever I search for web and python together, django pretty much always comes up. I don't need any python code help, just some direction on how to create that bridge. Thanks. -
Django - How to load app template files properly
I'm learning django by following the book Building Django 2.0 Web Applications and everything worked up until now. The project is called config and there is one app which is called core. The app (core) has it's own templates directory (config/core/templates) and it's own urls.py file (config/core/urls.py) which is loaded by the root urls.py file (config/config/urls.py). What happens when I run the server and visit one of the core URLs, is this: TemplateDoesNotExist at /movies Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/sugarcane/projects/config/templates/core/movie_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/sugarcane/projects/config/core/templates/core/movie_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/sugarcane/projects/config/venv/lib/python3.8/site-packages/django/contrib/admin/templates/core/movie_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/sugarcane/projects/config/venv/lib/python3.8/site-packages/django/contrib/auth/templates/core/movie_list.html (Source does not exist) The template file it's looking for is actually: /home/sugarcane/projects/config/core/templates/movie_list.html Why is it looking in the wrong directories? Here are the urls.py files: config/core/urls.py: from django.urls import path from . import views app_name = 'core' urlpatterns = [ path('movies', views.MovieList.as_view(), name='MovieList'), ] and config/config/urls.py from django.contrib import admin from django.urls import path, include import core.urls urlpatterns = [ path('admin/', admin.site.urls), path('', include(core.urls, namespace='core')), ] In settings.py, I got this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ] , 'APP_DIRS': True, 'OPTIONS': { ... }, }, ] … -
Django: nesting related columns in a json array
Objective I want to dynamically structure my menu links based on the site pages that I create in the database and its relationship with other pages so that I can generate the appropriate main menu links and dropdowns based on those relationships, formatting the query result as JSONField() using django-rest-framework (DRF). I generate and fetch the results via a DRF API class. This is the kind of navigation that I want: The level of dropdown can be indefinite, depends on whether I define it in the database. Expected Result Based on the desired navigation above, this is how my API should return the result: [{ "title": "Home", "path": "/", "depth": 1 "child": null, }, { "title": "Government", "path": "/government/", "child": [{ "title": "Provincial Profile", "path": "/government/provincial-profile/", "depth": 2, "child": null }, { "title": "Governor", "path": "/government/governor/", "depth": 2, "child": null }, { "title": "Offices", "path": "/government/offices/", "depth": 2, "child": [{ "path": "/government/offices/provincial-governors-office", "title": "Provincial Governor's Office", "depth": 3, "child": null }] }] }] Model Structure I have 2 models involved in generating the main menu and dropdowns CmsPage - defines the page property of the page i.e. title of page, the link it navigates to, etc. CmsPageTree - defines the … -
Read file and download from django
i'm trying to read an audio file mp3 and download it using django and vuejs my-backend code @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def file_download(request, application_id, file_id): base_path = os.getenv('UPLOAD_PATH') file_name = str(file_id) file = default_storage.open(base_path + file_name) print(file) print(file.size) print(settings.MEDIA_ROOT) response = HttpResponse(content=file) response['Content-Type'] = 'audio/mp3' response['Content-Length'] = file.size return response front-end code ApplicationFileService.download(this.$route.params.applicationId, this.$route.params.fileId).then( async result => { let blob = new Blob([result.data], { type: 'audio' }) console.log(blob.size); this.$utils.downloadFileFromBlob(result.data, this.file.name) } ) download file function downloadFileFromBlob (data, fileName) { const blob = new Blob([data]) const url = window.URL.createObjectURL(blob) const anchor = document.createElement('a') anchor.href = url anchor.download = fileName anchor.click() window.URL.revokeObjectURL(url) } I was able to download the file but it is not playable while the original file on server was fine. I check file size on server is 6270152 and it is correct but when i check the file received in front-end it is 10610168 in size. I don't know why there is a big difference in file size the file received was wrong and not playable. Can anyone help? -
Django login doesnt work when deployed live
I've seen this question asked before and not answered, so I'm going to give as much detail as possible. Django login gives http 500 error Locally both my out the box admin and allauth admin work fine, however deploying to cpanel or aws my app crashes with a server 500 error on "post". However, if I sign in the credentials do make it to the database, but the 500 error is still generated. If the credentials are wrong, django generates the right response. So the post makes it to the endpoint, but not back. For cpanel I used mysql, the connection was fine. I was able to add things from the backend into the app. This time I kept sqlite to see if it was just a database issue, for example not allowing remote connection. Wrong again, for aws I tried to add the wsgipassauth on to the config file. No luck, I'm fairly new to django. I'd think this is a problem many encounter when going live but I don't see much support for it. It's as if the admin urls and all auth urls aren't beings brought in, however if debug is on true I can see the … -
Reshape django queryset to display in template
I am learning Django and trying to build a simple student grade publishing system. I have set up my model classes as follow: class Student(models.Model): name= models.CharField(max_length=30) rollNum=models.CharField(max_length=12) faculty=models.CharField(max_length=10) def __str__(self): return self.name class Tutorial(models.Model): name=models.CharField(max_length=10) def __str__(self): return self.name class Grade(models.Model): grade=models.CharField(max_length=2) student=models.ForeignKey(Student,on_delete=models.CASCADE) tutorial=models.ForeignKey(Tutorial,on_delete=models.CASCADE) def __str__(self): return self.student.name+ '|' + self.tutorial.name+ '|' +self.grade class Meta: unique_together = ('student','tutorial') Grade.objects.filter().values_list('student__name','tutorial__name','grade') is returning QuerySet in following form: Student1 Tutorial1 A Student2 Tutorial1 A+ Student1 Tutorial2 B Student1 Tutorial3 A How can I reshape the result into the following form? Student Tutorial1 Tutorial2 Tutorial 3 Student1 A B A Student2 A+ X X I want to render this in django template. -
Logged in with Heroku on command line, now it says I'm not authorized to run any Heroku command Django
I published a website to the web today. I was able to run git push heroku master fine at least ten times, then I login to my heroku account in order to upgrade the site, and it says I am no longer authorized to publish any changes to my site. It runs a 403 error and I can't figure out how to authorize my app with my heroku account. Here is the error message displayed. -
How to fix arranging objects by date in the Class Based Views in Django
This is a beginner's question I am trying to arrange orders by ordered date but it is not working I tried 2 things to add order in the CBV directly and in a get_queryset but both are not working. I am trying to learn how to do it correctly, they are currently ordered from old to new and I am trying to arrange them from new dates to old. Here is the model class Order(models.Model): ordered_date = models.DateTimeField() here are the views.py class OrderList(LoginRequiredMixin, ListView): model = Order template_name = "user_orders.html" paginate_by = 6 context_object_name = 'orders' ordering = ['-ordered_date'] def get(self, *args, **kwargs): try: order = Order.objects.filter(user=self.request.user, ordered=True) context = { 'orders': order, 'object': order } return render(self.request, 'user_orders.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have any orders") return redirect("/") def get_queryset(self): return Order.objects.filter(user=self.request.user, ordered=True).order_by('-ordered_date') Thank you -
Request multiple parallel ajax call in same django view?
I want to make multiple ajax call on same django view so that i get all the response from those calls at the same time. For example: If this is my ajax call $(document).ready(function(){ $(document).on('click', '.btn', function(event){ event.preventDefault(); $.ajax({ url:'', dataType:'json', }); }); }); And the ajax call request this view def ajax_call(request): time.sleep(5) return JsonResponse() Now what i want is, if i make three multiple ajax call parallely on same view 'ajax_call'(in above example) i should get all the 3 responses in 5 seconds instead of 5*3=15 seconds that means the ajax call should work parallely . I tried the above format but i get the response back in (5*3=)15 seconds . So what change should i make in above jquery ajax call ? -
ModuleNotFoundError: No module named 'mysite.myapp'
I have prior experience with Django but have never run into such an error before. While trying to import my app module into urls.py of settings to add path. I am getting the above error. I have tried for solutions about relative imports but I am not able to fix it. My project structure is as follows: > mysite mysite __init__.py asgi.py settings.py urls.py wsgi.py myapp >migrations __init__.py admin.py models.py tests.py views.py -
Django how to only allow specific users
my models.py class Utilizador(AbstractBaseUser): id = models.AutoField(db_column='ID', primary_key=True) departamentoid = models.ForeignKey(Departamento, models.DO_NOTHING, db_column='DepartamentoID', blank=True, null=True) email = models.CharField(db_column='Email', max_length=255, blank=True, null=True, unique=True) nome = models.CharField(db_column='Nome', max_length=255, blank=True, null=True) class Inscrio(models.Model): id = models.AutoField(db_column='ID', primary_key=True) utilizadorid = models.ForeignKey('Utilizador', models.DO_NOTHING, db_column='UtilizadorID') participanteinfoid = models.ForeignKey('Participanteinfo', models.DO_NOTHING, db_column='ParticipanteinfoID') my view.py def ver_col(request, pk): user = Utilizador.objects.get(id=request.user.id) insc = Inscrio.objects.get(utilizadorid=request.user.id) if request.user.is_authenticated: if request.user.id==insc.utilizadorid.id: return render(request, 'main/ver_col.html', { "insc": insc }) So, I want users to see this "ver_col.html" but they are only allowed to enter the pages with the UtilizadorID (of the table Inscrio) associated with the user logged in at the moment (request.user.id or request.user). Basically I want them to only be allowed to enter the ones they created where Inscrio.utilizadorid = request.user.id -
How can i order post by last comment's date in django
enter code here> Blockquote View post on imgur.com View post on imgur.com -
Why I get a Json page response when it's supposed not to load the page in Django using AJAX?
My problem is well described in the title, so I'll leave the code below This is the HTML: (Sorry for the indentation but I don't often use Stackoverflow) {% block content %} <div class="col-8 mt-5"> <form id="createTaskForm" class="form-inline justify-content-center" method="post" date-url="{% url 'task_list' %}"> {% csrf_token %} {% for field in form %} <div class="mx-3"> {{ field }} </div> {% endfor %} <button id="createButton" class="btn btn-outline-success"> create </button> </form> </div> <div class="col-5 mt-5" id="taskList"> {% for task in tasks %} <div class="card mb-1"> <div class="card-body"> {{ task.title }} <button type="button" class="close float-right" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> </div> {% endfor %} </div> {% endblock %} Javascript file: $(document).ready(function(){ $('#createButton').click(function(){ var serializedData = $('#createTaskForm').serialize() $ajax({ url: $("#createTaskForm").data('url'), data: serializedData, type: 'post', success: function(response){ $("#taskList").append('<div class="card mb-1"><div class="card-body">' + response.task.title + '<button type="button" class="close float-right" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button></div></div>') } }) }); }); And finally the view from Django: from django.shortcuts import render, redirect from django.views.generic import View from .models import Task from .forms import TaskForm from django.http import JsonResponse from django.forms.models import model_to_dict class TaskList(View): def get(self, request): form = TaskForm() tasks = Task.objects.all() return render(request, 'task/task_list.html', context={'form':form, 'tasks':tasks}) def post(self, request): form = TaskForm(request.POST) if form.is_valid(): new_task = form.save() return … -
Datetime substraction django
I have a datetime as below. Voted datetime is the time when user has voted last time. The user can vote again only after 15 minutes. current_datetime = 2020-06-27 10:07:29.906931 voted_datetime = 2020-06-25 12:59:56.554216 time_diff = current_datetime - voted_datetime which gives the output: time_diff = 1 day, 21:07:33.352715 After getting time_diff i want to do is check if time_diff is greater than 15 mins. If time_diff is greater than 15 mins then return true else return the remaining time to be 15 mins so that i can pass the remaining time to template and display countdown uisng javascript. Any suggestions or related articles will be helpful. -
How to fix Pagination if not showing in PAge
I am creating an Order List page for my e-commerce project and I am trying to add pagination and limit the number of orders showing in one page to 6. I don't know the reason for not working or what might I be missing. Here is the views.py: class OrderList(LoginRequiredMixin, ListView): model = Order template_name = "user_orders.html" paginate_by = 6 def get(self, *args, **kwargs): try: order = Order.objects.filter(user=self.request.user, ordered=True) context = { 'orders': order } return render(self.request, 'user_orders.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have any orders") return redirect("/") Here is the template.html <table class="table"> <thead> <tr> <th scope="col">No.</th> <th scope="col">Order Reference</th> </tr> </thead> <tbody> <tr> {% for order in orders %} <th scope="row">{{ forloop.counter }}</th> <td>{{order.ref_code}}</td> </tr> {% endfor %} </tbody> </table> <!--Pagination--> {% if is_paginated %} <nav class="d-flex justify-content-center wow fadeIn"> <ul class="pagination pg-blue"> <!--Arrow left--> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} <li class="page-item active"> <a class="page-link" href="?page={{ page_obj.number}}">{{ page_obj.number}} <span class="sr-only">(current)</span> </a> </li> {% if page_obj.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> <span class="sr-only">Next</span> </a> </li> {% endif %} </ul> </nav> {% endif %} <!--Pagination-->