Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Returning httpresponse with queryset for ListView after post in Django
I have a listview with formmixin after submitting the form I was trying to return the exact same view with some extra messages, but I havent been able to return the query set, hence the list is not appearing, Can anyone pls help me. Views.py class NewsletterList(FormMixin, generic.ListView): queryset = newsletter.objects.filter(status=1).order_by('-created_on') template_name = 'newsletterlist.html' form_class = SubscriberForm def post(self, request, *args, **kwargs): form = SubscriberForm(request.POST) if form.is_valid(): sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() return NewsletterList.as_view()(request, queryset=newsletter.objects.filter(status=1).order_by('-created_on'),template_name='newsletterlist.html', form_class = SubscriberForm) Thanks in advance -
Display multiple list in django template
I have 10 lists of same lenght (20) with chained data meaning that A[0] is image for B[0] and C[0] but for the sake of smallest reproducible example i have 3 A=[image1, image2, image3, image4, image5, image6] B=[title1, title2, title3, title4, title5, title6] C=[name1, name2, name3, name4, name5 ,name6] I need to dispaly them in Django Templates like this: <div class="row"> <div class="col-4"> <div class="image"> image1 </div> <div class="title"> title1 </div> <div class="name"> name1 </div> </div> <div class="col-4"> <div class="image"> image2 </div> <div class="title"> title2 </div> <div class="name"> name2 </div> </div> <div class="col-4"> <div class="image"> image3 </div> <div class="title"> title3 </div> <div class="name"> name3 </div> </div> </div> and after this row is next one will be generated with the rest of the values How can i do this -
How to get data in the last 48 hours in Django?
I want to return the list of last points per vehicle that have sent navigation data in the last 48 hours. Since there may be a lot of data, I am looking for the most efficient and fast way to list. I wrote a function but encountered an error. AttributeError at / Manager isn't accessible via NavigationRecord instances How can I fix this error? Is there a more afformative and efficient way for me to do this listing? models.py class Vehicle(models.Model): id = models.IntegerField(primary_key=True) plate = models.CharField(max_length=30) class NavigationRecord(models.Model): id = models.IntegerField(primary_key=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) datetime = models.DateField() latitude = models.FloatField() longitude = models.FloatField() views.py def get_48_hours(request, id): time_48 = datetime.now() - timedelta(hours=48) navs = get_object_or_404(NavigationRecord, id=id) results = navs.objects.filter(date_created__gte=time_48) context = { 'navs': navs, 'results': results } return render(request, 'navigation.html', results) traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.13 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'navigation'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\edeni\senior\myenv\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\edeni\senior\evreka\navigation\views.py" in get_48_hours 10. results = … -
How to fix the problem of not showing the sitemap in django?
I created a sitemap as follows, but nothing is displayed inside the sitemap URL. How can I fix the problem? Thank you setting.py INSTALLED_APPS = [ 'django.contrib.sitemaps', ] sitemaps.py from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from riposts.models import Posts class RiSitemap(Sitemap): priority = 0.5 changefreq = 'daily' def get_queryset(self): posts = self.kwargs.get('posts') return Posts.objects.filter(status="p") def lastmod(self, obj): return obj.updated def location(self, item): return reverse(item) urls.py from django.contrib.sitemaps.views import sitemap from .views import home_page from riposts.sitemaps import RiSitemap sitemaps = { 'posts':RiSitemap, } urlpatterns = [ path('', home_page, name="home"), path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"), ] sitemap image -
Pagination for only one specific method of ModelViewSet Django Rest Framework
I have a class class Home(viewsets.ModelViewSet): serializer_class = HomeSerializer queryset = Home.objects.all() @action(detail=False, methods=['get']) def blog_data(self, request): queryset = Blogs.objects.filter(identifier='blog') serializer = BlogDataSerializer(data=queryset, many=True) #other serializer specific to this method serializer.is_valid() return Response(serializer.data) # need pagination here for this method only def list(self, request): .... return Response(serializer.data) i have overwritten list method and i only want pagination in blog_data method to have pagination with page_size and page_number(page) to be given as query params. example: http://localhost:8000/home?page=1&page_size=5 how would i acheive it, i have read about pagination_class = HomePagination but i dont want it to impact list method or any other method in this class, i only want pagination in my blog_data method pagination.py is class HomePagination(PageNumberPagination): page_size_query_param = 'page_size' def get_paginated_response(self, data): response = { 'no_of_records': self.page.paginator.count, 'no_of_pages': self.page.paginator.num_pages, 'page_size': int(self.request.GET.get('page_size')), 'page_no': self.page.number, 'results': data } return Response(response, status=status.HTTP_200_OK) -
How to correctly use validation messages in Django Models
In my Django app I am using a PositiveSmallIntegerField in one of my models wherein the minimum value for the field has been specified as under: trc_frequency = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1)], ...) Now what is happening is, when a value less than 1 (zero or a negative value) is being input in the form, the error message put forth by the system is to the effect: Ensure this value is greater than or equal to 0. Whereas, since the the minimum value defined for the field is "1" (one), I would prefer that the message informs the user that the minimum allowable value for the field is 1 (One), to the effect: Ensure this value is greater than or equal to 1. What I have tried so far: trc_frequency = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1, _('Must ensure this value is greater than or equal to %(limit_value)s.'))],...) But still getting the minimum value specified in the error message as 1 (Zero). Even more surprisingly, the message text also is not getting changed from Ensure this value is ... to Must ensure this value is... Why? Where am I going wrong. -
MySQL (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)"
I can't access to MySQL since yesterday. ❯ mysql -u root -p Enter password: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) I've tried several things to fix, but don't have any clue yet. First Try ❯ find / -name mysql.sock find: /usr/sbin/authserver: Permission denied find: /usr/local/var/mysql: Permission denied …. ❯ mysql -u root -p mysql S/var/local/var/mysql/mysql.sock mysql Ver 8.0.19 for osx10.14 on x86_64 (Homebrew) Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. I could see some messages, but can not access to MySQL. Second try I found mysql.sock file in "/var/mysql/mysql.sock" So I edited my.cnf file, but it didn't work. ❯ vi /usr/local/etc/my.cnf #my.cnt [client] socket = /var/mysql/mysql.sock [mysqld] socket = /var/mysql/mysql.sock ❯ ln -s /tmp/mysql.sock /var/mysql/mysql.sock ln: /var/mysql/mysql.sock: File exists And there are other informations to try to fix. ❯ ls -l /tmp/mysql.sock lrwxr-xr-x 1 seungholee wheel 31 8 30 18:45 /tmp/mysql.sock -> /usr/local/bin/mysql/mysql.sock -
How to do I Architect my Website Builder using Django and React
I am planning to make a website builder of my own using which a user can generate websites based on a category they like . I am using django rest framework to handle the backend part in django and send data in api format to the front end. I am using ReactJS to render the components in Frontend. I am Very much confused regarding the architecture of the Project. Should i be storing the React/ Html components in the database or Should I Declare a Few React Components and pass the parameters which is returned for a particular site -
Cant split template django
I cant split string in my django template: {% with list.list|split:"%%_next_done=TRUE%%" as array %} {% for string in array %} <p>{{ string }}</p><br> {% endfor %} {% endwith %} Error: Invalid filter: 'split' -
on making migrations giving error django.db.utils.IntegreityError: (1364,"Field 'name' doesnt have a default value")
I was actually working on sqlite3 before where my django admin was working properly. but recently i shifted to mysql(cloud cluster). Ran all migrations python manage.py makemigrations python manage.py migrate sessions python manage.py migrate auth python manage.py migrate migrate its giving me error - ProgrammingError at /admin/login/ (1146, "Table 'databasename.auth_user' doesn't exist") when i am putting my previous superuser id and password when i recheck migrations - migrations is giving me error django.db.utils.IntegreityError: (1364,"Field 'name' doesnt have a default value") kindly help me making django admin work properly with my new database -
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.