Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to group items by month and year using itertools.groupby()
Problem: I am trying to take a sorted list and group it based on the month and year but having trouble returning the grouped value correctly... Assuming this data, we have a title and date/time list that has been ordered by datetime lst = [ {'title': 'in the past','date_time': datetime.datetime(2020, 3, 18, 0, 0)}, {'title': 'Just another event','date_time': datetime.datetime(2020, 10, 1, 19, 7)}, {'title': 'earlier today 9am','date_time': datetime.datetime(2020, 10, 21, 9, 0)}, {'title': 'greater than .now()','date_time': datetime.datetime(2020, 10, 21, 23, 0)}, {'title': 'another one','date_time': datetime.datetime(2020, 10, 30, 10, 0)}, {'title': 'Me testing the latest event','date_time': datetime.datetime(2020, 10, 30, 12, 0)}, {'title': '18 Nov 20','date_time': datetime.datetime(2020, 11, 18, 20, 27)}, {'title': '18 January 2021','date_time': datetime.datetime(2021, 1, 18, 20, 0)}, {'title': '18 March 21','date_time': datetime.datetime(2021, 3, 18, 20, 0)} ] Then to group it, run it through itertools.groupby() from itertools import groupby def loop_tupe(): diction = {} for key,group in groupby(lst, key=lambda x: (x['date_time'].month, x['date_time'].year)): for element in group: append_value(diction, key, element) return diction After grouping it by the month and year the returned result looks like { (3, 2020): {'title': 'in the past', 'date_time': datetime.datetime(2020, 3, 18, 0, 0)}, (10, 2020): [ {'title': 'Just another event', 'date_time': datetime.datetime(2020, 10, 1, 19, … -
Why is Django trying to open a URL that I don't tell it to?
Hello Community! I am creating a small blog with Django, in which I have a single application. It happens that I have already defined a large part of the blog, this is: The Home view. Views for the categories of each publication. View for each of the posts Among other Now that I have wanted to add the "About Author" view, when it should redirect to its respective HTML template, Django ends up redirecting itself to another template, which generates a NoReverseMatch error. Simplifying the code, this is: views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post, Author, Category class Home(ListView): def get(self, request, *args, **kwargs): context = { 'post': Post.objects.get(title='NamePost') } return render(request, 'PageWebApp/home.html', context) class PostSimple(DetailView): def get(self, request, slug_post, *args, **kwargs) context = { 'post': Post.objects.filter(slug_post=slug_post) } return render(request, 'PageWebApp/page-simple.html', context) class PostsCategory(DetailView): def get(self, request, category, *args, **kwargs): # View that shows each of the categories within the blog context = { 'categories': Category.objects.get(category=category) } return render(request, 'PageWebApp/posts-category.html', context) class AboutAuthor(DetailView): def get(self, request, slug_autor, *args, **kwargs): context = { 'author': Author.objects.get(slug_author=slug_author) } return render(request, 'PageWebApp/page-author.html', context) urls.py from django.contrib import admin from django.urls import path from PageWebApp import views urlpatterns … -
Is the combo of JavaScript on front end and Django + python on back end is good or not?
Actually i have a web app development project to do and i want to work through Django and python i am yet to decide the topic. I first want to decide front and back end development frameworks and languages. Let's suppose i want to build restaurant management system, should i use this combo or not in restaurant management system or python and Django are good as full stack only project will also need some little data mining work too (like predicting food orders etc.) continuing 3 where will that data mining lie (at back end) -
Why is my Django form for user sign up not “valid”? ValidationError 'This field is required.'
I am trying to write a signup form in Django, but I keep getting a Validation error when I post 'date_joined': [ValidationError(['This field is required.']) The form is based on the django user model. I have not got this field on the form because it's value can be set in code html <form method="post" action="{% url 'sign-up' %}"> {% csrf_token %} <h1>Bid for Game - Sign Up</h1> Your first and last names will be used to help your friends identify you on the site. <table> <tr> <td>{{ signup_form.first_name.label_tag }}</td> <td>{{ signup_form.first_name }}</td> </tr> <tr> <td>{{ signup_form.last_name.label_tag }}</td> <td>{{ signup_form.last_name }}</td> </tr> <tr> <td>{{ signup_form.username.label_tag }}</td> <td>{{ signup_form.username }}</td> </tr> <tr> <td>{{ signup_form.email.label_tag }}</td> <td class='email'>{{ signup_form.email }}</td> </tr> <tr> <td>{{ signup_form.password.label_tag }}</td> <td><class='password'>{{ signup_form.password }}</class></td> </tr> <tr> <td>Confirm password: </td> <td class='password'>{{ signup_form.confirm_password }}</class</td> </tr> </table> <button type="submit" class="btn btn-success">Submit</button> </form> forms.py class SignupForm(forms.ModelForm): first_name = forms.CharField(label='First name', max_length=30) last_name = forms.CharField(label='Last name', max_length=30) username = forms.CharField(label='User name', max_length=30) email = forms.EmailField(label='Email address', widget=forms.EmailInput(attrs={'class': 'email'})) password = forms.PasswordInput() confirm_password=forms.CharField(widget=forms.PasswordInput()) date_joined = forms.DateField() class Meta: model = User fields = '__all__' widgets = { 'password': forms.PasswordInput(), 'password_repeat': forms.PasswordInput(), } @staticmethod def initialise(request): """Return a dict of initial values.""" initial = { … -
Django - Error while trying to iterate a model class (db table) in views.py (need to compare dates)?
The idea is to compare a checking date & a checkout date stored , with checking & checkout dates obtained from a html file (hotel booking, with this I'm trying to see if there are habitaciones [rooms] available) this is what I did in views.py This is the models.py file This is the error that I get thanks in advance!!! -
redirect to a Django url in another app using JavaScript
Right now I have two apps in the project, here is the project structure: The current function being called is in chess1 and I want to redirect to a url in Chess_Django. My url in Chess_Django/urls.py is path('start/', views.start_game, name='start'). I tried to use window.location.href = "{% url 'Chess_Django:start/' %}". But I got this error: Right now I am able to access it using the absolute path. But I am just curious how to achieve it using Django template language. Thanks! -
removing the string character in integer value : Python
i want to remove the string character from int value in a list. when i remove str character from below statement then it's throw me TypeError: 'int' object is not iterable. how can i achieve that? for record in serializer.data: if record: less_eight = [x for x in str(record['car_cc'])] print(less_eight) else: #some logic output: ['8', '0', '0'] ['5', '0', '0'] what i want is: [8, 0, 0] [5, 0, 0] -
My function is creating and deleting objects incorrectly (django)
I'm trying to create or delete an object based on certain conditions. I am looping through rows on a csv as below. My problem is I am restricted as my variables are defined from within the csv loop, so when I delete - instead of deleting all, it deletes the object, then continues through the code and creates the next corresponding one on the csv, and then deletes the next one down etc for each row. My intention is to delete all the objects first, regardless of what is on the csv. And then create according to the csv - but I can't figure out how to do this as the variables are all contained within the loop. I hope that makes sense!! Please help list_of_people = [1,2,3,4] for row in csv: id = row["id"] person = Object1.objects.filter(id=id).first() if person=4203: Object1.objects.filter(id=id).exclude(otherfield__isnull=True).delete() if person not in list_of_people: Object1.objects.create(person=person) -
Endless Django websocket
There is a page that has a button that I can click and initiate the process on the server via Websocket. I get information about process via Websocket. How can I close and reopen the page to see the current status of the process, not at first, without a disconnect? -
how to create an api for nested comments in django rest framework?
I want to have a nested comment system for my project. I have product model so I want to clients can comment on my products. I have my product and comment models and serializers and I related comments to products in product serializer so I can show product comments. what should i do to clients can write their comment for products??? the comments must be nested. this is my code: #models class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True,blank=True, related_name='replys') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' class Meta: ordering = ('-created',) serializers: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created'] class ProductSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True, read_only=True) class Meta: model = Product fields = ['id', 'category', 'name', 'slug', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'description', 'price', 'available', 'created', 'updated', 'comments'] lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } views: class Home(generics.ListAPIView): queryset = Product.objects.filter(available=True) serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) filter_backends = [filters.SearchFilter] search_fields = ['name', 'category__name', 'description'] class RetrieveProductView(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) lookup_field = 'slug' -
the JSON object must be str, bytes or bytearray, not ListSerializer
I have a queryset which is: queryset = Business.objects.raw(query) I am trying to serialize the query using the Business serializer: serialized_data = BusinessSerializer(queryset, many=True) However, for some reason I get the error: the JSON object must be str, bytes or bytearray, not ListSerializer. The serialization works if I use the following: serialized_data = serializers.serialize('json', queryset) Could someone please tell me why I am unable to use the business serializer? Is it something to do with the raw query? Thanks in advance. -
In django using elastic search client how to insert data in elasticsearch document?
Basicall i am using django-elastic-search dsl...i am dealing with this model--> Class Post: .. title = models.Charfield() ...body = models.Charfield() I want to index it in my locally running index at localhost:9200 directly without writing any document.beacause i have al ready created the index in localhost:9200, I just want to push it through with a es client? -
How to save extra data sent using django signals in a model related to User model via OneToOne relationship?
I am trying to create a signup functionality for the Teacher model. The Teacher model is related to Django's User model via an OneToOne relationship. When I am trying to save the serializer I am getting this error- IntegrityError at /teacher/create-teacher NOT NULL constraint failed: teacher_teacher.school_id_id My Teacher model: from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from school.models import School class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contact = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{10}$')]) school_id = models.ForeignKey(School, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_user_teacher(sender, instance, created, **kwargs): if created: Teacher.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_teacher(sender, instance, **kwargs): instance.teacher.save() TeacherCreateView: class TeacherCreateView(APIView): def post(self, request): serializer = TeacherSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) TeacherSerializer: from django.contrib.auth.models import User from rest_framework.serializers import ModelSerializer, EmailField, CharField from rest_framework.validators import UniqueValidator class TeacherSerializer(ModelSerializer): email = EmailField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) password = CharField(min_length=8, write_only=True) def create(self, validated_data): user = User.objects.create( email=validated_data['email'], username=validated_data['username'], first_name=validated_data['first_name'] ) user.set_password(validated_data['password']) user.teacher.contact = validated_data['contact'] user.teacher.school_id = validated_data['school_id'] user.save() return user class Meta: model = User fields = ['email', 'username', 'password', 'first_name'] JSON data for creating the teacher: { "email":"teacher@gmail.com", "username":"teacher", "password":"somepassword", "first_name": "Teacher", "contact":"1234567890", "school_id":"school" } The twist is that the email, first_name, … -
Is it okay to listen same queue in multiple celery pods using redis as a brocker?
I am trying to scale my Django application that uses Celery for background tasks. Assume that I have one main queue and one celery instance listening to it. What could actually happen if I add another celery instance that listens to the same queue? Is there a way two workers will execute same task twice? Note: Using different queues for each celery instance is not an option for me. Thanks in advance! -
How to align bokeh rectangles?
In django I'm drawing a boxplot using bokeh and the image has a left an right margin which I cannot remove as shown in the picture. The green rectangle should be left aligned without having the white space. Here my code: def get_boxplot_chart_pdf(data, student_score): if len(data) == 0: return None df = pd.DataFrame({'scores': data}) cats = ['scores'] mean = df.quantile(0.5) q1 = df.quantile(0.25) q3 = df.quantile(0.75) upper = [max(data)] lower = [min(data)] # create figure and set all borders to 0px p = figure(y_range=cats, toolbar_location=None, plot_width=285, plot_height=27) p.min_border = 0 p.margin = (0, 0, 0, 0) # Stems p.segment(upper, cats, q3, cats, color="black") p.segment(lower, cats, q1, cats, color="black") # Boxes p.hbar(y=0.5, right=q1, left=mean, height=0.5, fill_color=None, line_color="black") p.hbar(y=0.5, right=mean, left=q3, height=0.5, fill_color=None, line_color="black") # whiskers (almost-0 height rects simpler than segments) p.rect(lower, cats, 0.01, 0.2, color="black") p.rect(upper, cats, 0.01, 0.2, color="black") # student score fill_color = "Green" if student_score >= 30 else "Red" p.rect(x=student_score / 2, y=0.5, height=1, width=student_score, fill_color=fill_color, line_color=None, fill_alpha=0.3) p.xgrid.grid_line_color = None return remove_chart_chrome(p) def remove_chart_chrome(chart): chart.axis.visible = False chart.grid.visible = False chart.outline_line_color = None chart.min_border = 0 return chart Thank you for any help ;) -
Android Studio: Create Login Screen in Existing Android Studio Project as First Screen
I purchased a source code from codecanyon and now i want to add login screen at the first page of the app so that when someone opens app for first time they have to login through user id and password given by us. I'm new in android studio and have only basic knowledge. So, please help me. -
Python pytesseract incorrect data extraction from image
I used the below code in Python to extract text from image, def read_image_data(request): import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = "C:/Program Files/Tesseract-OCR/tesseract.exe" img = cv2.imread("image_path") height, width = img.shape[0:2] startCol = 345 # x1 Left startRow = 107 # y1 Top endCol = 389 # x2 Right endRow = 135 # y2 Bottom croppedImage = img[startRow:endRow, startCol:endCol] text = pytesseract.image_to_string(croppedImage) gray = cv2.cvtColor(croppedImage, cv2.COLOR_BGR2GRAY) ret, threshold = cv2.threshold(gray, 55, 255, cv2.THRESH_BINARY) print(pytesseract.image_to_string(threshold)) print(text) But the output is incorrect. The input file is ± 0.1 % and the output received is 201% instead of ± 0.1 %. The input file is ± 50 ppm/K and the output received is +50 ppmik instead of ± 50 ppm/K The input file is 10 to 100 k and the output received is 1010332ka. instead of 10 to 100 k What are the required code changes to retrieve the right Characters from the image? -
How to insert JavaScript variable into template tag variable in Django?
I have the following code in my templatetag: def getbyid_property(pk): property_detail=Properties.objects.get(id=pk) html_data='<div class="property_item heading_space"><div class="image">......</div></div>' return html_data and in my template, I have the following code: var getPointData = function (index) { var property_id='{{ 'index'|getbyidproperty|safe }}'; ....} Here, index is JavaScript variable and {{ 'index'|getbyidproperty|safe }} is python(django) variable. When I run this code, it is rising the following error message Field 'id' expected a number but got 'index'. index JavaScript variable returns integer value. And it is not inserting this integer value instead it is inserting index word. if I place some integer value instead of index for example 28 {{ 28|getbyidproperty|safe }}, this code works without any issue. My question is how can I insert JavaScript variable into python variable? Is it possible to it in a way that I did above? If no, how can I do it? -
ruby devise encrypted password decrypt in django
First my database was connected to ruby.Ruby devise uses Bcrypt password by default to hash passwords. I am building same app in django but also want that old users can login using django app that is only possible if django can decrypt ruby hashed password stored in mysql database. By default django password hashing looks something like this: pbkdf2_sha256$180000$cZxgIsN0sthv$XnAOHJiWIX1E1/p4livZCcmf6DmmKi2FZPrKbDZIpfM= When i changed default password haser in django to Bycrypt algorithm passwords are stored something like this: bcrypt_sha256$$2b$12$MUA0prRIYOnu63HAFP9tP.RsNVyO.ApAv.zTJX5GOBb2eBQ.8hz.W IN database ruby passwords are stored something like this: $2a$12$tBfIVsgQvDSM8WOu9SDpGupSaFbHXJbAT8lOtkvYCMO5NrOVjy9Y2 Inorder to decrypt ruby written passwords i tried adding "bcrypt_sha256$" and "bcrypt$" before ruby passwords to make it django bcrypt format but it does not work. -
bootstrap card in a for loop - tabs only work on the first card - django
I am trying to get repeating cards with tabs within my for loop but the tabs only seem to work on the first card and none of the below e.g I have two tabs - on card 1: tab 1 opens tab 1 and tab 2 opens tab2 but on card 2 tab 2 opens tab 2 on card 1: Cards example Is there a way to make the second tab repeat down the for loop? HTML: {% for project in projects %} <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="nav-link active" href="#details" role="tab" data-toggle="tab">Details</a> </li> <li class="nav-item"> <a class="nav-link" href="#stats" role="tab" data-toggle="tab">Stats</a> </li> </ul> </div> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="details"> <div class="card-header"> <div class="row"> <div class="col-md-2"><strong>Project</strong></div> <div class="col-md-2"><strong>Distributor</strong></div> <div class="col-md-2"><strong>Licensee</strong></div> <div class="col-md-2"><strong>Budget</strong></div> <div class="col-md-2"><strong>Release Date</strong></div> <div class="justify-content-center col-md-1"><strong>View</strong></div> <div class="justify-content-center col-md-1"><strong>Edit</strong></div> </div> </div> <div class="card-body"> <div class="row"> <div class="col-md-2">{{project.production_title}}</div> <div class="col-md-2">{{project.distributor}}</td></div> <div class="col-md-2">{{project.licencee}}</td></div> <div class="col-md-2">{{project.currency}} {{project.budget}}</td></div> <div class="col-md-2">{{project.release_date}}</td></div> <div class="justify-content-center col-md-1"><a href="{% url 'tracks' project.pk %}" class="btn btn-dark btn-sm" role="button">Tracks</a></div></td> <div class="justify-content-center col-md-1"><a href="{% url 'update_project' project.pk %}" class="btn btn-dark btn-sm" role="button">Edit</a></div></td> </div> </div> </div> <div role="tabpanel" class="tab-pane" id="stats">Test </div> </div> </div> <br> {% endfor %} -
How to create a custom authenticate in Django?
I want to create an aunthentication django views, but I have my own custom User model. I am not using django default user model. So I need my custom authenticate model and import in anywhere I want. -
When i turn off the DEBUG mode in settings.py it returns a bad request(400)
I see this when i turn off Debug mode DEBUG = False ALLOWED_HOSTS = [ 'localhost:8000', ] How am i going to fix this? -
Sentry mark some exceptions as warnings
I have a lot of errors when user tries to access some resource and get 403 exception because of forbidden IP. Is it possible to find them by regular expression by their message and send them to sentry as warnings? -
Transformer model deployment
I am trying to deploy a transformer model for question answering within a website using django framework. As I test it locally the model responds quickly giving back the answers. Currently, I have deployed it in digital ocean server and tested the website across three different users. The model only runs for few instances and then stops giving back answers. I receive a websocket disconnect error. The server droplet has 8gb of ram, 8vCPUs and 32gb of disk. What might be the problem? I am kindly asking for your help -
Is the a way to make ALLOWED_HOSTS accept new domains dinamically in Django?
I wan't to let users to connect their domains to my site. For example, a user has bought example.com (the domain) and wants that when someone types example.com in the browser, what the browser shows is my app. I have everything configured and working except for the ALLOWED_HOSTS setting. If I add manually the domain to my ALLOWED_HOSTS it works. But, in production server, users will be creating this connections at anytime, I can't be adding this lines manually and restarting the server. Is there a different way of achievings this without making ALLOWED_HOSTS = ['*',] If there is no other way, I'm not sure wich is the safest way to check request.get_host() in a middleware. If someone could guide me, I'd be eternally thankfull. I hope I explained myself good enough.