Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Django Token authentication problem accessing another accountI have made Account model, which is now custom user model in Django my app. Also, I have Token authentication, but I do not know how to refresh Token, and how frequently I have to change Token for user.. Also I have a problem, because a user after logging with token can access another account, by just changing id in url. How can I solve this problem. I thought about solution that I put id of user in Token, so when he access to some url I check if it is his id in url from Token. But I am not sure is this is good solution for Django, because I do not know how to add id in Token. Maybe Django has some cleverer solution. I am pretty new in Django, so...
- 
        error on Django drf ModelSerializer update methodI have a very strange error, this is my serializer class class user_ser(ModelSerializer): class Meta: model = User fields = '__all__' depth = 1 whenever I send an API request to update user data, i got default values for is_staff and is_superuser in the image below I send only email and password example : look what I got :( this is the validated_data for the update method is : I did not add is_staff or anything else to the request body, so why is that happening.
- 
        Adding flag based on date in django listviewI am looking to add an extra column based on two date columns. The column should indicate if the item overlaps a certain date. I have no idea how or where to get started. I am loading a simple model in a listview with 3 columns, name, startdatetime and enddatetime. The selected date is currently datetime.now() So basically i want to know what item is active right now. thanks in advance
- 
        include text and variable in ValidationErrorI am using this code on the model to check if users are uploading images that are too large code: def validate_image(image): file_size = image.file.size test = 'whoop' if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError("image too large") image = models.ImageField(default='default.jpg', upload_to=path_and_rename, validators=[validate_image]) however i want to include the name of the offending file if i use raise ValidationError(image) it displays the file name but if I try to include some text raise ValidationError(image, "is too large") it will only display whatever comes first either the variable or the string. How can i include both
- 
        Accessing session variable based on variable in for loop django templateI have some products listed which can be in a cart, this cart is stored in a session variable dictionary for which the key is the product id and the value is some information about the quantity and stuff. I want to add the option to view (on the products page) how many of that product are in your cart. I know I can access session variables in a django template like this: {{ request.session.cart.2323.quantity }} Problem is, the key (2323 in this case) is a variable which depends on a for loop: {% for prod in products %} <p>{{ request.session.cart[prod.name].quantity }}</p> {% endfor %} But implementing it like that unfortunately is not possible. Is there any way in which this would be possible or would I have to change the way my cart works?
- 
        Django queryset for usermodels.py(shrunk to things that matter) class Messages(models.Model): sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE) receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE) forms.py class MessageForm(forms.ModelForm): subject = forms.CharField(max_length=100, required=False, help_text='Optional.') text = forms.CharField(max_length=4096, required=True, help_text='Required.') class Meta: model = Messages fields = ('receiver','subject','text',) I have a dropdown that shows all users that were made I would like to filter it based off some fields like is_active to showcase only users that are authenticated and more like this so I would like to override I think it's receiver queryset. def index(request): sendMessageForm = MessageForm() if is_staff: if is_active: else: What my current form displays. <select name="receiver" required="" id="id_receiver"> <option value="" selected="">---------</option> <option value="39">1</option> <option value="40">2</option> <option value="41">3</option> <option value="42">4</option> </select>
- 
        Django migrate error: formisoformat argument must be stringI would really need help to understand this error I get in Django that suddenly appeared after I added a bunch of objects to a models.Model class. This error persists even when I comment out all the new objects that might have provoked the error. This error is a bunch of Tracebacks and at last it tells that there is a "TypeError: fromisoformat: argument must be str " in this line: return datetime.date.fromisoformat(value) in dateparse.py file. I've been looking for a solution for a few days now but can't seem to find any, I don't fully understand the functioning of django yet so it would be really great if anyone could tell me how to get through this. Thanks for your time.
