Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SEO for every blog post in Django Python framework
I am working on Django application for rendering blog posts on various topics. As you know, in WordPress Yoast / math rank plug in there is an option for SEO for every blog post using meta tags. My question is can we use meta tags in the {% block content %} within the body of the blog post in Django, or otherwise. Bear in mind that Django documentation recommends, using meta tags in the base.html file and in the head section only. If we use the meta tags in the head section in HTML, then how it can be altered for each and every blog post. Thanks -
overriding behavior when 'submit' button clicked in Django
I am trying to develop a tennis ladder Django website that has classes for Player, Match, and Ladder. I have imported some dummy data and also have Create, Delete, Update, and List views for players and matches. But when a player is created, I need to also create a new Ladder object that will contain the new state of the ladder. Likewise, when a player is deleted (or is unavailable due to injury), the ladder state must change, and a new ladder is created. (I want to retain a historical record of each ladder state in case something is done by mistake ... this lets me revert to an earlier verson of the ladder). Finally, ladder positions change if a challenger defeats his or her opponent. Here's my question. How do I trigger such code in a DeleteView (e.g. deleting a player). For a CreateView, I use this approach: class PlayerCreateView(CreateView): model =Player num_players = Player.objects.count() context_object_name = 'player' fields = ['ranking', 'first', 'last', 'cell', 'email', 'availability'] template_name = 'player_create.html' success_url = reverse_lazy('players') def form_valid(self, form): response = super().form_valid(form) num_players = Player.objects.all().count() ladders = Ladder.objects.all() # <CALL CODE TO CREATE NEW LADDER OBJECT> return response But what about other scenarios … -
Django-channels Problems
Good day, I am currently learning how to implement WebSocket with Django and I have encountered some roadblocks. I'm using uvicorn and Django channels for my project, I am trying to implement a feature whereby I would be able to retain the previous message that I have been sent in a group chat. But this is my errors anytime I try to send messages. Traceback (most recent call last): File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 247, in run_asgi result = await self.app(self.scope, self.asgi_receive, self.asgi_send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/routing.py", line 116, in __call__ return await application( ^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/utils.py", line 50, in await_many_dispatch await dispatch(result) File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/asgiref/sync.py", line 479, in __call__ ret: _R = await loop.run_in_executor( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/db.py", line 13, in thread_handler return super().thread_handler(loop, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/asgiref/sync.py", line 538, in thread_handler return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/consumer.py", line 125, in dispatch handler(message) File "/Users/bottgabriel/Desktop/Practices/py/chatapp/server/venv/lib/python3.11/site-packages/channels/generic/websocket.py", line 59, in … -
How can I perform a SQL JOIN using Django ORM when the models are not related?
I have two models that look like this: (tableA) class ModelA(models.Model): student_id = models.TextField() name = models.TextField() age = models.IntegerField() (tableB) class ModelB(models.Model): student_id = models.TextField() report_card_file_id = models.TextField() # Other fields in ModelB I created a sql query to join them that looks like this: SELECT tableA.*, tableB.report_card_file_id FROM tableA LEFT JOIN tableB ON tableA.student_id = tableB.student_id where tableB.report_card_file_id is not null; But how can I transform this query into Django orm so that I will have a QuerySet with student_id, name, age, and report_card_file_id? Here is some code I have, but I am not sure how to fill in the ?: a = ModelA.objects.all() a = a.annotate(?) I also tried using .raw() but then I get a RawQuerySet instead of just a QuerySet. -
django queryset that counts occurrences of sub string in field
I have a model called Animal that contains a field called text that starts with the animal name followed by optional text e.g. cat - grey long hair class Animal: text = models.TextField() I want to count the occurrences of text that start with cat, dog or fish and return that count per animal category. I assume something like this wold work: queryset = models.Animal.objects.all() animal_summary = ( queryset .annotate( cats=Count( Case( When(text__startswith="cats", then=1), default=0, output_field=IntegerField(), ) ) ) .annotate( dogs=Count( Case( When(text__startswith="dogs", then=1), default=0, output_field=IntegerField(), ) ) ) .annotate( fish=Count( Case( When(text__startswith="fish", then=1), default=0, output_field=IntegerField(), ) ) ) .values('cats', 'dogs', 'fish') ) return {"animal_count": animal_summary} But it appears to count the number of entries irrespective of the sub-string. -
NoReverseMatch error following Python Crash Course Book
I have been working through the Django chapter of the Python Crash Course book and have run into an issue with the 'Create new entry' page. When I try to access the page it gives me this error: NoReverseMatch at /topics/2/ Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/\\Z'] and displays an error on my topic.html file: {% extends 'learning_logs/base.html'%} {%block content%} <p>Topic: {{topic}}</p> <p>Entries:</p> <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a> </p> <ul> {%for entry in entries%} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {%empty%} <li>There are no entries for this topic yet.</li> {%endfor%} </ul> {%endblock content%} As followed in the book I also wrote the view and URL path for the page def new_entry in views.py: def new_entry(request, topic_id): #add new entry for particular topic topic = Topic.objects.get(id=topic_id) if request.method != 'POST': #no data submitted, create blank form form = EntryForm() else: #POST data submitted, process data form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit = False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) #display blank or invalid form context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) urls.py urlpatterns = [ #home page path('',views.index, name='index'), #topics … -
How to create tables in different schemas using Geodjango and Postgres/ PostGIS?
My question is very similar to the question asked and answered here, using the Meta class and db_table = 'schema"."tablename' approach to use multiple schemas: How to create tables in a different schema in django? This solution worked for me under the standard Django project framework (using django.db models); however, once I attempted to use this method in a Geodjango project (using django.contrib.gis.db models), I received the following error when trying to migrate a model that included geospatial fields (PointField, LineStringField, and PolygonField): django.db.utils.ProgrammingError: syntax error at or near "." LINE 1: CREATE INDEX "schema"."tablename_geom_point_id" ON "sch... How can I implement this approach using Geodjango to leverage the benefits of schemas directly in the model? Example code of what I tried and resulted in the error message has been presented below. models.py import uuid from django.contrib.gis.db import models class TableName(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) ... geom_point = models.PointField(blank=True, null=True) geom_line = models.LineStringField(blank=True, null=True) geom_polygon = models.PolygonField(blank=True, null=True) ... class Meta: managed = True db_table = 'schema"."tablename' Thank you for any support you can provide! -
Django 4.2: Pagination doesn't work for me
I'm trying to use pagination in Django. Here is my code: Views.py from catalog.models import Book from django.views import generic class BookListView(generic.ListView): """Display authors per 10""" model = Book paginate_by = 10 author_list.html {% extends "catalog/base.html" %} {% load static %} {% block content %} <h1> Authors </h1> {% if perms.catalog.can_add_author %}<p> <a href="{% url "author-create" %}"> New author </a></p>{% endif %} <figure> <img src="{% static "catalog/images/author.png" %}" alt="library" width=300/> </figure> {% if author_list %} <ul> {% for author in author_list %} <li> <a href="{{author.get_absolute_url}}"> {{author}} </a> </li> {% endfor %} </ul> {% else %} <p> No author. </p> {% endif %} {% endblock content %} base.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static "catalog/css/style.css" %}"/> {% block title %}<title> Local Library </title>{% endblock title %} </head> <body> {% block sidebar %} {% if user.is_authenticated %} <p> <u> Hello {{user.get_username}} </u> </p> {% endif %} <nav> <ul> <li> <a href="{% url "index" %}"> Home </a> </li> <li> <a href="{% url "books" %}"> Books </a> </li> <li> <a href="{% url "authors" %}"> Authors </a> </li> {% if perms.catalog.can_see_borrowed_book %} <li> <a href="{% url "borrowed-book" %}"> Books borrowed </a> </li> {% … -
Jinja+Django. Uncaught SyntaxError: Unexpected token '{'
I'm loading js from another file, where i has a line this.data = {{ data.as_list | safe }};. When it is right in html tag, everything works fine. But when it's in another file, it throws an error "Uncaught SyntaxError: Unexpected token '{'". Appreciate any answers. <div class="recipe"> <div class="recipe-page-pointer" id="recipe-left-page-pointer"> <svg width="28.5" height="28.5" viewBox="0 0 28.5 28.5"> <path fill="#FFFFFF" d="M 28.5 0 L 0 14.25 L 28.5 28.5 Z"></path> </svg> </div> <div id="recipe-page-content"> <span></span> </div> <div class="recipe-page-pointer" id="recipe-right-page-pointer"> <svg width="28.5" height="28.5" viewBox="0 0 28.5 28.5"> <path fill="#FFFFFF" d="M 0 0 L 28.5 14.25 L 0 28.5 Z"></path> </svg> </div> <script src="{% static 'dishes/js/dish-details.js' %}"></script> </div> -
Dockerizing Django with Rabbitmq and Redis - Ports don't work
I'm dockerizing a Django project which uses Celery, Rabbitmq and Redis. Celery can't connect to Rabbitmq: consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. And Redis (used for cache) doesn't work either. Error while opening a cached url: Error 111 connecting to 127.0.0.1:6379. Connection refused. docker-compose.yml: services: rabbitmq: container_name: rabbitmq image: rabbitmq:latest networks: - main ports: - "5672:5672" restart: always environment: - RABBITMQ_DEFAULT_USER=guest - RABBITMQ_DEFAULT_PASS=guest celery_worker: container_name: celery_worker command: celery -A zwitter worker -l INFO build: . depends_on: - app - rabbitmq environment: - C_FORCE_ROOT=true networks: - main restart: always redis: container_name: redis image: redis:latest ports: - "6379:6379" volumes: - cache:/data command: redis-server --save 60 1 restart: always app: container_name: app build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/src/ ports: - "8000:8000" networks: main: volumes: cache: Celery settings: # ... CELERY_BROKER_URL = "amqp://guest:guest@localhost:5672/" # ... Cache settings: CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://127.0.0.1:6379", } } All containers are all up. -
Building a Django Q object for query
I am having an issue wrapping my head how to build a Q query in Django while setting it up as a dict. For example: I have a list of pks for properties and I am trying to filter and see if those pks are associated with either item = ['6', '21', '8', '13', '7', '11', '10', '15', '22'] I am trying to build a Q object that states: Q('accounts_payable_line_item__property__pk__in' = properties) | Q('journal_line_item__property__pk__in' = properties) while defining it in a dict I can pass to the queryset like so: If I define a filter dict and then create values it looks like this but it doesn't create the Q: filter_dict = {} filter_dict['accounts_payable_line_item__property__pk__in'] = properties filter_dict['journal_line_item__property__pk__in'] = properties queryset = queryset.select_related('accounts_payable_line_item', 'journal_line_item').filter(**filter_dict).order_by('-id') -
Can I work around running Pygame in Django?
Project's repository: https://github.com/StaryGoryla/BoardGameSite A little context: I have recently started learning coding, and I like it a lot. For my first project I decided to make a place for playing board games online. I made a Django server, learnt some Pygame, made a desktop app using PyQT, auth system, etc., but didn't think to check if running Pygame in a browser is doable. I have just checked it and apparently it's very hard if you are new to Python and know nothing about JS etc., so my main question is: Would you say it makes sense to learn how to work around it (considering that I am new to coding in general), or would it be better to have the game in a separate window, that would be opened via Django or desktop app? I also have a couple questions about the project itself, because I got stuck on implementing some functions: I added a CustomUser model to Django that has a is_online flag as a field. When I run shell I see that the accounts have been migrated well and that all of them have it set to False, but I can't change it during logging in/out. In login … -
fetch(...) not stopping to fetch with spotify api
This function - to get access to what the current listener is listening to via the spotify API is contantly fetching: const getCurrentSong = () => { fetch('/spotify/current-song').then((response) => { // check if not ok if(!response.ok){ return {} } else { return response.json(); } }).then((data) => { setSong(data); console.log(data); }); } When inspecting, I can see the JSON data being printed out constantly. With other fetch instructions, this is not the case. This is the full code: room.js: import React, { useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { Grid, Button, Typography } from "@mui/material"; import { Link } from 'react-router-dom'; import CreateRoomPage from './CreateRoomPage'; function Room(props) { const [votesToSkip, setVotesToSkip] = useState(3); const [guestCanPause, setGuestCanPause] = useState(false); const [isHost, setIsHost] = useState(false); const [showSettings, setShowSettings] = useState(false); const [spotifyAuthenticated, setSpotifyAuthenticated] = useState(false); const [song, setSong] = useState({}); const params = useParams(); const roomCode = params.roomCode; const authenticateSpotify = () => { // send the request fetch('/spotify/is-authenticated').then((response) => response.json()).then((data) => { setSpotifyAuthenticated(data.status); if (!data.status) { fetch('/spotify/get-auth-url').then((response) => response.json()).then((data) => { window.location.replace(data.url); // redirect to the spotify authorisation page }) } }) } const getRoomdetails = () => { fetch('/api/get-room' + '?code=' + roomCode).then((response) => { … -
celery autodiscover_tasks() not discover all packages but some packages
i have project with django and celery and using app.autodiscover_tasks() autodiscover was work and discover all packages and after some changes autodiscover_tasks not discover all package but discover some packages no error seen what happend? celery==4.* , django==3.* , python3.9 -
How to fix Cannot resolve keyword 'username' into field. Choices are: id, profile_image, status, user, user_id
I am a beginner in Django, and I have an academy project. I extended the User model by adding some fields to it and used them in a form to allow users to log in. When I try it, it works, but when I submit the form, I get this error: Cannot resolve keyword 'username' into field. Choices are: id, profile_image, status, user, user_id I know this question is repetitive, but all the cases I've seen were not similar to mine. models.py from django.contrib.auth.models import User from django.db import models STATUS_CHOICES = ( ('', 'What is your use of the academy?'), ('student', 'Student'), ('teacher', 'Teacher'), ('author', 'Author'), ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(null=True, default='profile.jpg') status = models.CharField( max_length=150, choices=STATUS_CHOICES, default='What is your use of the academy?', ) USERNAME_FIELD = 'user__username' def __str__(self): return self.user.username views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import RegisterUserForm # Create your views here. def profile(request): return render( request, 'common/profile.html' ) class RegisterView(CreateView): form_class = RegisterUserForm success_url = reverse_lazy('login') template_name = 'registration/register.html' urls.py from django.urls import path, include from django.contrib.auth.views import LoginView from .forms import UserLoginForm from . import views urlpatterns = [ path('login/', … -
Django HttpResponseRedirect() doesn't work - it doesn't redirect to the page
I was trying to implement the function listing(request, listId) that when user wants to post a comment without login, it will be redirected to the login page. This is the code of my listing(request, listId) in views.py def listing(request, listId): if request.method == "POST": if request.user.is_authenticated: # some code here to manipulate data else: HttpResponseRedirect(reverse("login")) return render(request, "auctions/listing.html", { "listing":Listing.objects.get(pk=listId), "comments": Listing.objects.get(pk=listId).itemComment.all(), "bids": Listing.objects.get(pk=listId).itemBid.all(), "bidCount": Listing.objects.get(pk=listId).itemBid.count(), "currentPrice": currentPrice, "isValidBid": True } ) Here is the urls.py, note that the name of login url is "login" from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("add_listing", views.addListing, name="addListing"), path("listing_<int:listId>", views.listing, name="listing") ] The problem is each time when I click the submit button without login, it doesn't redirect me to the login page but stays in the original page, which is not what I expect. I also tried to replace HttpsResponseRedirect(reverse("login")) with redirect("login") and type the whole url in like HttpsResponseRedirect("/login"). Both of them didn't work. Thanks in advance for any help! -
Malloc Error: cannot allocate memory while running Django Application
I'm currently running 3 separate Django sites on a linux (debian 9) server. I am currently receiving the following error: Wed Sep 20 15:53:23 2023 - malloc(): Cannot allocate memory [core/utils.c line 1796] Wed Sep 20 15:53:23 2023 - !!! tried memory allocation of 512 bytes !!! When attempting to load a page on one the sites. This error message is found within my logfile for UWSGI. I receive no errors in my django logs. 2/3 sites are working fine, so I don't believe the system as a whole is struggling with memory. This error happened following our last push to the server which included a change in code that added matplotlib as an import. (Yes, I have already changed matplotlib to use the "Agg" backend to prevent a memory leak). I am aware this is not enough information for a full answer, but does anyone have any ideas as to direction? I am not finding any history of people with a similar error message online (not one that has to do with core/utils). Noting also that this did not happen on our development servers, which are about half the strength of this server. -
how to filter and sort fields in django-filter that are not in Django model?
I am trying to filter values in 2 fields that I am creating in my serializer and I am wondering how to add last_run and lat_status to filtering and orting fieldset but when I am adding them I get Cannot resolve keyword 'last_status' into field. error. Is there any option to annotate these 2 fields in my ListAPIView so I can sort and filter by them sample API data { "id": 2, "user": 1, "project": 3, "last_run": "17-08-2023 16:45", "last_status": "SUCCESS", "name": "test spider", "creation_date": "10-08-2023 12:36", }, models.py class Spider(models.Model): name = models.CharField(max_length=200, default="", unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name='project_spider') creation_date = models.DateTimeField(default=timezone.now) serializers.py class SpiderListSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) last_run = serializers.SerializerMethodField() last_status = serializers.SerializerMethodField() class Meta: model = Spider fields = "__all__" def get_last_run(self, instance): return get_last_spider_status(instance.id)[0] def get_last_status(self, instance): return get_last_spider_status(instance.id)[1] filters.py from django_filters import rest_framework as filters from .models import Spider class SpiderFilter(filters.FilterSet): name = filters.CharFilter(field_name='name', lookup_expr='icontains') user = filters.NumberFilter(field_name='user__id', lookup_expr='icontains') project = filters.NumberFilter(field_name='project__id', lookup_expr='icontains') creation_date = filters.DateFilter( field_name='creation_date', input_formats=['%d-%m-%Y'], lookup_expr='icontains' ) class Meta: model = Spider fields = [] views.py class SpiderListView(ListCreateAPIView): permission_classes = [IsAuthenticated] serializer_class = SpiderListSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = SpiderFilter ordering_fields = … -
__str__ returned non-string (type NoneType) I don't even know where the problem
I was making which user allowed to do what and which doesn't allowed by watching a video series. After I did something I couldn't delete one user. I added one more user to see could I delete that one and I deleted it. I even don't know where is the problem. decoraters.py from django.shortcuts import redirect from django.http import HttpResponse def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not autherized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == "customer": return redirect('user') if group == "admin": return view_func(request, *args, **kwargs) return wrapper_function models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.IntegerField(null=True) email = models.EmailField(null=True) profile_pic= models.ImageField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name I don't know should I share anymore information. I hope someone can fix my problem and tell me why I … -
How can I Make Django Filter With Field-Choices?
Hello my friends, I am now facing a problem when I create a filter on the Category page, which is a Page not found (404) error, and I do not know what the exact problem is. Can anyone help please? models.py: class categorie (models.Model): title = models.CharField(max_length=100 , null=True ) slug = models.SlugField(blank=True,allow_unicode=True,editable=True) def save(self , *args , **kwargs): if not self.slug: self.slug = slugify(self.title) super(categorie , self).save( *args , **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('category', args=(self.slug,)) class software (models.Model): LICENSE_CHOICES = [ ('free', 'free'), ('opensource', 'opensource'), ('demo', 'demo'), ] category = models.ForeignKey(categorie,on_delete=models.CASCADE,null=True) slug = models.SlugField(blank=True,allow_unicode=True,editable=True) title = models.CharField(max_length=50 , null=True) license = models.CharField(max_length=100 ,choices=LICENSE_CHOICES, null=True,blank=True) picture = models.ImageField(upload_to='img' , null=True) description = RichTextUploadingField(null=True,blank=True) created_at = models.DateField(auto_now_add=True) auther = models.CharField(max_length=100 , null=True) download = models.URLField(null=True) def save(self , *args , **kwargs): if not self.slug: self.slug = slugify(self.title) super(software , self).save( *args , **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', args=(self.slug,)) filter.py: import django_filters from .models import software class SoftwareFilter(django_filters.FilterSet): license= django_filters.ChoiceFilter( choices=[ ('free', 'free'), ('opensource', 'opensource'), ('demo', 'demo'), ], label='Choose from the list', field_name='license', ) class Meta: model = software fields = ['license'] views.py: from django.shortcuts import render , get_object_or_404 , Http404 from django.http import … -
Python - HTML/JQUERY Pagination
Hello friends and colleagues in the community, I am trying to make a pagination bar, the problem is that using a button I can only print/function the first page but not the remaining pages. Pagination This is my code: <div> <script type="text/javascript"> $(function () { $("#descargar").DataTable({ "lengthChange": true, "searching": true, "ordering": true, "info": true, "autoWidth": false, "responsive": true, language: { "lengthMenu": "Mostrar _MENU_ registros", "zeroRecords": "No se encontraron resultados", "info": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros", "infoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros", "infoFiltered": "(filtrado de un total de _MAX_ registros)", "sSearch": "Buscar:", "oPaginate": { "sFirst": "Primero", "sLast":"Último", "sNext":"Siguiente", "sPrevious": "Anterior" }, "sProcessing":"Procesando...", }, }) $("#descargar").ready(function() { $('.fa-binoculars').on('click', function() { var codigoPartner = $(this).data('codigo-partner'); var url_seguimiento = "/seguimiento/" + codigoPartner; window.location.href = url_seguimiento; }); }); }); </script> </div> I think the problem could lie in the DataTable but I'm not sure. I would greatly appreciate your help. What I hope is that the button works on the other pages (pagination) -
How to change background image in django web app using the admin interface?
I want to change the background of the home page in my web app but using the admin interface. I made a model specific for the backgrounds of each section used in the home page. this was my first approach, which is editing the save function and give the image name the id name as 1.jpg then reffering to 1.jpg in my html file Here is the my ImageHome model for the images in the background: def save_home_image(instance, filename): upload_to = 'Images/' ext = filename.split('.')[-1] # get filename if instance.name: filename = 'Home_Pictures/{}.{}'.format(instance.name, ext) return os.path.join(upload_to, filename) def custom_upload_to(instance, filename): ext = filename.split('.')[-1] return os.path.join('Images', 'Home_Pictures', f'{instance.name}.{ext}') class ImageHome(models.Model): name = models.CharField(max_length=500, null=True, blank=True) image_home = models.ImageField( upload_to=custom_upload_to, blank=True, verbose_name='Home Image', null=True, max_length=500 ) def __str__(self): return self.name def save(self, *args, **kwargs): # Check if an image with the same name exists try: existing_image = ImageHome.objects.get(name=self.name) # Delete the existing image if existing_image.image_home: existing_image.image_home.delete() except ImageHome.DoesNotExist: pass # Call the original save method to save the new image super(ImageHome, self).save(*args, **kwargs) here is the code in my html file: <section data-image-width="1980" data-image-height="1320" style="background-image: linear-gradient(0deg, rgba(41, 49, 51, 0.5), rgba(41, 49, 51, 0.5)), url('/media/Images/Home_Pictures/1.jpg') ; background-position: 50% 50%;"> my second approach … -
[Django][Django Migration Linter] Does not work with Oracle
I discover the world of Python and Django, having to take charge of an existing project written in Python with the Django framework. This Django project has to be connected to a new database, an Oracle database. I see on the net a tool that seems to be very useful. This tool calls djanomigrationlinter (https://pypi.org/project/django-migration-linter/) It seems to be very useful to ckeck the migrations, i see a very instructive demo on the net which shows the use of Django Migration Linter. I take as dependency of the project django-migration-linter. I want to use it but it does not work with Oracle. Executing the command : python manage.py lintmigrations --sql-analyser oracle gives me the following error: I have few questions: Do you know a similar tool compatible with Oracle ? I found a work around that seems to work by replacing in my command oracle by postgresql (even if it is an Oracle database that is connected to the project) python manage.py lintmigrations --sql-analyser postgresql and it seems to "work", i mean that it gives information about the migrations without errors => Do you think that it is a good work-around without any similar tool (if a similar tool compatible … -
After successful login django giving 404 error
I have a login page, and after user logs in it should take him to the main page under articles. I have the main project called pnb, then i have 2 other apps, which are users and articles Under the pnb -> urls.py i have the following from django.contrib import admin from django.urls import path, include from users import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('signin', views.signin, name='signin'), path('signout', views.signout, name='signout'), path('articles', include('articles.urls')), ] Under users -> urls.py i have the following from django.urls import path from .views import home urlpatterns = [ path('', home, name = "home"), ] Under users -> views.py i have the following from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect import articles.views def home(request): return render(request, "users/home.html") def signin(request): if request.method =='POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('articles/index.html') else: messages.error(request, "Bad Credentials") return redirect('home') def signout(request): logout(request) return redirect('home') Under articles -> urls.py i have the following from django.urls import path from . import views urlpatterns = [ path('', views.articles_view, name='articles_view'), ] Under articles -> views.py i have the following from django.shortcuts … -
Does Django store the tables inside the 'models.py' files for each app in the same database?
Just to make it clearer: suppose I have a Django project that contains multiple apps. Each one of those apps contains a 'models.py' file. Each one of those 'models.py' files contains multiple Python classes; each class represents a Python table. (If I said anything wrong, please correct me). If what I said above is true, my question is: does Django save ALL of those tables (from multiple apps) in the same database? If yes, can you 'join' data from tables that belong to different apps? I hope this makes sense. I have just started learning Django and following their official tutorial but I feel it skips a lot of these types of questions and I find myself copying stuff without understand too much how exactly it works so here I am.