Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Slice on the queryset argument of a Django Prefetch object and got "Cannot filter a query once a slice has been taken."
I did a slice on the queryset argument of a Django Prefetch object and got "Cannot filter a query once a slice has been taken." from django.db.models import Prefetch queryset = SomeModel.objects.filter(some_field=some_value).order_by('id')[:5] prefetch_obj = Prefetch('related_field', queryset=queryset) some_queryset.prefetch_related(prefetch_obj) Is there any way to slice only the first 5 query sets to be cached by prefetch? -
Find all broken foreign key and m2m relationships in a Django app?
I've got a sqlite data dump for a django app where some models have been redacted. How can I find all the models that have broken FK and M2M relationships* in the app ? *I'm happy I can generate placeholder data for everything that is missing - this is so I can write a script to make sure I'm not missing some field. -
Doesn't transfer a string to django?
return HttpResponse(f'{product}'.replace('\n', '')) does not wrap a string. what could this be about and how to fix it here's what I wanted to get into the product I have several data but all the data I have is not transferred -
Create a normal Django Model, View, Serializer within a wagtail app
We currently have a wagtail app that acts like a CMS as it should, but we recently had a requirement that requires us to create a model view and serializer that should not be seen through wagtail admin page. I've gone through and created a model from within one of our apps in django (not from home apps that is default created by wagtail). class MasterClass(models.Model): topic = models.CharField(max_length=255) <<redacted>> and it doesnt seem to be detected by django when doing make migrations. is there any additional config to make this work? -
How to run command directly on local machine drive
My intention is to write data directly on the disk from where I run the docker command and not into the container disk. Any ideas how to do this ? I tried this: docker exec -it app bash -c "python manage.py dumpdata > data.json" but the data is saved inside container. -
In django, bulk_create with update_conflicts=True doesn't work if I have multiple UniqueConstraints
Let's say I have this model: class XYZ(Model): id = models.BigAutoField(primary_key=True) keys_1 = models.IntegerField() keys_2 = models.JSONField(null=False, default=dict) keys_3 = models.DateField(null=True, default=None) values = models.JSONField(null=False, default=dict) class Meta: db_table = "xyz" constraints = [ models.UniqueConstraint( fields=["keys_1", "keys_2"], name="unicity_when_keys_3_null", condition=Q(keys_3__isnull=True), ), models.UniqueConstraint( fields=["keys_1", "keys_2", "keys_3"], name="unicity", ), ] I then do this: XYZ.objects.bulk_create( data, update_conflicts=True, unique_fields=["keys_1", "keys_2", "keys_3"], update_fields=["values"], ) with data being a list of XYZ objects If data[n].keys_3 is not None, it works as expected If data[n].keys_3 is None, it fails on conflict, citing the unicity constraint Am I doing something wrong ? PS: these can't be used btw XYZ.objects.bulk_create( data, update_conflicts=True, unique_fields=["keys_1", "keys_2"], update_fields=["values"], ) XYZ.objects.bulk_create( data, update_conflicts=True, unique_fields=["keys_1", "keys_2"], update_fields=["values", "keys_3"], ) -
Consuming messages from Kafka with different group IDs using confluent_kafka
I am using python and confluent_kafka I am building a Queue Management for Kafka where we can view the pending(uncommitted) messages of each topic, delete topic and purge topic. I am facing the following problems. I am using same group ID for all the consumers so that I can get the uncommitted messages. I have 2 consumers one (say consumer1) consuming and committing and another one (say consumer2) just consuming without committing. If I run consumer1 and consumer2 simultaneously only one consumer will start consuming and another just keep on waiting and hence cause heavy loading time in the frontend. If I assign different group Id for each it works but, the messages committed by consumer1 are still readable by consumer2. Example: If I have pushed 100 messages and say consumer1 consumed 80 messages and when I try to consume from consumer2 it should consume only remaining 20, but it is consuming all 100 including the messages committed by consumer1. How can I avoid that or solve? -
Django 'QuerySet' object has no attribute 'startswith'
I'm new to Django and I created function to allow admin to create users accounts. I used a password generator + make_password() function to hash the password. Now it's sending the plain password to users email and storing it in the database hashed, I used check_password() to compare but I'm getting this error: 'QuerySet' object has no attribute 'startswith' def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email).values() hashed_pw = User.objects.filter(user_password=user_password).values() check_password(user_password, hashed_pw) if user_details: request.session['logged_in'] = True request.session['user_email'] = user_details[0]["user_email"] request.session['u_id'] = user_details[0]["user_email"] request.session['user_name'] = user_details[0]["user_name"] request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') -
Is there any way to roll back execution of delete method with ldap3
I'm using Django 4.1 and ldap3 to connect directory service using ldap. Is there any way to roll back execution of delete method? the sample code likes below: # import class and constants from ldap3 import Server, Connection, ALL # define the server s = Server('servername', get_info=ALL) # define an unsecure LDAP server, requesting info on DSE and schema # define the connection c = Connection(s, user='user_dn', password='user_password') # perform the Delete operation c.delete('cn=user1,ou=users,o=company') #some checks here #if condition: # user1.recover() after some checking, I want to recover user's data based on a condition. Thanks! I've searched about rollback delete execution, but did not find any solution. -
Clean up unused database tables after removing a Django app?
When I remove a Django app from my list of INSTALLED_APPS, it doesn't get rid of the old database tables; running ./manage.py makemigrations doesn't detect any changes. Apart from going into the database myself and dropping the old tables, is there a better way to clean up unused tables after uninstalling an app from my Django project? -
Display data by date, when data comes from multiple models in Django
I'm currently working on an app with Django 4.1. I try to display a resume of some data comming from the database. Here is a simplified example of my models: class Signal(models.Model): data1 = models.CharField() data2 = models.CharField() date = models.DateTimeField() class Ban(models.Model): data3 = models.CharField() data4 = models.CharField() date = models.DateTimeField() What I'm trying to do is getting filtered data from these 2 models, and make a list ordered by date from all this data to display it. someting like: Ban1 (08/03/2023) Ban2 (07/03/2023) Signal2 (06/03/2023) Ban3 (05/03/2023) Signal1 (04/03/2023) Thanks in advance for your ideas -
Django I want to make comments on category posts
I want to make comments on posts. I found a lot of monual, but it either does not fit or does not work. I need to create a separate comment view function and display the comment form in a template. I don't understand how to make a separate comment function and display it in the post template. Need a simple, elegant solution to the problem. class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(episode,on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) FORM.PY from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') Views from .forms import * from .models import * ... def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) return render(request, 'content/season.html',{ 'season':seasonpages, 'episode': episodepost,}) def ContentEpisode(request, seasonpost_slug, episodepost_slug): … -
How to add more details in a shoping cart in django?
I am building a application which is quiet similiar to an Ecommerce Shopping Cart in Django. However, in my case for each item in the shopping cart belongs to someone. So, instead of having the name of the item, the quantity, the price, ..., I would like to be able to see for each item, the name of the buyer, the receiver, the receiver's phone number and so fourth. So, for each order ID, I will be able to the details of beside the price, the quantity and items. Here are my file Cart.py class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart # store current applied coupon self.coupon_id = self.session.get('coupon_id') def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = { 'quantity': 0, 'price': str(product.prix), 'destinataire':product.destinataire } if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # mark the session as "modified" to make sure it gets saved self.session.modified = True def remove(self, … -
How would I update a field to set a default value?
After updating an existing django field to have a default value if I save the field with a null value I get the error: IntegrityError: null value in column rather than the field being set to the default, does anyone know why this may be? If I include null=True it just sets it to null. -
Django sitemap problem for domain/category/city listing pages
I have a business directory and i made sitemaps for categories and firms, but when i came to build sitemap for category/city listing pages, i couldn't resolve. https://www.endustri.io/firma/enerji/bursa/ This is my live website. firma is prefix for business directory, enerji is a category and bursa is city. I am listing companies correctly. I made sitemap5.py codes with chatgpt. #Before the live version i am making local tries. but the result is here <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> <url> <loc>http://example.com/firma/</loc> <lastmod>2023-03-04</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> </urlset> here is my models.py class City(models.Model): city = models.CharField(max_length=50) slug = models.SlugField() def __str__(self): return str(self.city) class District(models.Model): district = models.CharField(max_length=50) slug = models.SlugField() city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return str(self.district) class FirmaCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() aciklama = tinymce_models.HTMLField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Firma Kategorileri' def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('firma-category', args=[str(self.slug)]) class Firma(models.Model): category = models.ForeignKey(FirmaCategory, related_name="firma", on_delete=models.CASCADE) title = models.CharField(max_length=300) slug = models.SlugField() adres = tinymce_models.HTMLField() tel = tinymce_models.HTMLField() website = tinymce_models.HTMLField() email = tinymce_models.HTMLField() intro = tinymce_models.HTMLField() body = tinymce_models.HTMLField() city = models.ForeignKey(City,related_name="FirmaCategory" ,on_delete=models.CASCADE) district = models.ForeignKey(District,related_name="FirmaCategory", on_delete=models.CASCADE) #url = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural … -
Setting a timer for players in an online game in Django [closed]
I am implementing an online poker game with Django. Each player in the game has a certain amount of time to perform an action. What solution do you suggest for placing this timer? For this project, I am using Django Channel and WebSocket, and the scheduling work is done there -
Accessing Django on a secondary device
I am trying to access Django from a secondary device i.e. android phone. I have made sure that The laptop I am running Django on is connected to the same network as my secondary device. I have turned off the firewall on my laptop I configured CSRF to accept POST requests a trusted origin in settings.py Thereafter running python manage.py runserver 0.0.0.0:8000 , the POST requests on my website works when I access it from the laptop I am running Django from. However, when I use the same link http://192.168.16.130:8000/ on my phone, the POST requests don't work. import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.16.130', '127.0.0.1', 'localhost', '0.0.0.0'] # !!! Added for CSRF protection # CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_ALL_ORIGINS=True CORS_ALLOWED_ORIGINS = [ "http://0.0.0.0:8000", "http://localhost:8000", "http://192.168.16.130:8000", "http://127.0.0.1:8000", ] CSRF_TRUSTED_ORIGINS = [ "http://0.0.0.0:8000", "http://localhost:8000", "http://192.168.16.130:8000", "http://127.0.0.1:8000", ] CORS_ALLOW_METHODS = [ 'GET', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # !!! Added for … -
Cookiecutter-django custom User field is never saved to DB
I'm struggling with a banal (I guess) issue with cookiecutter-django... I added the field invitation_code to users.models.User: class User(AbstractUser): """ Default custom user model for pintable. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ #: First and last name do not cover name patterns around the globe name = CharField(_("Full name"), max_length=255, null=True, blank=True) first_name = None # type: ignore last_name = None # type: ignore invitation_code = CharField( _("Invitation code"), max_length=8, null=True, blank=True ) Then I added the same field to users.forms.UserSignupForm: class UserSignupForm(SignupForm): """ Form that will be rendered on a user sign up section/screen. Default fields will be added automatically. Check UserSocialSignupForm for accounts created from social. """ invitation_code = CharField( label=_("Invitation code"), widget=TextInput(attrs={"placeholder": _("Invitation code")}), ) The problem is that when a new user is saved to DB, the invitation_code field is always None. What am I missing..? Thanks for your help! -
How to auto create foreingKey object (python with django)
I'm creating a simple rest api This is my actual result from devices, i create first the group and options, and then associate, but i want to create the options at the same time i create the device. My result from devices right now [ { "id_device": "a099d2ce-812b-4d85-8c8b-cfe71057fbe7", "group": { "id_group": "39407ef6-1a3e-4965-9b61-96f6c40b76b3", "name": "Cozinha" }, "options": [ { "id_option": "1b383a37-5229-4ae0-9649-f76aa32eeda0", "name": "1", "identifier": "POWER1" }, { "id_option": "4ff5406a-8c7b-4517-9ec0-14fd4f68f30b", "name": "2", "identifier": "POWER2" }, { "id_option": "a541216d-f509-4461-85ca-444491ac9217", "name": "3", "identifier": "POWER3" }, { "id_option": "3debe828-edd6-4d83-bfd8-2776a1594380", "name": "4", "identifier": "POWER4" } ], "name": "Interruptor 4", "identifier": "identifiertest" }, ] my models.py from uuid import uuid4 from django.db import models class Options(models.Model): id_option = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Groups(models.Model): id_group = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Devices(models.Model): id_device = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) options = models.ManyToManyField(Options) group = models.ForeignKey(Groups, on_delete=models.CASCADE, default="") viewsets from rest_framework import viewsets from devices.api import serializers from devices import models class DevicesViewsets(viewsets.ModelViewSet): serializer_class = serializers.DevicesSerializer queryset = models.Devices.objects.all() class OptionsViewsets(viewsets.ModelViewSet): serializer_class = serializers.OptionsSerializer queryset = models.Options.objects.all() class GroupsViewsets(viewsets.ModelViewSet): … -
Structure Policy for Django / Python Libraries
Question Summary Hi Folks, This is a kind of opinion question, I've built a Django library for my company and I keep swithering and changing my mind on how to structure it. Possible strategies I've come up with are below: Method 1 - Individual Libraries Split all parts of the library into separate repos. For example my_library_core my_library_cookies my_library_exporter and include from them individually. Pros Each library is compartmentalised and can be updated or included individually, so you can include only some of the functionality and install only some of the library modules. Cons Dependencies / functionalities between libraries can get out of sync, if library one is using version 1 of the core library and library two is using version 2, you're forced to upgrade both to upgrade one. Lots of separate repos to keep on top of. Harder to have a reliable "core" library for common functionality. Feels messy / uncentralised. Method 2 - Monolithic Library Have one large library that contains all functionality. Pros Centralised, everything is referencing the same library. Dependencies are centralised, the whole library has one set of dependencies that apply to all sub apps. Neater, everything imports from a one library. Cons Upgrading … -
Can't make superuser: error no such column
Hi I try make superuser to login my admin panel but I recieved this error while making superuser: django.db.utils.OperationalError: no such column: accounts_user.password1 and this is my model: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField(unique=True, max_length=10) email = models.EmailField() password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) is_publisher = models.BooleanField(default=False) def change_user_type(self): if self.is_publisher: self.is_superuser = True self.save() -
Handling concurrent user in Django + PostgreSql
I am creating a website which will take input from form and store it to database (PostgreSql) and the Input will be used for operation using python (eg: adding two numbers taken from form) and also there will be a button to take input from form again and previous given input will also be seen by a click. My question is : Let's say 100 users at same time comes to the website and filling the form, then in that case how should I handle the database, how to Store data each time from form so that It will not be an issue for other user and user can only see their previous input. I am new to development field, So I have no idea how to handle this. -
I am experiencing an error which comes anytime
I am experiencing an error which comes anytime i.e. sometime the code works fine but other time, this error occurs. I am working on login and signin project with minimalist html. The error is "Reason given for failure: CSRF token from POST incorrect." from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User from home.models import contactIssue from django.contrib.auth.forms import UserCreationForm def index(request): if (request.method=="POST"): if (request.POST.get('LoginButton','false')!='false'): return redirect('loginPage') else: return redirect('signinPage') return render(request, template_name="index.html") def loginFunc(request): if (request.method=='POST'): username = request.POST.get('username','Not found') password = request.POST.get('password','No password') print(username, password) try: user = User.objects.get(username=username) print(user) user = authenticate(request, username=username, password=password) if (user is not None): print("Login successful") login(request, user) return redirect('/loginPage') else: print("Login failed") except: print('No user found') return render(request, template_name='loginPage.html') def signinPage(request): # if (request.method=='POST'): # username = request.POST.get('username','Not found') # email = request.POST.get('email','No email') # password = request.POST.get('password','No password') # print(username, email, password) # return redirect('/') form = UserCreationForm(request.POST or None) if (request.method=="POST"): if (form.is_valid()): user = form.save() login(request, user) return redirect('/') return render(request, template_name='signPage.html', context={'form':form}) def logoutFunc(request): logout(request) return redirect('/') def contact(request): if (request.method=='POST'): username = request.user.username description = request.POST.get('description', 'No description') contactObject = contactIssue.objects.create(username=username, description=description) contactObject.save() print("contact submitted … -
Django how to compare stored hash password and plain password
I'm new to Django and I created function to allow admin to create users accounts. I used a password generator + make_password() function to hash the password. Now it's sending the plain password to users email and storing it in the database hashed. now the user is able to login with the hashed password only. my view.py: @admin_login_required def add_emp(request): if request.method == 'POST': user_name = request.POST['user_name'] user_email = request.POST['user_email'] user_otj = request.POST['user_otj'] user_password = pwo.generate() user_password1 = make_password(user_password) empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj) if empObj: subject = 'Advanced Analytics Portal - Login Info' message = f'Name : {user_name}, \n Email : {user_email}, \n Password : {user_password} \n FROM - AA Portal' email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [user_email]) messages.success(request, "Employee was added successfully!") return HttpResponseRedirect('/create-emp') else: messages.error(request, "Some error was occurred!") return HttpResponseRedirect('/create-emp') return render(request, 'AddEmp.html') def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email, user_password=user_password).values() if user_details: request.session['logged_in'] = True request.session['user_email'] = user_details[0]["user_email"] request.session['u_id'] = user_details[0]["user_email"] request.session['user_name'] = user_details[0]["user_name"] request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') Any idea how to make the user login with the plain password and keep it hashed in … -
Changing modelformset labels
I have created a modelformset for voting on multiple subtitles. It looks like this: I want to change the "Vote:" label to the names of the different subtitles instead (so if the subtitles are A, B and C, A should be before the first field, B for the second field etc.). How can I change this? The modelformset is created in the views.py like this: VoteFormSet = modelformset_factory(YesNoVote, form=YesNoVotingForm, extra=3) YesNoVotingForm looks like this: class YesNoVotingForm(forms.ModelForm): class Meta: model = YesNoVote fields = ['vote',] widgets = { 'vote': forms.Select(attrs={"required": True}), } and this is the yesnovote model: class YesNoVote(models.Model): subtitle = models.CharField(max_length=128) vote = models.CharField(choices=choices, max_length=10) user = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False, related_name="yesnovote_user", null=True) election = models.ForeignKey(YesNoElection, on_delete=models.CASCADE, related_name="yesnovote") def __str__(self): return f"{self.user} stemde {self.vote} bij {self.subtitle} (vallend onder {self.election})" and this is the html page: <form method="post"> {{ formset.management_data }} {% csrf_token %} {% for form in formset %} {{ form }} <br> {% endfor %} <button type="submit" name = "voting" class="btn btn-primary save">Submit</button> Let op: Je kunt je stem niet meer wijzigen. </form>