Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Formatting text in Python
I currently have a breadcrumb package which have successfully deployed into my website. The package displays the name of the name of the html document which is gleamed from the web directory. I'm still very new to Python. This correctly display the breadcrumb trail, however I need to format this. My code is as follows but Django appears to ignore any formatting I tell it to action. class BreadcrumbsItem: def __init__(self, name_raw, path, position, base_url=None): ..... self.remove_dashes = self.name_raw.replace("-", " ") .... def remove_dashes(self): formatted_path_name = str(name_raw) return formatted_path_name.replate("-"," ") Why are the items (page names) in the breadcrumbs in my HTML document not being removed? -
How to insert a new page data manually in wagtail database table?
I am using wagtail 2.10.2. And I want to use SQL query to manually create a page entry for a page type in database. Would like to know the steps and possible complications in doing so. Thanks How to achieve this with out breaking the existing setup which is up and running. -
Django factory-boy custom provider
I would like to create my own customer Faker provider. I am using factory-boy which comes already with Faker included, so in my test factories I am using for a UserFactory name = factory.Faker('name') My question is, can I somehow implement my own custom provider? So I could use factory.Faker('my_provider')? Or for that I would have to swap all factory.Faker() instances and just use Faker() instance? -
Error while adding exiting table from sql server in django app using django inspectdb -- error
I am try to use py -m django inspectdb , but not able to get success... I am able to connect database through django code in setting.py I am getting following error while using inspectdb command in windowds cmd shell py -m django inspectdb SeatLocation --database="DB_UUIS_ITO_BB" > seatlocation.py (seatenv) C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\OSeatMap\OSeatMap>py -m django inspectdb SeatLocation --database="DB_UUIS_ITO_BB" > seatlocation.py Traceback (most recent call last): File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\utils\connection.py", line 58, in getitem return getattr(self._connections, alias) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\asgiref\local.py", line 105, in getattr raise AttributeError(f"{self!r} object has no attribute {key!r}") AttributeError: <asgiref.local.Local object at 0x000001B984F51750> object has no attribute 'DB_UUIS_ITO_BB' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 198, in run_module_as_main File "", line 88, in run_code File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django_main.py", line 9, in management.execute_from_command_line() File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management_init.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\commands\inspectdb.py", line 46, in handle for line in self.handle_inspection(options): File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\commands\inspectdb.py", line 55, in handle_inspection connection = connections[options["database"]] ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\utils\connection.py", line 60, in getitem if alias not … -
annotate django query by substring
How do you annotate a query set using a substring from a field? I presume something like this: query_by_domain = ( queryset .annotate(domain=Substr("email", F("email").Index("@") + 1)) .values("domain") .annotate(count=Count("id")) .order_by("domain") ) -
Is there something i am doing wrong?
import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import axios from 'axios'; import '../styles/sales.css'; // Import the CSS file function Sales() { const [propertyData, setPropertyData] = useState([]); useEffect(() => { // Fetch data from your Django API using Axios axios.get('http://127.0.0.1:8000/api/v1/core/for-sale/') .then((response) => { // Limit the photos to a maximum of four const limitedData = response.data.slice(0, 4); setPropertyData(limitedData); }) .catch((error) => { console.error('Error fetching data:', error); }); }, []); return ( <div className="sales-container"> {propertyData.map((property) => ( <div key={property.id} className="property-card"> <Link to={`/property/${property.id}`}> <img src={property.main_photo} alt={property.title} className="property-image" /> <h2 className="property-title">{property.title}</h2> </Link> <p className="property-description">{property.description}</p> <p className="property-details"> {property.bedrooms} Bedrooms | ${property.price} </p> </div> ))} </div> ); } export default Sales; I was trying to fetch data from a django-rest api. I have installed the axios library, defined the CORS_ALLOWED_ORIGINS also added the corsheaders but the images cannot be rendered. I get the following error "Error fetching data: TypeError: response.data.slice is not a function" -
how to display cart items detail in html
my views.py def cart(request): context={'cart': Cart.objects.filter(is_paid=False)} return render(request, 'cart.html',context) my models.py class Cart(models.Model): is_paid=models.BooleanField(default=False) class CartItems(models.Model): cart=models.ForeignKey(Cart, on_delete=models.CASCADE) product=models.ForeignKey(Product,on_delete=models.SET_NULL, null=True,blank=True) color_variant=models.ForeignKey(ColorVariant, on_delete=models.SET_NULL, null=True, blank=True) size_variant=models.ForeignKey(SizeVariant, on_delete=models.SET_NULL, null=True, blank=True) my cart.html {% if cart %} <tr> {% for item in cart %} <td class="product__cart__item"> <div class="product__cart__item__pic"> <img src="{% static "img/shopping-cart/cart-1.jpg" %}" alt=""> </div> <div class="product__cart__item__text"> <h6>{{item.product.name}}</h6> <h5>98</h5> </div> </td> <td class="quantity__item"> <div class="quantity"> <div class="pro-qty-2"> <input type="text" value="1"> </div> </div> </td> <td class="cart__price">$ 30.00</td> <td class="cart__close"><i class="fa fa-close"></i></td> {% endfor %} </tr> -
Implicit UUID auto fields for primary keys in Django
By default, Django adds integer primary keys as Autofields. This is annoying for many purposes, but especially makes debugging more difficult (code may accidently refer to the wrong "id", but instead of creating a runtime error, this might work in "some" instances because the IDs are accidently the same). I want either unique integers across all tables or UUIDs for primary key. I do not want to specify either explicitly, since I want to only use this for debugging (and switch back to integers in production). This is not a new proposal, but all answers seem to say "this is not performant" (blinding flash of the obvious) or advise to use explicit UUID fields (I don't want to do this because it means changing my model EVERYWHERE, then having to change it back later). Is there a way how to achieve this? The proposals I've looked at (none of which answer by question) can be found here: Using a UUID as a primary key in Django models (generic relations impact) and Django: Unique ID's across tables with an open ticket for this feature here https://code.djangoproject.com/ticket/32577 -
Django psycopg2 error while migrating the project
The following error occurs while doing manage.py migrate. psycopg2.errors.UndefinedTable: relation "relation_name" does not exist ... ... ... django.db.utils.ProgrammingError: relation "relation_name" does not exist Happened when I tried to set up a copy of my project elsewhere. Yes, I have installed all the dependencies. -
Why is my page displaying duplicate objects during pagination?
I've added in a sort-by dropdown option to my webpage but for some reason it's displaying duplicate objects on the page. Here's how the flow goes: User lands on webpage and list of objects (these are posts from other users) are displayed. This displays as expected User then changes the drop down to sort the posts by "newest" and the webpage is reloaded but the webpage is displaying 2 of each object/post. home_page.html that the user lands on: <div class="bg-grey-lighter flex flex-col mt-2 mb-2"> <div class="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2"> <form action="{% url 'posts:dropdown_selected' %}" method="get" name="sort_form"> <select class="rounded border-gray-200" name="sort_by" onchange="sort_form.submit()"> <option id="" value="placeholder" disabled selected hidden>Sort By</option> <option value="most_supported">Most Supported</option> <option value="newest">Newest</option> <option value="oldest">Oldest</option> </select> </form> </div> </div> {% if home_search %} {% for post in object_list %} <div class="bg-grey-lighter flex flex-col mt-2 mb-2"> <a href="{% url 'posts:post_detail' post.pk %}"> <div class="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2"> <div class="bg-white px-6 py-8 rounded shadow-md text-black w-full"> <img class="lg mb-6" src="" > <h1 class="mb-8 text-3xl text-center">{{ post.title }}</h1> <p class="text-gray-700 text-base"> {{ post.description }} </p> </a> <div class="relative flex-nowrap text-gray-500 mt-8 mb-0"> {% for tag in post.tags.all %} <div class="ml-4 text-xs inline-flex items-center …