- 
        Django Ajax Reorder Not Updating the Field in DatabaseI'm building a list of students by each class in the grade. I have a folder full of profile pictures for students downloaded into my img folder and a column within my model that maps the details (name, class, age, etc.) to the image name. How do I tell my table to bring in the appropriate img for each student? Below I have my code working to use a single image as a constant (e.g. student1's picture shows up for everyone). list.html: <table class="table table-hover" id="table-ajax"> <thead class="thead-light"> <tr> {% comment %} <th></th> {% endcomment %} <th style="width: 50px; text-align: center;"></th> <th>{{ object_list|verbose_name:'field:name' }}</th> <th>{{ object_list|verbose_name:'field:hometown' }}</th> <th>{{ object_list|verbose_name:'field:birthday' }}</th> <th>{{ object_list|verbose_name:'field:race' }}</th> <th>{{ object_list|verbose_name:'field:rank' }}</th> <th style="width: 50px; text-align: center;">Pictures</th> <th style="width: 160px; text-align: center;">Actions</th> </tr> </thead> <tbody class="order" data-url="{% url 'cms:reorder' model_name %}"> {% include 'app/partials/pick_list_partial.html' %} </tbody> partial-list.html: {% for pick in object_list %} <tr id="{{ pick.pk }}"> <td><img src="{% static 'img/student1.jpg' %}" width="50" height="50"></td> <td><a href="{% url 'app:lead-list' pick.pk %}" title="Leads">{{ pick.name }}</a></td> <td>{{ pick.hometown }}</td> <td>{{ pick.birthday }}</td> <td>{{ pick.race }}</td> <td>{{ pick.rank }}</td> <td style="text-align: center;"> <a href="{% url 'app:file-list' pick.pk %}" class="btn btn-outline-success btn-sm border-0" title="Files"> <i class="fa fa-copy"></i></a></td> <td style="text-align: center;"> <a …
- 
        How do you connect Django to an existing Microsoft SQL Server DB stored on Azure?I have setup a Django API connected to a React frontend. I'm attempting to connect the Django API to an already existing mssql database on Azure. I've installed pyodbc, djagno-pyodbc-azure, and mssql-django. In my settings.py I have the data: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'DBNAME', 'USER': 'USERNAME', 'PASSWORD': 'PW', 'HOST' : 'tcp:dbname.database.windows.net', 'PORT': '1442', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } }, } I've tried removing "tcp:" from host, I've tried "sql_server.pyodbc" as the ENGINE. I installed a few different other packages. Whenever I run "python manage.py inspectdb > models.py" to import the models of the existing database I either get an empty models.py file or an error "django.db.utils.Error: ('01000'...". Feel a bit stuck and was wondering if anyone had some guidance.
- 
        Connect Django Postgres to AWS RDS over SSLI'm digging into Django and thought it would be a nice exercise to connect to an AWS RDS database over SSL, but I can't quite figure out how to provide the SSL-cert from AWS to the database config. I've downloaded the global-bundle.pem from https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html. Now in the Django source code, it seems you can pass these parameters to DATABASES: DATABASES = { 'default': { ... 'OPTIONS': { 'sslmode': 'verify-ca', 'sslrootcert': 'root.crt', 'sslcert': 'client.crt', 'sslkey': 'client.key', }, } } My question is, how do I convert/pass the certificate from AWS?
- 
        Django project - database table in cacheI have a Django(python) project running on a digitalocean.com droplet. Because the configurations options are limited I have an excess of free memory. I'm thinking about using that available memory, and load some database tables in memory. I already have a Redis server caching some views. Is it possible to cache a database whole table? How? Thanks.
- 
        How to change gmail contact name in Django emailsI am trying to change my gmail contact name that is sent from Django. Currently, when I send an email, it shows david as the sender when it is from david@mycompany.com. I have tried the other suggestions on SO by setting it up like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') DEFAULT_FROM_EMAIL = f"David at Company <{os.environ.get('EMAIL_HOST_USER')}>" print(DEFAULT_FROM_EMAIL) This results in the error: celery_1 | smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials d8sm7252296pfu.141 - gsmtp') The setting which send the email but have the user as david looks like: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') I have also tried not using env vars and hard coding it as such: EMAIL_HOST_USER = "David at Company <david@company.com>" to no avail. Thoughts?
- 
        Why my django m2m_changed signal not triggered?I am trying to validate an image field which have a m2m relationship with the post model by using the m2m_changed signal but it is not being triggered at all. clearly there is something that I am missing but don't know what. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) images = models.ManyToManyField('Files', blank=True) here is my signals.py file from django.dispatch import receiver from django.db.models.signals import m2m_changed from django.core.exceptions import ValidationError @receiver(m2m_changed, sender=Post.images.through) def images_changed(sender, **kwargs): print("the images signal changed ran") And I also defined the ready method in my apps.py file. def ready(self): import social.signals
