Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble paginating results from a 3rd party API in Django
I'm making a portfolio project where I'm using the Google Books API to do a books search, and the Django Paginator class to paginate the results. I've been able to get search results using a CBV FormView and a GET request, but I can't seem to figure out how to get pagination working for the API response. The solution I can think of is to append &page=1 to the url of the first search, then pull that param on every GET request and use that to paginate. The problem is, I can't figure out how to append that param on the first search, and I don't know how I'd increment that param value when clicking the pagination buttons. Here's what I've got now: Form: class SearchForm(forms.Form): search = forms.CharField(label='Search:', max_length=150) View: class HomeView(FormView): template_name = "home.html" form_class = SearchForm pageIndex = 0 def get(self, request, *args, **kwargs): # get submitted results in view and display them on results page. This will be swapped out for an AJAX call eventually if "search" in request.GET: # getting search from URL params search = request.GET["search"] kwargs["search"] = search context = super().get_context_data(**kwargs) # Rest API request response = requests.get( f'https://www.googleapis.com/books/v1/volumes?q={search}&startIndex={self.pageIndex}&key={env("BOOKS_API_KEY")}' ) response = response.json() … -
login required don't take effect - django
when i try to make this page view as required login it don't do that , it's open the page without ask for login this is my code views.py @method_decorator(login_required, name='dispatch') @register.inclusion_tag('survey/surveys.html', takes_context=True) def all_surveys(context): surveys = Survey.objects.all() return {'surveys': surveys} so what is the problem here any idea guys ? also anyone can explain why that happened thanks . -
Django ORM: SUM of grouped MAX
I am trying to translate this SQL query: SELECT user_id, SUM(max_score) FROM (SELECT user_id, MAX(score) AS max_score FROM submissions GROUP BY exercise_id, user_id) AS subquery GROUP BY user_id; where the table submissions has the columns user_id, exercise_id and score. Translating the inner subquery results in: subquery = ( Submission.objects .values("exercise", "user") .annotate(max_score=Max("score")) .values("user", "max_score") ) with a queryset like this: <QuerySet [{'user': 1, 'max_score': 27}, {'user': 2, 'max_score': 50}, {'user': 1, 'max_score': 16}, {'user': 3, 'max_score': 14}, {'user': 1, 'max_score': 14}, ...]> However, when I try to sum it up by user using subquery.annotate(total_score=Sum("max_score")) I get: FieldError: Cannot compute Sum('max_score'): 'max_score' is an aggregate How could I implement this in Django ORM instead of an inefficient solution like this: scores = defaultdict(int) for row in subquery: scores[row['user']] += row['max_score'] -
How to check if a booleanfield ina django modelform is true and add whatever it is true under to a list?
I am trying to create an e-commerce site (CS50 Project 2) that allows the user to add a listing item to their watchlist. I have decided to use a django modelformw ith a booleanfield that corresponds with the WatchList model to do this. I have created the form but am not sure how to check if it is true and save the listing to the WatchList model. views.py def listing(request, id): listing = Listings.objects.get(id=id) listing_price = listing.bid sellar = listing.user watchlist_form = WatchListForm() watchlist_form = WatchListForm(request.POST) if watchlist_form == True: listing.add() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "watchlistForm": watchlist_form }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "watchlistForm": watchlist_form }) models.py class WatchList(models.Model): listing = models.ManyToManyField(Listings) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") add_to_watchlist = models.BooleanField(default=False) Thank you so much for all the help! Please let me know if you need any more code. -
aws lambda zappa deployment with django : ModuleNotFoundError
I ve created the most basic django website. Nothing except django-admin startproject hello cd hello python manage.py makemigrations python manage.py migrate The command python manage.py runserver gives me the default website with access to admin with /admin url. But when I deploy it with zappa deploy, i get a "Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 500 response code." And when I try to go the the url provided by zappa, i get No module named 'hello.urls'. I also have the same error when i try to go to the zappa_url/admin page. The urls.py file only contains : from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] How can i solve this so my website is up and running? -
Why am I automatically logged out of django admin
I deployed a Django website with Nginx on DigitalOcean and now I'm having the problem that I can login to admin but if I'm logged in for a short time I get logged out automatically -
Django ORM multiple tables query
I trying to make some queries in Django ORM (migration from SQL). My models looks like this class Iv2(models.Model): s_id = models.AutoField(primary_key=True) l_eid = models.CharField(max_length=265) t_id = models.CharField(max_length=265) class Sv2(models.Model): id = models.AutoField(primary_key=True) s_id = models.OneToOneField(Iv2, on_delete=models.PROTECT) gdd = models.DateTimeField(default=datetime.now) class Ev2(models.Model): id = models.OneToOneField(Iv2, to_field='l_eid', on_delete=models.PROTECT) s_id = models.ForeignKey(Iv2, on_delete=models.PROTECT) car = models.CharField(max_length=265) I want to write a query, given t_id. I want get corresponding Sv2.gdd and Ev2.car I'm thinking to get s_id and l_eid with the t_id. And when I get s_id. I can query Sv2 and with l_eid I can query Ev2. Is it possible to achieve everything with one ORM query ? can prefetch/select_related work here? -
Remove django inline Admin label row labels
I have the following TabularInline: class ProcessVariableInlineAdmin(TabularInline): model = ProcessVariable fields = ( 'variable', 'station_rank',) readonly_fields = ( 'variable', 'station_rank', ) ... and would like to remove the small line variables on each row: I tried poking around on the django docs for TabularInline but came up short. Is there a way to do this that I'm overlooking? Thank you in advance! -
How to create dynamic reports for Django
I have looked around a lot and have seen many tools like jasper reports, Birt, pentaho, kool report etc etc but all are in java or php, none in python. That is not the problem either because as I have seen and tested with Jasper and Birt you can connect to them with their API but there are no good resources as to how do I integrate those with Django backend using Django Rest Framework or with my frontend. Jasper has Visualize Js but is paid only, BIRT has from my experience terrible report design tool, you can't even resize or move a simple text field, there seems to be a way to do that with css, I think but why? Jasper's report designer is pretty good but again no good resource as to how to use it. I want to use it in my student management sysrem where I can print fee vouchers report cards admission slips, general reports, detail reports etc but how do I tell jasper which student or which data to use, it just uses whatever is specified in the designer. Any guidance on this matter would be immensely helpful as I am learning all this … -
Can't change value in model object with button
I need to change the quantity value of item then user pressed button on page. My code works, but only one time: if I press button at the first time, value is changing, but at second or third time nothing happens views.py def item(request, item_id): item = Item.objects.get(id=item_id) context = {'item': item} return render(request, 'main/item.html', context) def change_quantity(request, item_id): item = Item.objects.get(id=item_id) context = {'item': item} if request.method == 'GET': item.quantity +=1 return render(request, 'main/item.html', context) urls.py urlpatterns = [ path('', views.index, name='index'), path('categories/', views.categories, name='categories'), path('categories/<category_id>/', views.category, name='category'), path('topics/', views.topics, name='topics'), path('categories/category/<item_id>/', views.item, name="item"), path('categories/category/item/change_quan/<item_id>/', views.change_quantity, name='change_quan') models.py class Item(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) title = models.CharField(max_length = 150) description = models.CharField(max_length = 250) text = models.TextField() photo1 = models.ImageField(upload_to = 'static/') photo2 = models.ImageField(upload_to = 'static/') small = False quantity = 1 def __str__(self): return self.title item.html {% extends "main/base.html" %} {% load static %} <body> {% block content %} <li> <img src="{{item.photo1.url}}"> <img src="{{item.photo2.url}}"> <p> Название {{ item.title}} </p> <p> Краткое описание {{ item.description | linebreaks }} </p> <p> Большое описание {{ item.text | linebreaks }}</p> <p> Количество {{ item.quantity }} </p> <form action="{% url 'main:change_quan' item.id %}" method="get" > {% csrf_token %} <button type="submit" … -
Python deploying django with django channels on heroku
I have been trying to deploy my application on heroku with django channels and I always get the following error 2022-05-26T20:09:58.137436+00:00 app[web.1]: ModuleNotFoundError: No module named 'core' I have seen previous questions such as Deploying asgi and wsgi on Heroku but even when following these steps I can't get the deployment to work. My channel layers in settings.py: ASGI_APPLICATION = "server.asgi.application" CHANNEL_LAYERS = { 'default': { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')] }, 'ROUTING': 'server.routing.channel_routing', } } My asgi.py: import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = get_asgi_application() My wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') application = get_wsgi_application() My Procfile web: daphne server.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 chatworker: python manage.py runworker --settings=server.settings -v2 My file structure server | |_ _ chat | | | |_ __init__.py | | | |_ admin.py | | | |_ consumers.py | | | |_ models.py | | | |_ routing.py | | | |_ urls.py | | | |_ views.py |_ _ server | | | |_ __init__.py | | | |_ asgi.py.py | | | |_ routing.py | | | |_ settings.py | | | |_ urls.py | | | |_ wsgi.py | |_ _ … -
Localize dependency model name
I want to localize the DJANGO OAUTH TOOLKIT app and models names. But as it's a dependency, it's not included in my project as a custom app and I cannot change the verbose name from verbose_name = "Django OAuth Toolkit" to verbose_name = _("Django OAuth Toolkit") I could just include oauth2_provider as a entire app inside my project, but in case we need to update that dependency with a new version published in github, we should replace the entire folder. Can I just override the oauth2_provider models verbose names without creating a new Class that inherits from the original oauth2_provider class that exists as a project dependency? -
HighlightJS not highlighting certain code fragments
I'm using HighlightJS to format code that's being stored in a model's TextField of my Django application. Here is the template HTML: <pre> <code class="{{ compiler.highlight_js_alias }}">{{ compiler.unit_test_boilerplate_code }}</code> </pre> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/default.min.css" <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script> <script>hljs.highlightAll();</script> Example output: <pre> <code class="ruby hljs language-ruby"> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Person</span> : <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span> ( <span class="hljs-params"> <span class="hljs-variable language_">self</span>, name, age</span> ): <span class="hljs-variable language_">self</span> .name = name <span class="hljs-variable language_">self</span> .age = age me = Person( <span class="hljs-string">"Nathan"</span> <span class="hljs-number">32</span> ) print(me.name) </code> </pre> Why are certain fragments not highlighted? Thank you for any advice. -
Do I need to have AWS CLI to use Boto3?
I have a Django application that needs to use Boto3 to create and manage EC2 instances. When I host the Django application, do I need to install AWS CLI in the server to use Boto3 in the Django application? -
Django Rest Framework Nested Serializers with multiple types of Query Filters
Sorry for the not so descriptive title, hard to put into words what I am trying to do. My Models have various Many to Many relationships. I am trying to make my Serializers act in a very similar way to the queries I listed out below. Essentially, I am looking to get my TeamStats Model Serialized in various ways. If I need the whole leagues stats, I filter by season, if just a single team, I filter by team etc. These queries will also be read only, they won't be written to, they are just for viewing purposes on the front end. In addition, I need the serializer to be nested in such a way that whatever is filtering the query, is top data in JSON. For example, if I was doing TeamStats by Season, I would have Division Nested inside of Season, Team nested inside of Division. If I was just calling TeamStats by Division, I would have just Team nested inside of Division. Models class BaseModel(LifecycleModelMixin, models.Model): date_modified = models.DateTimeField(auto_now=True) date_created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: abstract = True class SeasonTest(BaseModel): name = models.CharField(max_length=50) class DivisionTest(BaseModel): name = models.CharField(max_length=50) seasons = models.ManyToManyField(SeasonTest, through='SeasonDivision') … -
Change webpage logo for every user in django
How can I change website logo for every other user login into django platform? For example: User-A when login, will see different logo on website, while User-B will see different and so on. -
Django exclude only works with get_context_data
Can I use exclude() without having to use get_context_data with generic class based views? I want to exclude the is_removed for the soft delete. I have seen examples where it's not used. It only works with a form variable school_district_model_form with an SchoolApplicationModelForm in get_context_data and using it in the template. Below works. I was expecting the default form variable in the template to exclude the fields and it still includes all fields. models.py class SchoolDistrictModelForm(forms.ModelForm): class Meta: model = SchoolDistrict exclude = ("is_removed",) view.py class SchoolDistrictCreateView(SchoolDistrictBaseView, CreateView): """View to create a new school district""" def get_context_data(self, **kwargs): context = { "school_application_model_form": SchoolApplicationModelForm(), } return context schooldistrict_form.html <div class="container d-flex justify-content-center mt-5" style="width: 25%;"> <div class="col mt-5"> <form action="" method="post"> {% csrf_token %} <table class="table"> {{school_district_model_form.as_table}} </table> </form </div> </div> -
django add likes user blog post
am quite new to django and am trying to make a blog in django but cant figure out how to add a few key features. How can i make my code so other ppl also can make blog posts ? how can i add a like/dislike button with counter on all blogposts created? How can i add so you can add pictures to the posts so they show on the front page so you dont have to click in to the post to see them? Would be very appreciated if someone could help me with this since am not quite sure how to do it. code is below: This is my code: APP Folder views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from .models import Post from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to … -
How to display the total number of votes in a Poll?
I have a simple voting application. models: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text results.html: {% extends 'base.html' %} {% block content %} <h1 class="mb-5 text-center">{{ question.question_text }}</h1> <ul class="list-group mb-5"> {% for choice in question.choice_set.all %} <li class="list-group-item"> {{ choice.choice_text }} <span class="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span> </li> {% endfor %} </ul> <a class="btn btn-secondary" href="{% url 'polls:index' %}">Back To Polls</a> <a class="btn btn-dark" href="{% url 'polls:detail' question.id %}">Vote again?</a> {% endblock %} How to make the total number of votes for each question so that you can display total: and the total number of votes for this poll at the bottom. -
Refused to apply css styles in my Django App, because its MIME type its not supported
I have a serious problem with my Django application and is that I do not load the styles in my app, the error I get in console is as follows: "It has been rejected to apply the style of 'http://127.0.0.1:8000/static/static/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled". "ailed to load resource: the server responded with a status of 404 (Not Found)" Settings.py: """ Django settings for DjanPro project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from email.mime import application from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # IMPORT MODULES import os # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-5%wdpom7_!0w5wx&qfv2_e@riio6&dqv$h!h_8ly_nk^2=w!pz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'clase', 'index', 'accounts', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
How to avoid the magnifying zoom my cropbox has in Cropper js?
Im using Cropper JS by fengyuanchen. When my cropper loads everything looks ok. But when I resize the window the cropbox zooms in the image. This is how it loads: And this is how it ends after the window resizing: The is a zoom effect in the cropbox that I don't want. I'd like to be able to resize the window and avoid the zoom effect in the cropbox. Below are my cropper and container specifications: Cropper: croper() { const image = document.getElementById('image'); const cropper = new Cropper(image, { responsive:false, autoCropArea:1, zoomable:false, movable: false, aspectRatio: NaN, viewMode: 2, crop(event) { console.log("***********************************"); console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); this.data = this.cropper.getData(); document.getElementById("demo").innerHTML = JSON.stringify(this.data); var contData = cropper.getContainerData(); //Get container data }, }); cropper.setCropBoxData({ height: contData.height, width: contData.width }) //set data } Container: <div class="col-md-8 col-sm-6 grid-margin stretch-card" id="image_box" align="center"> <div class="card text-center" style=" overflow: hidden; height: 100vh;"> <!-- <div class="card-body"> --> <!-- <label id="file-drag"> --> <img id="image" style="max-width: 100%; display: block; " src="static/template/{{img}}.png" alt="Preview"> <span id="preview">La vista previa de la imagen de la plantilla irá aquí</span> <!-- </label> --> <!-- </div> --> </div> </div> Thanks! -
Django + Gunicorn + Nginx + Python -> Link to download file from webserver
On my webpage served by a Debian web server hosted by amazon-lightsail behind nginx and gunicorn, a user can send a request to start a Django view function. This function add some work to a background process and check every 5s if the background process created a file. If the file exists, the view sends a response and the user can download the file. Sometimes this process can take a long time and the user get a 502 bad gateway message. If the process takes too long, I like to send the user an email with a link where he can download the file from the web server. I know how to send the email after the process is finished, but I don't know how to serve the file to the user by a download link. This is the end of my view function: print('######### Serve Downloadable File #########') while not os.path.exists(f'/srv/data/ship_notice/{user_token}'): print('wait on file is servable') time.sleep(5) # Open the file for reading content path = open(filepath, 'r') # Set the mime type mime_type, _ = mimetypes.guess_type(filepath) # Set the return value of the HttpResponse response = HttpResponse(path, content_type=mime_type) # Set the HTTP header for sending to browser response['Content-Disposition'] … -
How can I send email using python with google workspace
I just signed up for the Google workspace business starter because of lots of recommendations from people, I would like to know how possible is it to send email via my backend API using Django, I've searched for it online but nothing comprehensive or direct, try to contact their support but not available. Thanks in advance -
ValueError: I/O operation on closed file in Django and DRF when saving data to model
I am trying to save a file to the Django instance the following way: class SomeName(ListCreateAPIView): queryset = fileUpload.objects.all() serializer_class = fileUploadSerializer def create(self, request, *args, **kwargs): file = serializer.validated_data["file"] object = fileUpload.objects.create( file_local_storage=file, file=file, ) ..... The models is class fileUpload(models.Model): fileName = models.CharField(max_length=200, unique=True, blank=True) file = models.FileField(storage=PrivateMediaStorage()) file_local_storage = models.FileField(upload_to="uploads/", blank=True) The error I get is ValueError: I/O operation on closed file in Django and DRF when wrting data -
How Can Update Python Version to be the same with the version on Cpanel Hosting Python App
I have fully developed my Django App using Python Version 3.9.1 and after purchasing Cpanel Python Hosting I realized that there was no version 3.9.1 rather the closer version on their Python App Installation was Version 3.9.12. I am confused on which version to choose that can work perfectly without errors. I have opened a Ticket to their support but no response till now so I need your professional advise.