Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Paginate Django without changing url
I have multiple tables in my documents_list view. Each of them has pagination (Django paginator) and when I click next button url changes, and table is hiding again. How can I fix this problem ? P.S: I'm using Bootstrap tables, and when page is initializing all tables are hidden by default, after clicking according button table is showing. And I want stay on current table when changing page. html: ... <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}">prev</a> {% endif %} <span class="current"> {{ page_obj.number }} </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> views.py: ... claim_documents = ClaimDocument.objects.all().order_by('-created_date') paginator = Paginator(claim_documents, 2) page = request.GET.get('page', 1) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'page_obj': page_obj, ... } -
In Django , Is it possible to migrate any perticular specific file?
Currently I am learning django and learning migration related stuff. I have found that we can migrate specific app using python manage.py migrate app-name but not found how to migrate specific migration file named python manage.py migrate 0024_auto_20200827_0706.py. If I will do python manage.py migrate 0024_auto_20200827_0706.py, it will revert migration from this point or file but not doing migrate for this specific file. My question : is it possible to do migrate for specific file if yes then How is it possible? Thanks. -
pyodbc error "SystemError: <class 'pyodbc.Error'> returned a result with an error set"
I was developing a reporting dashboard using Django. I'm pulling data from an outer database (ms SQL server 2012) using django-pyodbc-azure. I was facing a weird problem when I pulling data in my localhost using manage.py runserver it can pull the data from the database but when I run the same query in my production server its returns this error. The query is a bit big it takes 50 seconds + time. SystemError: <class 'pyodbc.Error'> returned a result with an error set my production server is ubuntu 18.4 and Nginx. I do a few google searches but not find any answer. -
Using asgi alongside wsgi with Apache as reverse proxy
I have a Django application, which will serve both HTTP requests and websocket connections. I red in several articles that using wsgi is more recommended for HTTP requests, than asgi, but I need also the asgi for websockets. Is it good practice to use Apache server, which will serve the incoming wsgi requests with mod_wsgi modul, and also use it as reverse proxy for the asgi requests, basically redirecting them to a daphne server? Do you have other recommendation for this structure? -
home/bitnami/apps apps folder not found on aws ligthsail
bitnami@ip-23-45-56-230:~$ ls bitnami_application_password bitnami_credentials htdocs stack bitnami@ip-23-45-56-230:~$ cd apps -bash: cd: apps: No such file or directory -
pip install django-allauth- Error: No module named 'allauth.socialaccountallauth' python django?
I'm trying to add social authentication to my login page . for that i have installed pip install django-allauth to my project. I have added required apps it to the INSTALLED_APP, added AUTHENTICATION_BACKENDS, SITE_ID and the path to the project urls.py you can check for the tutorial here https://django-allauth.readthedocs.io/en/latest/installation.html the thing is when i try to migrate it raises the following error ModuleNotFoundError: No module named 'allauth.socialaccountallauth' how can I solve it. If anyone can hepl me with it. one thing that i feel could be the problem is that i already have an app named accounts_app in my project which have the path path('accounts/', include('accounts_app.urls')), and the socialauth path is path('accounts/', include('allauth.urls')), if this could be the problem then how can i solve it without changing my accounts_app. -
better way to write def __str__(self) in django model
I am writing a django app. I'm curious if there is a better way of writing the python "magic method" __str__() that returns a string representation of any object. Currently, following the Django docs I find that you can do the following... class Todo(models.Model): firstName = models.CharField(max_length=30) secondName = models.CharField(max_length=30) def __str__(self): "%s %s" % (self.firstName, self.secondName) Fine and dandy but if I have 8, or even more fields, then it gets kind of annoying to do this. First I find myself counting how many fields I want and make sure to write out %s that many times just to then write out self. the same amount of times and this really sucks. I was hoping to if anyone knows of easier ways of writing this out and if there are what are the differences. I haven't been able to find another method online so I'd appreciate some help. -
can't able to pass models in template django
i am trying to pass models value in template as listview to show the cart list but it don't showing anything viwes.py class OrderNavSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'nav.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") i want to pass the context in nav.html nav.html <ul class="header-cart-wrapitem"> {% for order_item in object.items.all %} <li class="header-cart-item"> <div class="header-cart-item-img"> <img src="{% static 'images/item-cart-01.jpg' %}" alt="IMG"> </div> <div class="header-cart-item-txt"> <a href="#" class="header-cart-item-name"> {{ order_item.item.title }} </a> <span class="header-cart-item-info"> {{ order_item.quantity }} x &#8377;{{ order_item.item.price }} </span> </div> </li> {% endfor %} </ul> -
Web frontend designer
I am trying to learn web development and I did take some Django courses. I would like to know is there some kind of "Frontend Designer" (some think similar to wordpress) that can create templates like html etc. which are easy to use for Django developer? Or are there some kind of "Frontend Designer" that are more optimized for Django? Many many thank in advance. -
Django No module named 'django.middleware.commasdon'
I have migrated the django project from 1.8.0 to 3.0.9 also renamed the project. Im getting error while running the server it shows ModuleNotFoundError: No module named 'django.middleware.commasdon' This is the log python3.7/site-packages/django/core/servers/basehttp.py", line 50, in get_internal_wsgi_application ) from err django.core.exceptions.ImproperlyConfigured: WSGI application 'project.wsgi.application' could not be loaded; Error importing module. File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.middleware.commasdon' Settings.py WSGI_APPLICATION = "project.wsgi.application" wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_wsgi_application() -
Can you change the default Add <Model name > to something custom in django admin?
I have the following in my Django admin I can change the page title by overriding render_change_form but I haven't found a way to override the Add Newspaper part. I don't want to change the verbose name since it will now read Forms > New Name > Add New Name I want it to be Forms > Newspapers > New Name -
Saving instance of Many to Many field in Django
I'm trying to enroll a student in a specific course through a model form. But it's throwing an error saying 'Student' object is not iterable. My models are: class Student(User): full_name = models.CharField(max_length=300) class Course(models.Model): course_name = models.CharField(max_length=300) author = models.ForeignKey(Teacher,on_delete=models.CASCADE,null=True) student = models.ManyToManyField(Student) course_content = models.TextField(null=True) def __str__(self): return self.course_name View def course_enroll(request,pk): objects = Course.objects.get(id=pk) form = CourseEnrollForm(instance=objects) if request.method == "POST": form = CourseEnrollForm(request.POST) if form.is_valid(): #name = Student.objects.get(username = request.user.username) name = get_object_or_404(Student,username = request.user.username) instance = form.save(commit=False) instance.save() instance.student.set(name) instance.save_m2m() print('saved') else: print('not saved') return render(request,'course/enroll.html',{"form":form}) -
How to send links through email in django?
I am learning how to send emails in django. Now, i want to try to send links as a message in email. please help me how to do it. It would be a great help. this is my views.py def send(request): send_mail( "Subject", "This is a test sample mail https://www.google.com/ ", 'sample.mail.2101@gmail.com', ['padow76087@chclzq.com'], fail_silently=False) return redirect('/') thanku for your help. -
Javascript for like button applies for only first button
I am trying making app similar to twitter in which I want to give user to ability to like the posts. but only first post works neatly. html {% if request.user in post.userl.all %} <a class="likeu" style="cursor: pointer"><span id="{{ post.id }}" class="likeu1" style="font-size:24px;color:red">&hearts;</span></a> {% else %} <a class="likeu" style="cursor: pointer"><span id="{{ post.id }}" class="likeu1" style="font-size:24px;color:grey">&hearts;</span></a> {% endif %} javascript document.querySelector('.likeu1').addEventListener('click', change_like); }) function change_like(){ m = this.style.color; if (m=='red'){ this.style.color = 'grey'; } else{ this.style.color = 'red'; } } -
How can i create views for the nested comment system in django platform?
I have set my Comment model: class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments', blank=True, null=True) commentor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='replies') class Meta: ordering = ['-created_on'] def __str__(self): return 'Comment {} ---of----- {}'.format(self.body, self.commentor) I have already create the views for the comments and have assigned the post and commentor value but i don't know how to create views for the replies and also don't know how to make the reply form for the nested comment system. Anyone who can help will be thanked from the heart. -
passing video_url to html template in django
I am trying to dispaly video in my html page by passing url as dict to template in django view named as succes def success(request): url_video="/media/video1.mp4" return render(request,"payment/success.html",{"url_video":url_video}) my template code is all clear it has no errors i am getting this error on command prompt Not Found: /succes/media/video1.mp4 I don't understand why i get success/ in front of url i have passed.The video file is in media/video1.mp4 location but it is not getting displayed.let me know any changes i need to make.thanks -
Django Reversion - How to use With Django Rest
I'm trying to use Django Reversion with my My Django Rest, but i still confuse about it or i just couldn't what i want in Document. Here what i tried `Settings INSTALLED_APPS = [ .... 'reversion' ] MIDDLEWARE = [ 'reversion.middleware.RevisionMiddleware' ] In Model @reversion.register() class History(models.Model): pass In ModelViewset from reversion.views import RevisionMixin class HistoryViewset(RevisionMixin, viewsets.ModelViewSet): queryset = History.objects.all() serializer_class = HistorySerializer filter_backends = (filters.DjangoFilterBackend,) # if pagination page = none, it will return all page def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if 'page' in request.query_params: page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Then i try to update My Model and try to GET request from api endpoint, i got null Value. What do i Missing??? I'll appreciate of all ur Help. Thanks... -
Confusion regarding Django and SECRET_KEY
Recently finished my app and I am ready to deploy it but I don't understand how to set the application's SECRET_KEY. I'm trying to change my database from sqlite to postgresql, but I get the following error: raise KeyError(key) from None KeyError: 'SECRET_KEY' development.py from nurs_course.settings.common import * ALLOWED_HOSTS = ['0.0.0.0', 'localhost'] SECRET_KEY = '9t*re^fdqd%-o_&zsu25(!@kcbk*k=6vebh(d*9r)+j8w%7ci1' DEBUG = True production.py from nurs_course.settings.common import * DEBUG = False SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: update this when you have the production host ALLOWED_HOSTS = ['0.0.0.0', 'localhost'] common.py has all the other settings required. I use Windows OS w/ Powershell. I've been stuck on this for a bit and I am just unsure how to set the SECRET_KEY properly. Any help would be appreciated! -
How can I convert this SQL query to Postgresql in Django?
I have this query that I want to write in Postgres in Django. I can phrase the query using SQL command as DELETE FROM NOTIFICATION_MESSAGES.JSONFIELD["notifications"] WHERE POST_ID=POST_ID AND ACTIVITY="LIKE"; My jsonfield looks something like this: user_id : { notifications : { post_id: post_id, activity:[like, comment...] } } } Please let me know if you need any more information. Thanks in advance! EDIT: Till Now I have tried this: notification_messages = NotificationMessages.objects.get(user__id=user) notification_messages.doc["notifications"].pop(post_id) notification_messages.doc["notifications"].pop("activity") -
Django save a new custom id every time I create a new instance
I have Product db model, which should generate a custom_id every time a new Product has been added. class Product(models.Model): # Common code = models.CharField(_("Course Code"), blank=True, max_length=100) #... Other Fields def __str__(self): return self.code def custom_seq(pk, letters=4, digits=3): """ Generates a sequence when letters=4, digits=3 then, 'AAAA000', 'AAAA001', ..., 'ZZZZ999' Generates a sequence when letters=3, digits=4 then, 'AAA0000', 'AAA0001',..., 'ZZZ9999' """ alpha_list = [string.ascii_uppercase]*letters digit_list = [string.digits]*digits for i in itertools.product(*alpha_list): for j in itertools.product(*digit_list): yield "".join(i + j) def save(self, *args, **kwargs): product_code = next(self.custom_seq()) print("Code", product_code) #-- prints `AAAA000` if self.code is None: self.code = f"{product_code}" return super(Product, self).save(*args, **kwargs) The above code has 2 issues: Everytime, I save a new product its generating only first sequence of custom_seq() ie. AAAA000. code is not getting saved but rest of the object is getting saved -
Django - save under determined condition
I want a FeedstockFormula model (it has a ratio and a name field) to save if and only if the ratio value is something different than 0 or null or blank. Ps.: I'm on a inline formset and when django adds the new empty form to it, the fields are empty, so I can't click on the button to save because it leads to an error stating 'NOT NULL constraint failed' -
ModuleNotFoundError: No module named 'AgregarUsuarios'
from AgregarUsuarios.models import admin_text as at la linea anterior me marca el siguiente error ModuleNotFoundError: No module named 'AgregarUsuarios' El scrip desde donde tengo esa linea de codigo esta en el mismo directorio que mi aplicacion, alguien me podria decir porque me da el error y como lo puedo solucionar? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'social_django', 'AgregarUsuarios', #Agregando la app con la que agrego usuarios] La aplicacion ya esta dentro de la configuracion -
Django update InMemoryUploadedFile with Piexif
I am trying to strip out exif data on an uploaded image before continuing to do some other processing to it before saving to the server. I am using piexif as in this answer to strip out the exif metadata. However, piexif.insert() documentation requires the path to the image being modified. Can piexif be used to write to a file in memory? An InMemoryUploadedFile has a name attribute which seems to provide the path to the file, however it is not working as expected. def modifyAndSaveImage(): # Get the uploaded image as an InMemoryUploadedFile i = form.cleaned_data['image'] # Use piexif to generate an empty exif byte dump exif_bytes = piexif.dump({}) piexif.insert(exif_bytes, i._name) # What should the second parameter be? # continue using i... -
Why does my websocket keep disconnecting in Django Channels App?
I have been on this for a month now without a working solution. Everything works fine in production but I have been trying to deploy my django-channels application using nginx as reverse proxy, supervisor to keep servers running, gunicorn to serve http requests and I am stuck at the weboscket request part using daphne to process http requests. I am bindig with unix sockets: gunicorn.sock and daphne.sock The Console returns: WebSocket connection to 'ws://theminglemarket.com/ws/chat/undefined/' failed: Error during WebSocket handshake: Unexpected response code: 500 My supervisor config: directory=/home/path/to/src command=/home/path/to/venv/bin/gunicorn_start user=root autostart=true autorestart=true redirect_stderr=true stdout_logfile=/path/to/log/gunicorn/gunicorn-error.log [program:serverinterface] directory=/home/path/to/src command=/home/path/to/venv/bin/daphne -u /var/run/daphne.sock chat.asgi:application autostart=true autorestart=true stopasgroup=true user=root stdout_logfile = /path/to/log/gunicorn/daphne-error.log Redis server is up and Running, Sure of that, using redis-server my nginx configurations: upstream channels-backend { # server 0.0.0.0:8001; server unix:/var/run/daphne.sock fail_timeout=0; } upstream app_server { server unix:/var/run/gunicorn.sock fail_timeout=0; } server { listen 80; listen [::]:80; server_name theminglemarket.com www.theminglemarket.com; keepalive_timeout 5; client_max_body_size 4G; access_log /home/path/to/logs/nginx-access.log; error_log /home/path/to/logs/nginx-error.log; location /static/ { alias /home/path/to/src/static/; # try_files $uri $uri/ =404; } location / { try_files $uri @proxy_to_app; } location /ws/ { try_files $uri @proxy_to_ws; } location @proxy_to_ws { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; … -
How to get html from page in Django
I was trying to implement some testing in Django, and I needed to check the data on the web page with a string, but I couldn't retrieve data from the web page. so, how can I get data(html) from web page? my tests.py from rest_framework.test import APITestCase class TicketTestCase(APITestCase): def test_user_details_on_ticket_id(self): response = self.client.get(f"/api/ticket/1") print(response.content) # this returns empty data in bytes # I want to check this #self.assertEquals(response.data "helloworld")