- 
        Form validation djangoI am a beginner,I got this assignment in which I have to create django app. But am not able to understand how to do that ,so below are the requirements of the app. The app should have to form and each form should have proper JavaScript validation. The inputs in the first form say (gender of the applicant) should determine the field shown on the second form. I didn't understood the 2 nd point , do i have to create log in /sign up or what
- 
        Ordering by computed field in admin panelI'm learning Django and I got stuck on this problem I'm basically trying to order by a computed field in an admin panel view, I've read some "tutorials" like this: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/sorting_calculated_fields.html on google but I can't seem to figure out how it all works (between annotations etc) Here's my classes: class StockAdmin(admin.ModelAdmin): list_display = ("ticker_symbol", "security_name", "current_pretax_yield", "current_aftertax_yield", "displayed_price") search_fields = ("ticker_symbol", "security_name") def current_pretax_yield(self, obj): try: curyield = float(obj.coupon_amount/obj.last_price) return str(round((curyield*100),3)) + "%" except: return "n/a" def current_aftertax_yield(self, obj): try: withholding_tax = 15 at_yield = ((obj.coupon_amount/obj.last_price*100)*(1-(withholding_tax/100))*0.74) return str(round(at_yield, 2)) + "%" except: return "n/a" def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate( _current_aftertax_yield=self.current_aftertax_yield(), _current_pretax_yield=self.current_pretax_yield(), ) current_aftertax_yield.admin_order_field = '_current_aftertax_yield' current_pretax_yield.admin_order_field = '_current_pretax_yield' Basically, I want to get "coupon amount" and "last price" fields from the database, perform the calculations you see in the functions, then display those calculated files in the admin panel and be able to "order by" them The code as I have now errors out with a TypeError: current_aftertax_yield() missing 1 required positional argument: 'obj' I've tried to follow this: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/sorting_calculated_fields.html but I can't quite figure it out on my own.. Any ideas? Is there an easier way of doing this? I used a lot of …
- 
        Authenticate several apps with same Oauth2 provider using one callback urlI currently have a chrome extension which authorizes with an Oauth2 provider and then authenticates with my django rest framework backend using allauth. I want to add two new apps to the same backend; a iOS app and an Android app. They shall both use the same Oauth2 provider. Currently the Oauth provider has stopped the possibility to add new apps, which means I only have the possibility of ONE callback url, which is currently used by the Chrome extension. Is there a way of designing the auth flow to send redirect and callback to the backend for all three (using just one callback url), and somehow be able to send my backends api token back to the apps?
