Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/React CORS/Session Cookies only storing on Local Development, not Production Env
I have a web application using CSRF and Session tokens being stored as cookies. My backend application is built on Django. My frontend application is built with React and my requests are being made through the Axios library. Everything works perfectly in development. I can see the CSRF token stored in the browser and I can see the Session token stored after login. After deploying the application, both tokens are no longer stored in the browser. The application is deployed on Heroku and I'm using a custom domain. The only noticeable difference between development and production is my requests are being made over HTTPS. Any help would be appreciated. Below are my CORS settings in my settings.py file and my headers in my Axios requests. CSRF_COOKIE_SAMESITE = "Lax" SESSION_COOKIE_SAMESITE = "Lax" SESSION_COOKIE_HTTPONLY = True if config("ENVIRONMENT") == "DEVELOPMENT": CORS_ORIGIN_WHITELIST = ["http://localhost:3000"] else: CORS_ORIGIN_WHITELIST = ["https://biz.mywebsite.com"] CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = default_headers + ("Access-Control-Allow-Origin",) Axios { withCredentials: true, credentials: "include", headers: { Accept: "application/json", "Content-Type": "application/json", "X-CSRFToken": cookies.get("csrftoken"), } } -
How to filter Serializers in DjangoRestFramework based on user id?
I'm new to django, I can't seem to find how to return an api based on the user who requested it and created the Transaction object, can you please guide me through? I have read this, but I can't find a clear guide in the docs to update the Serializer straightaway. In laravel, I can do: Transaction::where('user_id', Auth::user()->id)->get(); This is my serializer: class TransactionSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer(read_only=True) tags = TagShortSerializer(read_only=True, many=True) def get_fields(self, *args, **kwargs): # Override this method so that the list of DatabaseUsers presented in the browseable API # is restricted to the DatabaseUsers owned by the current user. fields = super(TransactionSerializer, self).get_fields(*args, **kwargs) view = self.context["view"] user = view.request.user return Transaction.objects.filter(user=user) class Meta: model = Transaction fields = ["user", "title", "amount", "category", "tags"] My viewset: class TransactionViewSet(viewsets.ModelViewSet): queryset = Transaction.objects.all() serializer_class = TransactionSerializer permission_classes = [permissions.IsAuthenticated, IsOwner] Currently it returns: -
403 CSRF verification failed on Safari Private browser
can't figure it out why CSRF verification failed on safari private browser. Other rest of the browser all seems fine. Also have tested on safari browser but its working there but not on safari private browser. -
Django Admin /img not found
So iam learning Django at the moment but iam kinda stuck with this problem. I have a django app called projects, in which iam showing 3 projects (don't mind the lines around everything, i did this to better learn CSS and Bootstrap containers). So next feature i tried to implement, is that i can change these projects names etc. in the admin view page. I got it all working and i am seeing the projects. But when iam clicking on a project a get this error. So that is the path to the image folder which is defined in my models.py file: from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path="/img") How can I fix this? -
Submit a file in angular using Django
I'm trying to send a file from an angular frontend to Django, I have this code that uses a basic drag and drop file submission box but I cant get the file to process in typescript. formData.append('file', this.form.get('dragndrop')!.value); throws the error TypeError: Cannot read property 'setValue' of null in my browser console but I don't understand why. Am I missing something? I've set up a basic file submission box that works perfect, the file gets sent to the server with ease. Its only when I use this format of file submission does it happen HTML Component: <div class="dropzone" [class.visible]="onDragViewVisible" (dragenter) = "changeView($event)" (dragleave) = "changeView($event)" (drop) = "onFileDrop($event)" [formGroup]="form" > <input type = "file" name="dragndrop"/><br/><br/> <span class = "uitk-icon uitk-icon-folder_open lg-icon"></span><br /> <h3>Drop file here</h3> </div> Typescript: onFileDrop(event: any) { event.preventDefault(); console.log(event.dataTransfer.files); this.processFile(event.dataTransfer.files); } private processFile(files: FileList){ if(files[0].type == "application/vnd.ms-excel" || files[0].type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){ this.displayConfirmationView(); console.log(files[0]); if (files.length > 0) { const file = files[0]; this.form.get('dragndrop')!.setValue(file); } console.log(files[0]); const formData = new FormData(); formData.append('file', this.form.get('dragndrop')!.value); this.uploadService.upload(formData).subscribe( (res) => { this.response = res; this.imageURL = `${this.DJANGO_SERVER}${res.file}`; console.log(res); console.log(this.imageURL); }, (err) => { console.log(err); } ); } else { this.errorDialog.displayNotification(); this.displayDefaultView(); } } -
How to display a video that is not in static or media folder in Django Template?
I'm trying to add a video with html video tag in the Django template. The video path should come from /var/www/videos path. I have tried these settings below. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets/static"), '/var/www/videos/', ] STATIC_ROOT = os.path.join(BASE_DIR, "assets/staticfiles") Also, my urls.py file is below. urlpatterns = [ path('', index, name='index'), path('terms/', terms, name='terms'), path('privacy/', privacy, name='privacy'), path('error_page/', error, name='error'), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and I have added the video to the template as follows. <video src="{% static 'test101/test101_2021-07-13-12-35-16.mp4' %}"></video> However, I'm getting Failed to load resource: the server responded with a status of 404 (Not Found) error. How can I fix this issue and display my video on the Django template? -
How to change text color of certain row in django admin result list
When we enter the django admin site, we can see the result list of Modeladmin. And I want to change the row text color depending on the certain field value. How can i change text color of row when the field has a certain value? -
Django html page not updating on refresh
I want to know how to update the values in the html page with a simple refresh rather than having to restart the server, Has anyone come accross this and how can I fix it? -
CSS grid in landing django project
Right now I'm on the final stage of my landing project. Trying to understand css grid, but a little bit confused with the my previous code. Here is my image: IMAGE source I would like to center horizontaly and verticaly icons and text with the title in the white background box. Will be very thankful for the help <!DOCTYPE html> {% load static %} <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Home page</title> <link rel="stylesheet" href="{% static 'style.css' %}"> <script src="https://kit.fontawesome.com/5476287230.js" crossorigin="anonymous"></script> </head> <body> <div class="social-menu"> <ul> <li><a href="https://www.instagram.com/kseniia_ifbb_latvia"><i class="fab fa-instagram"></i></a></li> <li><a href="https://www.tiktok.com/@kseniiasherr"><i class="fab fa-tiktok"></i></a></li> <li><a href="https://www.facebook.com/profile.php?id=100009190064504"><i class="fab fa-facebook"></i></a></li> </ul> </div> <div class="title"> <h1>ЧТО ВЫ ПОЛУЧАЕТЕ?</h1> </div> <div id="background"></div> <div class="icons"> <li><i class="fas fa-utensils"></i></li> <li><i class="fas fa-dumbbell"></i></li> <li><i class="fas fa-clock"></i></li> <li><i class="fas fa-heartbeat"></i></li> </div> <div class="icons-text"> <li> <h1>План питания с учетом Ваших вкусовых потребностей</h1> </li> <li> <h1>Тренировки для любого уровня подготовки</h1> </li> <li> <h1>Максимально быстрые результаты</h1> </li> <li> <h1>Тело, о котором Вы могли только мечтать</h1> </li> </div> </body> </html> and: body { background: url(https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=889&q=80) no-repeat center center fixed; background-size: cover; margin: 0; } #background { position: fixed; top: 35%; width: 100%; height: 20%; background-color: white; z-index: -1; opacity: 0.8; } .social-menu ul { position: absolute; top: 25%; left: … -
How to combine two columns in one in Django?
How to combine two columns in one in Django? What is equivalent to "select col1 | col 2 as bothcols from tbl ..." ? -
python django how save a input field under a associate user
I am trying to save a todo text under a associat user How to do that i attach my models.py file, forms.py file and views.py file. Please Help meenter image description here -
how top pass data to javascript in django
I am looking for a way to pass data to the index.js script from django view. Sample simple view: def map_display(request): data = [ {'lat': 52.20415533, 'lng': 21.01427746}, {'lat': 52.20418, 'lng': 21.014386}, ] data = json.dumps(data) return render(request, 'index.html', {"data": data} ) How to pas list data to flightPlanCoordinates variable? index.js function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 3, center: { lat: 0, lng: -180 }, mapTypeId: "terrain", }); const flightPlanCoordinates = {{ data}}; # <--- pass here const flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(map); } index.html <html> <head> <title>Simple Polylines</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <link href= "{% static 'css/style.css' %}" rel="stylesheet" type="text/css"> <script src="{% static 'js/index.js' %}" ></script> </head> <body> <div id="map"></div> <script src="https://maps.googleapis.com/maps/api/js?key=........=initMap&libraries=&v=weekly" async ></script> </body> </html> -
Why do I get "CommandError: App 'app_name' does not have migrations." when using Heroku?
So I have deployed my Django project to Heroku, and now trying to migrate the database. I have everything working fine in my local sever. Then I tried to run the commands in heroku, as below. heroku run python manage.py makemigrations app_name'. This worked fine. Migrations for 'app_name': contents\migrations\0001_initial.py - Create model Book - Create model Category - Create model Content Then of course, I tried : heroku run python manage.py migrate app_name. But then I got this error CommandError: App 'app_name' does not have migrations. I've done some research for possible issues, none of which were relevant to mine. For example I do have __init__.py in the migrations folder inside app_name directory. Also, I've tried heroku run python manage.py migrate as well as heroku run python manage.py migrate app_name. I'm very confused. What do you think is the problem? Thanks in advance. :) -
Django Crispy Form & <select> tag
Is it possible to use crispy-form for < select > tags? "|as_crispy_field" doesn't help here <select id="food" name="food"> <option value="" selected="selected">---------</option> {% for object in form.fields.food.choices %} <option value="{{ object.0 }}" class="{{ object.1 }}">{{ object.2 }}</option> {% endfor %} </select> -
AttributeError: Got AttributeError when attempting to get a value for field
**job model** class JobPost(models.Model): creater = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=255) job_type = models.ForeignKey( JobType, on_delete=models.CASCADE) job_loc = models.ForeignKey(JobLocation, on_delete=models.CASCADE) cmpny_name = models.ForeignKey( Company, related_name='company', on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) job_description = models.CharField(max_length=255) salary = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return str(self.job_type) company serializer class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' post serializer class PostSerializer(serializers.ModelSerializer): # job_loc = JoblocationSerializer(many=True) companies = CompanySerializer(source='company', many=True) class Meta: model = JobPost fields = '__all__' error i am getting AttributeError: Got AttributeError when attempting to get a value for field companies on serializer PostSerializer. The serializer field might be named incorrectly and not match any attribute or key on the JobPost instance. Original exception text was: 'JobPost' object has no attribute 'company'. -
Change field type from a parent model with _meta.get_field()
I have the following model which inherits from user and has a signal to be created. However, I want to change the email field on the User model from email to string. Here is my model: class Seeker(User): birthdate = models.DateField(null=True, blank=True) phone_number = models.CharField(blank=True, max_length=30) open_for_job = models.BooleanField(default=False) latitude = models.DecimalField( max_digits=9, decimal_places=6, null=True, blank=True ) longitude = models.DecimalField( max_digits=9, decimal_places=6, null=True, blank=True ) class Meta: db_table = "seeker_table" def __str__(self): """ :return: Firebase UID related to Seeker """ return self.username def create_seeker(sender, instance, created, **kwargs): """ :param instance: Current context User instance :param created: Boolean value for User creation :param kwargs: Any :return: New Seeker instance """ if created: Seeker.objects.create( user_ptr_id=instance.id, username=instance.username, password=instance.password, email=instance.email, first_name=instance.first_name, last_name=instance.last_name, is_active=instance.is_active, is_superuser=instance.is_superuser, is_staff=instance.is_staff, date_joined=instance.date_joined, ) signals.post_save.connect( create_seeker, sender=User, weak=False, dispatch_uid="create_seekers" ) Is it possible? And how can I do that? -
Django Restframework - Multiple models for SearchFilter
Using Django 3.2 with Restframework. Iam trying for search filter and create a API with restframework which would output the searched term with its whole object. I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. Is there any existing document, blog on how to use multiple Models together? Or any working example. Or this the existing code for the single, how to extend it to all models? views.py class SearchView(generics.ListAPIView): queryset = MasterUser.objects.all() serializer_class = MasterUserSerializer filter_backends = [SearchFilter] search_fields = ['firstname', 'email', 'lastname'] serializer.py class MasterUserSerializer(serializers.ModelSerializer): class Meta: model = MasterUser fields = "__all__" -
Django & elixir combination
I am actually studying microservices architecture and I am thinking to use Django & elixir for two different backend services : Django for authentification and business logic. Elixir for real-time comunications My biggest concern is how to implement authentification & authorization in this context ?? -
How can I link the author of a post to his profile page with django?
[error in cmd][1] [its showing like this][2]gur.com/cD6dO.png urls.py pageviews.py page -
How can I make Django template correctly in Bootstrap5 nav-tabs?
Hi I'm new to stackoverflow. I want some help to make Django templates correctly appear in Bootstrap5 nav-tab. I embedded Django HTML template in Bootstrap5 nav-tab as following, but it doesn't apper up when I render the page. I want each tab to contain dynamically generated HTMLs by Django and to correctly show them. Does anyone have an idea to make this work? Any helps would be apprciated. Thanks! <div class="container"> <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Abstract</a> <a class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false">Questions</a> <a class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" href="#nav-contact" role="tab" aria-controls="nav-contact" aria-selected="false">FAQ</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab"> ... </div> <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab"> <div class="mb-3"> {% for item in question_list %} {{ item.question_id }} {% endfor %} </div> </div> <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">...</div> </div> </div> -
display already created Mysql database table with Django
I am very beginner in Django. I have just questions. I search and watched a lot of videos about Django and there tutors were creating classes for database then run it and boom, in the database and in the table there were columns. What if I already have a table and I just want to display . Is this possible ? So my goal is to display my table from database with pagination and then possibility to make querying. if there is any example of it can you show me ? Maybe something like github project or anything that helps me . Thank you in advance. Have a good day. -
How to make time slots for appointment, that admin can update every day or few days forward. Django
Im working on barber app. Admin is a barber who write time slots for every day or few days forward. Time slots can be string or integer, but i need to have exactly date that client can appointment. -
Django signals not triggered when a model object is created
I am using Django signals to trigger a task (sending mass emails to subscribers using django celery package)when an admin post a blogpost is created from Django admin. But the signal is not triggered. I have a print statement inside the signal which is not printing ie the signal is not recived after a new blog is created. My apps are set like this. My blog model: class BlogPost(models.Model): author = models.CharField(max_length=64, default='Admin') image = models.ImageField(blank=True, null=True) title = models.CharField(max_length=255) .................../ My tasks file from django.core.mail import send_mail from travel_crm.settings import EMAIL_HOST_USER @shared_task def send_mails(self,*args, **kwargs): subscribers = self.kwargs['subscribers'] blog = self.kwargs['blog'] for abc in subscribers: emailad = abc.email send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ", EMAIL_HOST_USER, [emailad], fail_silently=False) My signals.py file from .tasks import send_mails from apps.blogs.models import BlogPost,Subscribers from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=BlogPost) def email_task(sender, instance, created, **kwargs): print(123456789) if created: print(123456789) subscribers = Subscribers.objects.all() blog = BlogPost.objects.latest('date_created') print(blog) # task = send_mails(subscribers, blog) # task.delay() send_mails.delay(subscribers,blog) My init file from __future__ import absolute_import, unicode_literals from apps.blogs.celery_files.celery import app as celery_app __all__ = ('celery_app',) -
error in my view function in Django 'decimal.Decimal' object is not iterable
Please give some help or some hint why i am getting this error in my view function def EmployeeRateView(request): msg = '' try: fromDate = request.POST.get('fromdate') except: msg = "Pleas enter valid date" if request.method == 'POST': RateData = EmployeeRate.objects.filter(Site=request.user.SuperVisor.Site,DateFrom=fromDate) return render(request,"employeerate.html",{"EmployeeRate":RateData,"msg":msg}) else: print("get") rate = Rate.objects.filter(Site=request.user.SuperVisor.Site) EmpDetails = EmployeeRegistration.objects.filter(Site=request.user.SuperVisor.Site,Status="Working") for employee in EmpDetails: for get in rate: print("date",get.fromDate) if(employee.Site==get.Site and employee.Category==get.Category and employee.Department==get.Department): try: check = EmployeeRate.objects.get(EmpId=employee.EmpId,DateFrom=get.fromDate) print("found",check.EmpId,check.Name,get.fromDate) except: print("not found",check.EmpId,check.Name,get.fromDate) rate = get.Basic+get.Da print(rate) print("basic",get.Basic,"da",get.Da,"rate",rate) EmployeeRate.objects.create(EmpId=employee.EmpId, Name=employee.Name, Site=employee.Site, Basic=get.Basic, Da=get.Da,Rate=rate, Hra=get.Hra, Ca=get.Ca, SplAllow=get.SplAllow, CanteenAllow=get.CanteenAllow, DateFrom=get.fromDate) context = {'EmployeeRate':EmployeeRate.objects.filter(Site=request.user.SuperVisor.Site).order_by('Name'),'msg':msg} return render(request,"employeerate.html",context) Here is my error in my terminal as well as in my browser Basically i am trying to save or create some data in EmployeRate model based on filter and condition. But at the end it giving me this type of error. I can't able to understand why it is showing like this. -
Django file uploader throwing error "cannot pickle '_io.BufferedRandom' object" while uploading more thank 2.5mb of image using celery
i am trying to upload image files in Django, i am sending the upload task into the task queue using celery, but when I upload image files larger than 2.5mb it crashes with this error cannot pickle '_io.BufferedRandom' object i have added some settings options to Django but that does not work. celery application settings FILE_UPLOAD_MAX_MEMORY_SIZE = 90005000 CELERY_BROKER_URL = os.environ.get('REDIS_TLS') CELERY_ACCEPT_CONTENT = ['pickle', 'application/json'] CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_BACKEND = 'django-db' is there any way I can solve this issue, a reminder when am uploading the image files using Django alone, it works regardless the size, so the issue is from celery not been able to work with file larger than 2.5MB