Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count on big Django Datas
I have a LogTable with about 500k entries per week. models.py class Log(models.Model): timestamp= models.DateTimeField() name = models.CharField(max_length=30) status = models.PositiveIntegerField() objects = LogManager() I want to group the entries by the timestamp and get the counted numbers of each status per timestamp back. Like this: timestamp | automated | offline | user | inactive 29.10.20 17:40 | 5 | 40 | 30 | 15 29.10.20 17:45 | 10 | .... I tried this with a Manager like this: class LogManager(models.Manager): def auto(self, timestamp): return self.filter(datetime__exact=timestamp).filter(status__exact=0).count() def inactive(self, timestamp): return self.filter(datetime__exact=timestamp).filter(status__exact=1).count() def offline(self, timestamp): return self.filter(datetime__exact=timestamp).filter(status__exact=2).count() def user(self, timestamp): return self.filter(datetime__exact=timestamp).filter(status__exact=3).count() def activity(self, timestamp): data = { 'timestamp': timestamp, 'auto' : self.auto(timestamp), 'inactive' : self.inactive(timestamp), 'offline': self.offline(timestamp), 'user': self.user(timestamp), } return data def activity_sum(self): obj = self.values_list('datetime', flat=True) data = {} for i, time in enumerate(obj): data[i] = self.activity(time) return data But this can't be the way because it lasts about 10 minutes to calculate the results if I call Log.objects.activity_sum(). I feel like there is a simple answer but I just can't find it. Thanks for helping me out. -
django.db.migrations.exceptions.NodeNotFoundError: upon running "python manage.py migrate"
I have just started a new django project, which is my own blog. I ran this command first: django-admin startproject mysite Then: python manage.py migrate But, upon running python manage.py migrate, I am getting this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 86, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0012_user_following dependencies reference nonexistent parent node ('account', '0002_contact') I … -
socket.io-stream in django (channels)
I have a server which is used to download files. The server is written in nodejs and looks like this: const express = require("express"); const http = require("http"); const socketIO = require("socket.io"); const ss = require("socket.io-stream"); const port = 4001; const index = require("./routes/index"); const fs = require("fs"); var cors = require('cors') const app = express(); app.use(cors()); app.use(index); const server = http.createServer(app); const io = socketIO(server); io.on("connection", (socket) => { console.log("New Client Connected"); socket.on("download", (fileName) => { startStream(socket)(fileName); }); socket.on("disconnect", () => { console.log("Client disconnected"); }); }); const startStream = socket => fileName => { const file = `${__dirname}/public/${fileName}`; var stream = ss.createStream({allowHalfOpen: true}); const { size } = fs.statSync(file); ss(socket).emit("filedownload", stream, {size} ); var myFileStream = fs.createReadStream(file); myFileStream.pipe(stream); } server.listen(port, () => console.log(`Listening on port ${port}`)); It works great, but the problem is that it needs to be rewritten to Django - which is why i was looking at django channels. ' However I am not sure if Django channels can actually do something like this? The essential part here is socket.io-stream. How would I go about implementing this in Django Channels? -
How to decode django encoded password string in flutter?
i am making application, which has profile screen and in which i am showing password but the password i am getting from a django api is encoded by default now how can i decode my password in flutter application to show the actual password of that user not encoded string. Can anyone help me in this. Note: Django uses the PBKDF2 algorithm with a SHA256 hash to encode passwords -
Will my mail passowrd be visible in console if i use django mail service
I am using Djanog's mail service to send responce mails but i am worried that as i have written my password in my settings.py file so will it be visible to others once i deploy the site as people can see code in console by clicking inspect on websites , Please tell -
How to build a blog recommendation system in python for django?
class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') avatar = models.FileField(upload_to='media/%Y%m%d/', blank=True) body = RichTextField(blank=True ,null=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') likes = models.PositiveIntegerField(default=0) like = models.ManyToManyField(User,related_name='blog_post') dislike = models.ManyToManyField(User,related_name='blog_post_dislike') total_views =models.PositiveIntegerField(default=0) And for user model I used default Django model I want to build a blog recommendation system based on the user profiles and user like dislike and views. -
I am making web based blood donation project in python django .when i run i am dont get option of different blood group. How to resolve this
[Its shows my model.py code and homepage code] Please tell me if there is any module to install so that I get blood group in my project. or any code to resolve this issue -
python manage.py makemigrations Error and django.db.utils.OperationalError Could not connect to server
I am not sure how to fix this issue I have no idea why I am getting this error when I try to python manage.py makemigrations Error: (myproject) D:\E\Project\Trials\Book inventory Assignment>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\core\management\base.py", line 323, in run_from_argvThe above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File … -
The below code is not able to save the entered data in database in django
views.py def contact_us(request): if request.method == 'POST': formq = forms.querys(request.POST) if formq.is_valid(): obj = query() obj.name = formq.cleaned_data['your_name'] obj.email = formq.cleaned_data['your_email'] obj.message = formq.cleaned_data['your_message'] obj.save() return redirect(index) else : formq = forms.querys() return render(request, 'home/contact_us.html', {'formq': formq}) models.py class query(models.Model): Name = models.CharField(max_length=200) Email = models.CharField(max_length = 200) Message = models.CharField(max_length=1500) def __str__(self): return self.Name forms.py class querys(forms.ModelForm): class Meta: model=models.query fields = ['Name', 'Email','Message'] Please Help with how can I add the query in the database and view it on the admin page. -
How to get file location path in python, django?
file = request.FILES['file] Here I want to get the path of the selected file. Anyone tell me how to get? Thanks in advance. -
How to download a file using default_storage class in django
I am using django default storage api to save my media files. I am able to save the file open the file for writing. But not able to download the file Used below code to save the file ''' default_storage.save(filename, ContentFile(str(a).encode())) ''' is there any way to download the file in the same way -
Stuck in using intro.js with Sticky CSS style
I use intro.js to help user know how to use the Django website. The intro.js is used on the header bar which help describes the meaning of options. The header bar use the sticky CSS style. The code is as follows: <script> $("#help").click(function (e) { e.preventDefault(); introJs().start(); }); </script> <style> div.sticky { position: sticky ; /* position: -webkit-sticky; */ width: 100%; top: 0px; background-color: #96C9DB; margin-bottom: 30px; padding-bottom: 40px; z-index: 9999; } </style> <div class="sticky"> <div class="dropdown" style="float: right; margin: 0px 10px;"> {% if request.user.is_authenticated %} <a href="{% url documention' %}">Documention</a> <a href="{% url 'reset_pw' %}">Reset Password</a> <a href="" id="help">Help</a> <a href="{% url 'logout' %}">Logout</a> {% endif %} </div> <div class="header-bar"> <a href="{% url 'aaa_home' %}" data-intro="this is AAA" data-step="1">AAA</a> <a href="{% url 'bbb_home' %}" data-intro="this is BBB" data-step="2">BBB</a> <a href="{% url 'ccc_home' %}" data-intro="this is CCC" data-step="3">CCC</a> </div> </div> {% block content %}{% endblock %} If the attribute for the position is "sticky", then text will be covered as follows: Picture 2: https://ppt.cc/fw21ax If the attribute for the position is "-webkit-sticky", then words will can be displayed, but the header bar will not fix at the top: My goal is to fix the header bar at the top and … -
How to redirect to other url after downloading a file attachment in django
The file which I have generated in django view, after downloading this attachment I need to redirect to other url. Please someone suggest me how to achieve this or any other method to download file attachment without return response in django view def some view(request): with fs.open("filename.pdf") as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=filename.pdf" return response # Here I need to redirect to other page -
Wagtail and Django-fobi: TemplateDoesNotExist at /test-form/ page/base.html
django/wagtail noob here, i go ok writing basic stuff from scratch, but sometimes stumble when trying to integrate or modify other packages. using wagtail==2.10.2 and django-fobi==0.16.4, ive installed fobi as per instructions, and created a fobi form and added it to a wagtail page. When i go to view the page, i get "TemplateDoesNotExist at /test-form/" "page/base.html" so it's looking for base.html in 'page', but there is no folder/app named page?? is page part of wagtail core? do i have to extend class FobiFormPage(AbstractFobiFormPage), or should it just work out of the box? -
How can i fix migration problem in my Django project?
I have a migration problem: This is forms.py file enter image description here this is models.py enter image description here this is admin.py enter image description here -
Django template, how can i use if condition with using {% now 'F jS Y' %}
this is my template, how can i compare the date now with my myaccount.modifyDate ? <input name="temperature" value="{% if {% now 'F jS Y' %} >= myaccount.modifyDate %} 0.0 {% else %} {{myaccount.bodyTemperature}} {% endif %}" readonly></td> -
Better way of linking multiple models in Django [database]
I want to link the Subject model with Class in such a way that every student belonging of Class model will have same subjects included by user in Class. Inside models.py of school app. from django.db import models from accounts.models import School class Class(models.Model): connect_school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) class_list = models.CharField(max_length=95) def __str__(self): return self.class_list class Subject(models.Model): connect_class = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True) subjects = models.CharField(max_length=95, null=True) def __str__(self): return self.subjects Inside models.py of student app: from django.db import models from django.utils import timezone import nepali_datetime from school.models import Class, Subject from accounts.models import School connect_school = models.ForeignKey(School, on_delete=models.CASCADE, null=True) ...name,gender, etc. ... Class = models.ForeignKey(Class, on_delete=models.CASCADE, null=True) subject = models.ManyToManyField(Subject) Inside models.py of accounts. from django.db import models from django.utils import timezone import nepali_datetime # from django.contrib.auth.models import User # Create your models here. class School(models.Model): school_name = models.CharField(max_length=50) ... username = models.CharField(max_length=100) password = models.CharField(max_length=95) ... principal = models.CharField(max_length=150, default='') .... -
AttributeError at /api/logout 'AnonymousUser' object has no attribute 'auth_token'
I have successfully deployed the login view and it returns the token, but when i try to logout it returns the following error. I am new to this so cant figure out the reason. These are my login and logout views. class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) serializer.is_valid(raise_exception=True) new_data = serializer.data user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return response.Response(new_data, status=status.HTTP_200_OK) return response.Response({"token": token.key}, status=status.HTTP_200_OK) # return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Logout(GenericAPIView): def get(self, request, format=None): # simply delete the token to force a login request.user.auth_token.delete() return Response(status=status.HTTP_200_OK) -
DRF custom authentication class capture GET request parameters
I have a custom DRF authentication class like so: from rest_framework import authentication, exceptions class MyCustomAuthenticationClass(authentication.BaseAuthentication): def authenticate(self, request): try: # some codes print(request.GET.get('user_id', 'no user_id')) return (UserObject, None) except Exception as e: print(e) raise exceptions.APIException("Server error") I would like to capture parameter from my url path(/edit/<int:user_id>) in my custom authentication class for validation. So i tried to print it out to see if i can capture the parameter when calling a url But the console doesn't print out anything I can capture parameters like so in the normal APIView of DRF but not in custom authentication class Is my method of getting request parameters not correct? hope someone can tell me -
TypeError: Cannot create a consistent method resolution in django
I am learning django through the 'Django 3 by example' book, and right now i am trying to build an e - learning platform. But, I am getting a weird error in my views.py file. Here is my views file: from django.views.generic.list import ListView from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from .models import Course class ManageCourseListView(ListView): model = Course template_name = 'educa/manage/educa/list.html' permission_required = 'educa.view_course' def get_queryset(self): qs = super().get_queryset() return qs.filter(owner=self.request.user) class OwnerMixin(object): def get_queryset(self): qs = super().get_queryset() return qs.filter(owner=self.request.owner) class OwnerEditMixin(object): def form_valid(self, form): form.instance.onwer = self.request.user return super().form_valid(form) class OwnerCourseMixin(object, LoginRequiredMixin, PermissionRequiredMixin): model = Course fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin): template_name = 'educa/manage/course/list.html' class CourseCreateView(OwnerEditMixin, CreateView): permission_required = 'educa.add_course' class CourseUpdateView(OwnerCourseEditMixin, UpdateView): permission_required = 'educa.change_course' class CourseDeleteView(OwnerCourseMixin, DeleteView): template_name = 'educa/manage/course/delete.html' permission_required = 'educa.delete_course' The error is on line 30. Here is the full error message: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Padma … -
Weighted average for specific student, from specific subject
I've been learning Python for few days already and I've tried to accomplish a small Django model of school. My goal for now is to be able to assign a weighted score to a student for a specific subject (for example physics) and then sum these weighted scores and return a weighted average for a student for his subject. For example, Student A has scores 3 (score) * 2 (weight), 3 * 3 in Physics and 2 * 4, 3 * 1 in Math. My goal is to return: Student A Physics average: 2.5 Student A Math average: 2.2 for now I've been trying to achieve it this way, but it doesn't work. class Score(models.Model): scale = models.PositiveIntegerField(choices=scales_list) student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) task = models.ForeignKey(Task, on_delete=models.CASCADE) weight = models.PositiveIntegerField(default=1) def _weighted_score(self): return self.scale * self.weight weighted_score = property(_weighted_score) def _weighted_average(self): qs = self.objects.all().annotate( score_sum = sum('scale'), weighted_sum = sum('weight'), weighted_avg = Sum((F('scale') * F('weight')), output_field=FloatField() ) / Sum('weighted_sum'), output_field=FloatField() ) return weighted_avg weighted_average = property(_weighted_average) Thanks -
Django - display items from a collection inside a template
I am building an e-commerce store with Django, and I have added some products to a collection. I want to be able to display each collection separately with the products that have been added to it. Here is my models.py code #Products model Fields class Product(models.Model): title = models.CharField(max_length = 100) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2,) image = models.ImageField(upload_to = "pictures") def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug, 'my_id': self.id}) #Collections model Fields class Collections(models.Model): title = models.CharField(max_length=100) products = models.ManyToManyField(Product) def __str__(self): return self.title def get_absolute_url(self): return reverse('collections', kwargs={'slug': self.slug, 'my_id': self.id}) Here is my Views.py: def get_redirected(queryset_or_class, lookups, validators): ... def collectionsPage(request, my_id, slug): article, article_url = get_redirected(Collections, {'pk': my_id}, {'slug': slug}) if article_url: return redirect(article_url) collections = Collections.objects.get(id=my_id) products = Product.objects.all() context = {"products": products, "Collections":collections,} return render(request, "collections.html", context) Here is my urls.py: urlpatterns = [ path('collections/<slug:slug>,<int:my_id>', views.collectionsPage, name="collections"), ] Here is my HTML Code: {% for collection in collections %} <form action="{{collection.products.get_absolute_url}}" method="post"> {% csrf_token %} <button class="polaroid" style="background-color:white; border:none"> <div> <img src="{{collection.products.imageURL}}" alt="iPhone image"> <h3 class="container">{{collection.products.title}}</h3> <h4 class="container">{{collection.products.price}}</h4> </div> </button> </form> {% endfor %} -
Keycloak introspect token - 500 Failed to establish a new connection
I am connecting a Django backend to Keycloak and am getting a 500 - Failed to establish a new connection error when I call the token introspection endpoint. I believe I have a localhost vs. Docker sort of config issue that is not allowing the endpoint to return. How should these be set up so this will work or how can I further debug? I have the following set up: Front end on localhost:3000 with a Keycloak client that is public (this redirects to the Keycloak and then returns a valid token) Backend in Django on localhost8000 with a confidential KeyCloak client, libray = 'django-keycloak-auth' Keycloak on Docker pointing to localhost8080 When I do an API call from the front end with a valid token, the backend uses the `django-keycloak-auth' library to call the introspection endpoint: http://localhost:8080/auth/realms/myproject/protocol/openid-connect/token/introspect with my client id and my client name but this fails with the below error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /auth/realms/myproject/protocol/openid-connect/token/introspect (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fea20c3d370>: Failed to establish a new connection: [Errno 111] Connection refused')) When I test the token at this endpoint: http://localhost:8080/auth/realms/mobius-dev/protocol/openid-connect/userinfo I get a valid response. Items in the api call: body 'token=MY_TOKENA&client_id=backend&client_secret=MY_SECRET' encode_chunked False … -
Hot reloading properties in a Python Flask/Django app
Gurus, Wizards, Geeks I am tasked with providing Python Flask apps (more generally, webapps written in python) a way to reload properties on the fly. Specifically, my team and I currently deploy python apps with a {env}.properties file that contains various environment specific configurations in a key value format (yaml for instance). Ideally, these properties are reloaded by the app when changed. Suppose a secondary application existed that updates the previously mentioned {env}.properties file, the application should ALSO be able to read and use new values. Currently, we read the {env}.properties at startup and the values are accessed via functions stored in a context.py. I could write a function that could periodically update the variables. Before starting an endeavor like this, I thought I would consult the collective to see if someone else has solved this for Django or Flask projects (as it seems like a reasonable request for feature flags, etc). -
Unable to make any changes to view.py file
I'm hosting a web server with Django framework . Then , I'm using Notepad++ NppFTP to modify and upload those files . I can modify the html files and upload to ftp server instantly with Notepad++ NppFTP .But for updating view.py , I found that even though it says view.py 100% upload success , the web seems to be unchanged regarding to the new view.py file . Is that the way to modify the view.py file different to modifying HTML files ?