- 
        Uncaught TypeError: Cannot read properties of undefined (reading 'childNode')hi I am trying to follow the below tutorial for my formset only i find problem in part: container.insertBefore (newForm, addButton) and the error that presents me is the following: calculos.js: 195 Uncaught TypeError: Cannot read properties of undefined (reading 'childNode') I've already tried everything but can't find the childNode JS let parteForm = document.querySelectorAll(".part-form") let container = document.querySelector("#part-form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing addButton.addEventListener('click', addForm) function addForm(){ //e.preventDefault() let newForm = parteForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`,'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) //parentnode.insertbefore(newnode,elnodoantesdelcualseinsertanewnode) //#part-form-container.insertbefore(div.part-form,) totalForms.setAttribute('value', `${formNum+1}`) } HTML <form method="POST" id="part-form-container"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <div class="row mb-3"> <div class="col-md-12"> <div class="mb-3"> <label for="verticalnav-email-input">Summary</label> {{presupuestosparteform.resumen}} </div> </div> </div> <h4 class="card-title">Parts list</h4> <p class="card-title-desc">Add the parts that you need to include.</p> <input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" /> <div class="table-responsive"> <table class="table table-bordered table-nowrap align-middle" id="childTable1"> <tbody> {{ formset.management_form }} {% for form in formset %} <div class="part-form"> <tr> <td> {{form.codigo}} </td> <td> {{form.descripcion}} </td> </tr> </div> {% endfor %} </tbody> </table> </form>
- 
        xxxx matching query does not existI am trying to query data from a csv file to django, this is the code of the query : from django.core.management.base import BaseCommand import pandas as pd from website.models import Product class Command(BaseCommand): help='import booms' def add_arguments(self, parser): pass def handle(self,*args,**options): df=pd.read_excel('tt.xlsx',engine='openpyxl') for P_N,P_P in zip(df.Product_name,df.Price): models=Product.objects.get(Product_Name=P_N,Product_Price=P_P) models.save() here this the code of my models.py : from django.db import models # Create your models here. class Product(models.Model): Product_Name=models.TextField() Product_Price=models.TextField() #Product_Link=models.TextField() def __str__(self): return self.name knowing that my csv file is the following : http://prntscr.com/26cjw4a the error that I'm getting is this "Product matching query does not exist " http://prntscr.com/26cjw9n
- 
        Google Cloud Run: Cant connect to Postgress SQLI am following this tutorial to upload my existing Django project running locally on sqlite to Google Cloud Run / Postgres. I have the cloud_sql_proxy service running and can sign into Postgres from the command line. I am at the point of running the command python manage.py migrate And I get the error: django.db.utils.OperationalError: connection to server on socket "/cloudsql/cgps-registration-2:us-central-1:cgps-reg-2-postgre-sql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The answer to that questions is Yes, the server is running locally and accepting connections because I can log in with the Postgres client: agerson@agersons-iMac ~ % psql "sslmode=disable dbname=postgres user=postgres hostaddr=127.0.0.1" Password for user postgres: psql (14.1, server 13.4) Type "help" for help. postgres=> I double checked the connection string in my .env file and it has the correct UN / P Is this scoket not getting created somehow in a previous step? /cloudsql/cgps-registration-2:us-central-1:cgps-reg-2-postgre-sql/.s.PGSQL.5432
- 
        ¿How to iterate through model images in production?finally i deployed my first blog in heroku, but im stucked at serving each post image since in my local code whas iterating with image.url from the model. Now i have whitenoise configured but i dont know how to get the static image that is specific to each post from the model. This is my code actually: model: class BlogPost(models.Model): class BlogPostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='publicado') options = ( ('borrador', 'Borrador'), ('publicado', 'Publicado') ) categoria = models.ForeignKey(BlogCategoria, on_delete=models.PROTECT,default=1) titulo = models.CharField(max_length=250) excerpt = models.TextField(null=True,max_length=200) contenido = RichTextField() slug = models.SlugField(max_length=250, unique_for_date='publicado',null=False, unique=True) publicado = models.DateTimeField(default=timezone.now) autor = models.ForeignKey(Usuario,on_delete=models.CASCADE,related_name="autor") status = models.CharField(max_length=10,choices=options,default='borrador') imagen = models.ImageField(default= "empty.jpg" ,null=True, blank = True) likes = models.ManyToManyField(Usuario, related_name="blog_post") objects = models.Manager() postobjects = BlogPostObjects() view: class BlogInicio(ListView): template_name = "Blog/blog_inicio.html" model = BlogPost context_object_name = "posts" paginate_by = 6 template: {% for post in posts %} <div class="col-md-4" > <div class="card-content"> <div class="card-img"> {% if post.imagen %} <img src="{{post.imagen.url}}"/> {% else %} <img src="https://archive.org/download/placeholder-image/placeholder-image.jpg" /> {% endif %} <span><h4>{{post.autor}}</h4></span> <span style= "margin-top:43%;"><h4>{{post.categoria}}</h4></span> </div> <div class="card-desc"> <h3>{{post.titulo}}</h3> <p>{{post.excerpt|truncatechars:50}}</p> <a href="{% url 'blog:post_detalle' post.pk %}" class="btn-card">Leer</a> </div> </div> </div> {% endfor %} i know in line 6 from the template i could do a <img src="{% static …
- 
        DJANGO How to know if an object pk is in my request.pathI need to compare an url with if condition in Django html template, to make an options menu selected when I'm on this page. I have this but doesn't works well: {% for vehiculo in vehiculos %} {% if "/calendar/vehicle/{{ vehiculo.pk }}/" in request.path %} <a class="list-group-item list-group-item-action active"> {% else %} <a class="list-group-item list-group-item-action"> {% endif %} {% endfor %} In my url I have this. But doesn't works!!! I don't find any solutions in Django docs or here in stackoverflow, github... Any solution is worth, thanks!
