Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I verify jwt using "djangorestframework-simplejwt"
I am beginner in drf (Django rest framework), and now I'm making authorization logic with JWT. I heard that djangorestframework-simplejwt is most famous library in drf. I saw docs, but there are no way to verify token. (exactly i cannot find it :( ) thank you. -
My website didn't show css and Django nor python didn't run
I use VPS hosting and yes I'm learning about hosting using Django and VPS. First I set this DEBUG = False ALLOWED_HOSTS = ['*'] I followed the instruction this forum and I think I succeeded because it shows I need to install as I do in VisualStudio but when reviewing my site it renders as a plan HTML This is my picture -
javascript is not working on the back-to-top button on the blog page only
I have my Back-to-top button every pages and all the html, css and javascript is on the base file in django. Bact-to-top button is working as expected in all the pages except the blog page when it is not showing up because javascript is not working on it. I don't know why. Please help if you can. below code is the base-footer file:- {% block footer %} {% load main %} {% load static %} <style> html { scroll-behavior: smooth; } footer .back-to-top .bttBtn { display: flex; align-items: center; justify-content: center; text-decoration: none; opacity: 0; z-index: 2; } footer .back-to-top .bttBtn.active { opacity: 1; } footer .back-to-top .bttBtn.active:hover { cursor: pointer; background: #fa6742; border-color: #fa6742; } </style> <footer class="footer mt-30" style="position: relative; margin-top: 200px; text-align: center" > <div class="container" style="text-align: right"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-3"> <div class="item_f1"> <a href=" {% url 'main:aboutUs' %} ">About Us</a> <a href=" {% url 'media:ourBlog' %} ">Blog</a> <!--<a href=" {% url 'media:press' %} ">Press</a>--> </div> </div> <div class="col-lg-3 col-md-3 col-sm-3"> <div class="item_f1"> <a href=" {% url 'main:help' %} ">Help</a> <a href=" {% url 'main:helpFAQ' %} ">FAQ</a> <a href=" {% url 'main:feedback' %} ">Feedback</a> </div> </div> <div class="col-lg-3 col-md-3 col-sm-3"> <div class="item_f1"> <a href=" … -
export admin data to sql or csv
In django admin, I visualize data from several models as seen in the below image: enter image description here Would it be possible to export this data to sql or json or csv? I tried to use the django import_export library but it exported only data belonging to one of the models and not all fields and foreign keys. -
Are there any packages in laravel like DjangoRestFramework in Django?
I am a Django developer. I am working with it for a year now. I use DRF for my APIs. I am planning to switch to laravel for a project. Is there anything like DRF in laravel that I can use to easily create the APIs? -
How I can fetch a sp of sql server in django with calling a parameter
I'm very amature in django. And Now I wanna fetch a sp of my database(sql server) with calling one its parameter? Help and guide me please... Tnx alot -
Django - Hide server name in css/js file response
Delete 'Server' response header in Django framework - V3.0.5 The solution given in the above link didn't work. If you click on img/css/js file and see the response header. The server name is visible there. -
Redis server starts behaving erratically and stops functioning properly. Causing other services to malfunction
I have a docker-compose file with 4 containers, one of which is Redis. The image builds up properly and runs properly initially but after some time (sometimes it happens within 10 minutes or sometimes after a few hours) the Redis start throwing errors and my container 'worker' fails. docker-compose.yml version: '3.7' services: web: build: context: . command: gunicorn EmotAPI.wsgi:application --bind 0.0.0.0:8000 ports: - "8000:8000" container_name: web_app depends_on: - redis worker: build: context: . command: python manage.py rqworker default depends_on: - web - redis nginx: build: ./nginx ports: - "80:80" depends_on: - web redis: image: "redis:latest" restart: always ports: - "6379:6379" command: redis-server --save 20 1 --loglevel warning volumes: - redis:/data volumes: redis: driver: local redis error log (after which functions start to fail) 1:S 06 Jul 2022 08:03:53.556 # Failed to read response from the server: Connection reset by peer 1:S 06 Jul 2022 08:03:53.556 # Master did not respond to command during SYNC handshake 1:S 06 Jul 2022 08:03:54.567 # Failed to read response from the server: Connection reset by peer 1:S 06 Jul 2022 08:03:54.567 # Master did not respond to command during SYNC handshake 1:S 06 Jul 2022 08:03:56.509 # Wrong signature trying to load DB from … -
Amazon Linux2 AMI deployment
` packages: yum: python3-devel: [] mariadb-devel: [] mesa-libGL: [] gcc: [] libcurl-devel: [] amazon-linux-extras: [] option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: eagle_eye.settings PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: eagle_eye.wsgi:application container_commands: 01_make_migrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true 03_createsuperuser: command: "source /var/app/venv/*/bin/activate && python3 manage.py create_user" leader_only: true 04_static: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic --noinput" leader_only: true 05_redis: command: "sudo amazon-linux-extras enable redis6 && sudo yum -y install redis" leader_only: true 06_metadata: command: "sudo yum clean metadata" leader_only: true 07_celery: command: "sudo systemctl start redis" leader_only: true ` I am deploying Django application that makes use of celery for queuing.How to install redis package via .ebextension file.In .ebextension file I am specifying amazon-linux-extras: [].Can anyone help me out. -
How to Store the Data in Database from dropdown in Djngo
Here is my code I am working on student management project and I am unable to get the branch for student as it is foreignkey of Course model to Student model and I want to get the selected option into student model in branch row models.py class Course(models.Model): id=models.AutoField(primary_key=True) course = models.CharField(max_length=50) course_code = models.BigIntegerField(null=True) def __str__(self): return self.course class Student(models.Model): id=models.AutoField(primary_key=True) user=models.OneToOneField(User,on_delete=models.CASCADE) branch=models.ForeignKey(Course,on_delete=models.CASCADE,null=True,blank=True) middle_name=models.CharField(max_length=50,null=True) roll_no=models.IntegerField() mobile_no=PhoneNumberField(default='') parents_mobile_no=PhoneNumberField(default='') division=models.CharField(max_length=10,null=True) batch=models.CharField(max_length=10,null=True) def __str__(self): return self.user.first_name + " " + self.user.last_name views.py def studentregister(request): if request.method == 'POST': first_name = request.POST['first_name'] middle_name = request.POST['middle_name'] last_name = request.POST['last_name'] email = request.POST['email'] branch= request.POST['branch'] division = request.POST['division'] roll_no = request.POST['roll_no'] mobile_no = request.POST['mobile_no'] parents_mobile_no = request.POST['parents_mobile_no'] pass1 = request.POST['password'] pass2 = request.POST['confirmpassword'] if pass1 == pass2 : if User.objects.filter(email=email).exists(): return HttpResponse('User already exsits') else: user = User.objects.create_user(email=email, password=pass1, first_name=first_name, last_name=last_name) user.save(); studentdetails = Student ( user=user, middle_name=middle_name,roll_no=roll_no,mobile_no=mobile_no,parents_mobile_no=parents_mobile_no, branch=branch,division=division) studentdetails.save(); return render (request, 'ms/homepage/index.html') else: return HttpResponse('password does not match') else: return HttpResponse('failed') def staffstudent(request): if request.user.is_authenticated and request.user.user_type==3: courses = Course.objects.all() return render(request, 'ms/staff/student.html',{'courses':courses}) else: return render(request,'ms/login/login.html') html file as student.py <form action="studentregister" method="POST" style = "background-color:#011B3C;"> {% csrf_token %} <div class="form-group" name="branch"> <select > <option selected disabled="true">Branch</option> {% for course in courses%} <option>{{course.course}}</option> … -
Problematic error : Didn't return an HttpResponse object. It returned None instead
I am tasked with making a shopping crud project with models Products,categories,sub_categories,size,colors. Categories and subcategories are connected via foreign keys and I am using SERAILIZERS.the problem is that when I try to insert the data into sub Categories it doesnt come in both the database and the webpage I also tried value = "{{c.category_name}}" as well in select dropdown as well below are the models class Categories(models.Model): category_name = models.CharField(max_length=10) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) functions of sub catgeories and categories def show_sub_categories(request): showsubcategories = SUBCategories.objects.filter(isactive=True) #print(showsubcategories) serializer = SUBCategoriesSerializer(showsubcategories,many=True) print(serializer.data) return render(request,'polls/show_sub_categories.html',{"data":serializer.data}) def insert_sub_categories(request): if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return redirect('sub_categories:show_sub_categories') else: print(form.errors) else: insertsubcategories = {} form = SUBCategoriesSerializer(data=insertsubcategories) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category.data} if form.is_valid(): print(form.errors) return render(request,'polls/insert_sub_categories.html',hm) html of show sub_categories and insert subcategories respectively <td>category name</td> <td> <select name="category_name" id=""> {% for c in context %} <option value="{{c.id}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>sub categories Name</td> <td> <input type="text" name="sub_categories_name" placeholder="sub categories "> </td> </tr> <tr> <td>Sub categories … -
DJANGO - How to send a user from the admin site to a custom view?
I developed an application using the framework provided by Django. I developed CRUD functions using the admin site. However, I would like to redirect a user (if click on a link or button) to another view, a customized one. In my case, if a user is on the change_list template of the admin site and clicks on a button named import file, he will be redirected to a customized view. Change_list template with import file button To do that I developed the following code in the admin.py file concerning the MeasurePoint model. admin.py: @admin.register(MeasurePoint) class MeasurePointAdmin(admin.ModelAdmin): #ALL ATTRIBUTES OF THE CLASS change_list_template = "import/import.html" def get_urls(self): urls = super().get_urls() my_urls = [ path('importFile/', self.importFile), ] return my_urls + urls def importFileView(self, request): context = dict( self.admin_site.each_context(request) ) return TemplateResponse(request, "import/import.html", context) BASE_DIR/'templates/import/importFile.html {% extends 'admin/change_list.html' %} {% block object-tools %} <form action="importFile/" method="GET"> {% csrf_token %} <button type="submit">Import file</button> </form> {{ block.super }} {% endblock %} Nothing works I'm completely lost between the admin class, the customized view importFileView, and the customized template. I have plenty of different errors. I would like to understand more about how everything works and also find a solution to what I want to do. … -
Django - model.objects.all.exists() vs model.objects.exists()
Which one would be the faster and efficient way to check if any record exists in a table? We can use either model.objects.all.exists() or model.objects.exists(). But which one should be preferred? -
Create multiple unique Owl Carousels for each image object in model
I have a model of image data for a art gallery web app I am making. The homepage displays a grid of images each with its own specific data like image name, description, price etc. When you click on an image, a modal pops up and this is where I want to generate a unique Owl Carousel that will contain more images (front, back, left, right, different angles, etc.) of that painting that was clicked. As I currently have it, no matter which painting I initially click on, only one carousel is being created in the modal which contains every single image that I added in the admin page, which is not what I want. I want to have a separate specific carousel created for each picture object that grabs that object's pictures only. Any ideas? Thank you for the help. Here is my models.py: class Portrait(models.Model): name = models.CharField(max_length= 100) painting = models.ImageField(upload_to= 'paintings') long_description = models.TextField() price = models.IntegerField() short_description = models.TextField() # these are the images that will be displayed in the carousel painting_left = models.ImageField(upload_to= 'carousel_paintings') painting_right = models.ImageField(upload_to= 'carousel_paintings') painting_top = models.ImageField(upload_to= 'carousel_paintings') painting_bottom = models.ImageField(upload_to= 'carousel_paintings') painting_back = models.ImageField(upload_to= 'carousel_paintings') # name the objects … -
Select Multiple In Django Admin Form File Upload
I currently have 2 models: class Item(models.Model): title = Models.CharField(max_length=100) ... class Photo(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='photos') photo = models.ImageField() I want to be able to have one upload file field in the admin form for the item model, and be able to select multiple images at once, which are all then uploaded to the Photo model with the associated ForeignKey to the item object. In the admin.py file i tried using inline: class PhotoAdmin(admin.StackedInline): model = Photo class ItemAdmin(admin.ModelAdmin): inlines = [PhotoAdmin] class Meta: model = Item But that just gave multiple fields, rather than one field where I can select multiple images and upload them all. -
Django models error, Now I want subtract from one charfiled other, but always equal to 0, like a default,. I'm beginner with working with django
models.py -- there i create leave_links 10g field and want calculate him like substract by_projects_10g with on_facts_10g class KT(models.Model): by_projects_10g = models.CharField(max_length=255) by_projects_100g = models.CharField(max_length=255)enter code here on_facts_10g = models.CharField(max_length=255) on_facts_100g = models.CharField(max_length=255) #now I want do like this, but an error comes out leave_links_10g = models.IntegerField(default=0) def calculate_leave_links(a,b): leave_links_10g = a -b return leave_links_10g def query_links(self): calculate_leave_links(self.by_projects_10g, self.on_facts_10g) #####views.py def index(request): KT_links = KT.objects.all().values() template = loader.get_template('index.html') context = { 'KT_links': KT_links, } return HttpResponse(template.render(context, request)) -
why one of my components does not work in my django-react app?
I'm new to react and for my project i need carousel which i used react-multi-carousel package for that.after that i connected my react app to my django app with using npm run build and now the problem is that this component (named it slider.js )dosen't work fine it just render the buttoms but not images and even styles of it i but it's work just fine in react didn't find solutions by my searches heres the project directory tree and heres the view of how my component looks like and django static in settings.py: STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, '../frontend/build/assets')] and in fronted/build/index.html: <!doctype html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"/> <link href="favicon.ico"/> <meta name="viewport" content="width=device-width,initial-scale=1"/> <meta name="theme-color" content="#000000"/> <meta name="description" content="Web site created using create-react-app"/> <link href="./logo192.png"/> <link href="./manifest.json"/> <link type="text/css" href="{%static 'styles.css' %}" rel="stylesheet" > <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" > <title>React App</title><script defer="defer" src="{% static 'js/main.891355db.js'%}"> </script> <link href="{% static 'css/main.450b181d.css'%}" > </head> <body style="padding:0;margin:0"> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> </body> </html> -
request.user not available in Streamblocks subtemplate
In my main template I can call: {% load static wagtailuserbar wagtailcore_tags %} {% load navigation_tags %} {% if request.user.is_authenticated %} You're logged in {% endif %} but if I call this in my StreamBlock sub-template, it doesn't work. {% load wagtailcore_tags wagtailimages_tags %} {% if request.user.is_authenticated %} <div class="container"> ... </div> {% endif %} Any ideas? -
requests.exceptions ConnectionError Connection aborted.', ConnectionResetError(104, 'Connection reset by peer')
We have implemented a program to broadcast the commentary of sports, which will take data from firebase when firebase is triggered by data and send data to telegram channel. Everything has been good for so long. But recently we have been facing this connection reset issue? Can anyone please help? I have already tried to use time.sleep() function. But still there is issue. This problem exactly happens after running commentary for some time. It works well for sometime and then comes this error. Note: During commentary we may send 4/5 request per second. [2022-07-05 17:15:34,842: WARNING/ForkPoolWorker-2] Traceback (most recent call last): [2022-07-05 17:15:34,843: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 703, in urlopen [2022-07-05 17:15:34,845: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,846: WARNING/ForkPoolWorker-2] httplib_response = self._make_request( [2022-07-05 17:15:34,846: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,847: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 386, in _make_request [2022-07-05 17:15:34,848: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,849: WARNING/ForkPoolWorker-2] self._validate_conn(conn) [2022-07-05 17:15:34,849: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,850: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 1040, in _validate_conn [2022-07-05 17:15:34,851: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,852: WARNING/ForkPoolWorker-2] conn.connect() [2022-07-05 17:15:34,852: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,853: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/connection.py", line 414, in connect [2022-07-05 17:15:34,854: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,855: WARNING/ForkPoolWorker-2] self.sock = ssl_wrap_socket( [2022-07-05 17:15:34,855: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,856: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/util/ssl_.py", line 449, in ssl_wrap_socket [2022-07-05 17:15:34,857: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,858: WARNING/ForkPoolWorker-2] ssl_sock = _ssl_wrap_socket_impl( [2022-07-05 … -
Adapt global PAGE_SIZE setting in Django REST Framework's browsable API to a different local PAGE_SIZE setting
We are using the Django REST Framework with pagination and a browsable API. The global parameter for the page size in settings.py is set to 10000 in order to get higher performance when accessing the API via HTTP requests which works well: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ], "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10000, } Now the problem is that this is directly linked to the browsable API which also lists 10000 entries per page. This of course takes very long or even breaks within certain browsers. Is there a way to change this behaviour locally for the browsable API? Thanks in advance! -
Writing to Firestore with Firebase Admin SDK causes app to freeze
I am trying to use Firebase Admin SDK in a Django app using a service account. I followed the instructions as per the official documentation. However, the app gets stuck at the point when Firebase Admin is attempting OAuth2 using Google APIs. My code is as follows: import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credentials.Certificate(key_path)# path to serviceAccountKey firebase_admin.initialize_app(cred) db = firestore.client() doc_ref = db.collection(u'users').document(u'alovelace') # The following causes the app to freeze doc_ref.set({ u'first': u'Ada', u'last': u'Lovelace', u'born': 1815 }) The last message displayed in logs is: 2022-07-06 06:23:38,519 DEBUG Making request: POST https://oauth2.googleapis.com/token The app freezes after that message with no additional info. Any ideas why is this happening? -
Problems with connecting django codebase which in wsl to mysql database on xampp in windows
A few weeks ago I was working on an old laptop on a project in wsl connected to mysql database in xampp on windows which had no problems. I had to switch to a new laptop in which im facing the error. ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (111) [![Xampp control panel][1]][1] Configuration settings in settings.py file DATABASES = { 'default': { 'NAME': 'care_new', 'ENGINE': 'django.db.backends.mysql', 'USER': 'Canopus', 'PASSWORD': 'care', 'HOST': '127.0.0.1', 'PORT': 3306, 'OPTIONS': { 'autocommit': True, }, } } I'm using a venv. python - 3.8.10 pip - 22.1.2 using the command sudo lsof gives this output (venv) vishal@BatComputer:~/caremigration$ sudo lsof -i :3306 (venv) vishal@BatComputer:~/caremigration$ Please help me connect to this database in windows. I have tried out different stackoverflow answers such as editing my.cnf file and such. Also worth mentioning, in my linux folders, my.cnf file has no content, its actually named as mysqld.cnf [1]: https://i.stack.imgur.com/va6DF.png -
Django import-export error reporting for rows
I am using Django Import export for creating a data upload endpoint. However, in case there is an error while uploading the data, I want to know which row numbers have an issue and what the issue is. If there is an error on line 50 and line 60, then it should tell me that both lines 50 and 60 have errors. Currently, if I use raise_errors method then it only shows the error on line 50 and then stops checking. I can do a line-by-line iteration but that method is considerably slow. How can I achieve this? -
default=Ture not working in BoloeanField using Django
class SoftDeleteTimeStampMixin(TimeStampedModel): is_active = models.BooleanField(default=True) class Meta: abstract = True i created an abstract class for using for all models here model where I use class Schedule(SoftDeleteTimeStampMixin): day_of_week = models.CharField(max_length=200) partner = models.ForeignKey(User, on_delete=models.PROTECT, related_name="schedules") def __str__(self): return f"Schedule of {self.partner.username} on {self.day_of_week}" when I create an instance of my model is_active value is false, but it should be True -
Django DB Migration InconsistentMigrationHistory when running migrate
I am unable to migrate my django after running python ./manage.py migrate. This is what showmigrations is displaying customerweb [X] 0001_initial [X] 0002_user_industry [X] 0003_auto_20220209_1737 [X] 0004_userconfiguration_night_surcharge_exempt [ ] 0005_auto_20220614_1100 [X] 0006_orderdelivery_is_order_unique [ ] 0007_orderdelivery_client_reference_no I have tried --fake as well as trying to move back by one migrate using python ./manage.py migrate <app_name> <000x_migrate_file> all these is not working as the exeception keeps prompting InconsistentMigrationHistory. I have tried deleting the migration folders as well (keeping init only) but does not work as well.