- 
        Django Rest Framework Return on User's Resources in Nested SerializerI am trying to return just the user's resources in a nested serializer response. My current response looks like this: { "id": 5174, "resourceName": "name here", "moreInformation": [ { "id": 15924, "infoName": "stuff here", "infoDetails": [ { "id": 51, "createdBy": 1, "detail": "detail here", "moreInformation": 15924 }, { "id": 52, "createdBy": 3, "detail": "detail here", "moreInformation": 15924 } ] } ] } I'm trying to make it to where when the user GETs the ResourceName endpoint, that the infoDetails only shows the infoDetails that were createdBy that user. The current response returns all of the infoDetails regardless of the createdBy field. I'm able to only return the infoDetail if the current user's id matches the createdBy id on the ListInfoDetails view, but not on the DetailResourceName view. Is there a way to do this on the serializer, or is it best to do it in the view? Views: class ListInfoDetail(generics.ListCreateAPIView): queryset = InfoDetail.objects.all() serializer_class = InfoDetailSerializer def get_queryset(self): user = self.request.user return user.infodetail_set.all() class DetailResourceName(generics.RetrieveAPIView): queryset = ResourceName.objects.all() serializer_class = ResourceNameDetailSerializer Serializers: class InfoDetailSerializer(serializers.ModelSerializer): class Meta: model = InfoDetail fields = ['id', 'created_by', 'mnemonic_picture', 'block'] class MoreInformationSerializer(serializers.ModelSerializer): info_details = InfoDetailSerializer(source="infodetail_set", many=True, read_only=True) class Meta: model = MoreInformation fields = ['id', …
- 
        ValueError at /index.............The QuerySet value for an exact lookup must be limited to one result using slicingI'm building a socialmedia website in django.While I tried to list all the comments in the index page, i am getting this error, The QuerySet value for an exact lookup must be limited to one result using slicing. what should i do in this case views.py.... def index(request): if request.user.is_authenticated: allPost = Post.objects.all().order_by('-created_on').filter(creater = request.user) allBlog = Blogpost.objects.all() comments = PostComment.objects.filter(post=allPost) context = {'allPost' : allPost, 'allBlog' : allBlog, 'comments' : comments} return render(request, 'index.html', context) else: return render(request, "signoption.html") models.py.... class PostComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.sno) + '.....comment By.....' + str(self.user) index.html.... {% for comment in comments %} <div class="comment"> <div class="comment-user"> <div class="comment-usr-dp"> <img src="{%static 'img/profile/profile.png'%}" alt=""> </div> </div> <div class="comments-usr-usrname"> <b><h1>{{comment.user.username}}</h1></b> </div> <div class="comment-text"> <h1>{{comment.comment}}</h1> </div> <div class="comment-time"> <h1>{{comment.created_on}}</h1> </div> </div> {%endfor%}
- 
        'QuerySet' object has no attribute 'date_start'. Django rest frameworkI am new to Django. In my project I want to filter all the room with available status, then I want start_date to be updated to the current datetime. But I am getting the following error: 'QuerySet' object has no attribute 'start_date' I have the following class in the models.py: class RoomStatus(models.Model): room = models.ForeignKey(Room, on_delete=models.DO_NOTHING) class RoomStatusChoices(models.IntegerChoices): AVAILABLE = 1 UNAVAILABLE = 2 room_status = models.SmallIntegerField(choices=RoomStatusChoices.choices, default=RoomStatusChoices.AVAILABLE) start_date = models.DateTimeField(auto_now=True) In serializers.py I wrote an update with this code available_rooms = RoomStatus.objects.filter(room=room, room_status=RoomStatusChoices.AVAILABLE) print(available_rooms) available_rooms.start_date = max(available_rooms.start_date, datetime.now()) The result of print(available_rooms) is <QuerySet []> Can someone help me? thanks indvance.
- 
        how to grab a data from existing field in DjangoI have a web page that I have to connect with Django. So I have an existing form with input and submit button. I have created a model and form. I put {{form}} tag and a little unstyled form appeared. but I want to grab a data from the one in HTML file. The code: form file: class NumberForm(ModelForm): class Meta: model = Number fields = "__all__" HTML: <form action="#" method="post"> {% csrf_token %} {{ form }} <div class="line <input type="text" class="form-control" name="phoneNumber" id="phoneNumber2" value="" placeholder="+7 (___) ___-__-__"> <button class="button_blue">t</button> </div> <label class="container_checkbox"> <input type="checkbox" checked="checked"> <span class="checkmark"></span> </label> </form>