Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get count of friends of friends
i am building a website like instagram where users can follow friends, i have been able to implement follow friend and also displaying friends of friends (mutual friend). I was not able to get the count of friends of friends; this is what i tried: Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) friends = models.ManyToManyField('Profile', related_name="my_friends",blank=True) view: @login_required def profile_user_view(request, username): #Friend of Friends p = Profile.objects.filter(user__username=username).order_by('-id') all_friends = request.user.profile.friends.values_list('pk', flat=True) friends_of_friend = Profile.objects.filter(pk__in=all_friends) context = { 'profile_img': p, 'friends_of_friend': friends_of_friend, } return render(...) Template: {% for data in profile_img %} {% for friend in friends_of_friend %} {% if friend in data.friends.all %} <li> <a href="{% url 'site:profile-view' friend.user.username %}" class="dark-grey-text"> <b>{{ friend.user.username|lower }}</b> </a> </li> <li> {{ friend.count }} #This is not showing the count of friends of friends, when i use length it displays '0 0' instead of '2' (mutual friends) </li> {% endif %} {% endfor %} {% endfor %} -
i am getting 'django.db.utils.OperationalError: no such column:' error
from django.db import models from datetime import datetime Create your models here. class Appoint(models.Model): doc_choices = (('General Physician','General Physician'), ('Cardiologist','Cardiologist'), ('Dramatologist','Dramatologist'), ('Neurologist','Neurologist'), ('Physciotherpist','Physciotherpist'), ('Dentist','Dentist')) day_choices = (('monday','monday'), ('tuesday','tuesday'), ('wednesday','wednesday'), ('thursday','thursday'), ('friday','friday')) time_choices = (('10am - 12pm','10am - 12pm'), ('12pm - 2pm','12pm - 2pm'), ('3pm - 5pm','3pm - 5pm'), ('5pm - 7pm','5pm - 7pm')) f_name = models.CharField(max_length=12) l_name = models.CharField(max_length=12) phone1 = models.CharField(max_length=12) phone2 = models.CharField(max_length=12) add = models.TextField() city = models.CharField(max_length=20) state = models.CharField(max_length=30) pincode = models.CharField(max_length=10) doc = models.CharField(max_length=30, choices=doc_choices) day = models.CharField(max_length=30, choices=day_choices) timeslot = models.CharField(max_length=30, choices=time_choices) symptom = models.TextField() email = models.CharField(max_length=100) date = models.DateField(auto_now=True) def __str__(self): return self.f_name + self.l_name this is my model.py i made doc, day and timeslot as columns , but it keeps on saying that unable to make column day and i have tried deleting my pycache and dbsqlit3 but it gives the same error when i run python manage.py migrate. -
timezone aware dates issue in django rest framework with postgresql
I am using the Django rest framework with Postgresql. From the Django docs, I understood that Postgres will store the DateTime in UTC only and Django converts it back to the local time while displaying in the templates. However, I am not using templates. I am using DRF to create APIs which are consumed by a Vue app. I have two questions - Why Django Model DateTime fields are converted to "timestamp with time zone" type column if values are always stored in UTC? How to return DateTime values in local time from the Django rest framework. Here is my settings File - TIME_ZONE = 'Asia/Calcutta' USE_TZ = True REST_FRAMEWORK = { 'DATE_INPUT_FORMATS': ["%d-%m-%Y",], 'DATE_FORMAT': "%d-%m-%Y", 'DATETIME_FORMAT': "%d-%m-%Y %H:%M:%S", } Special Note - using django.utils.timezone.localtime(timezone.now()) creates a value in localtime but it is converted back to UTC while storing in DB. Any help will be highly appreciated. Thanks a lot for your time and help. -
Django+React: Documentation review on an ongoing boilerplate project
I wrote a boilerplate project for my own Django + React integration design. I have a draft markdown file briefly documenting the project. If it's not too much to ask, maybe someone can help review it? If the design is ideal for use, I will publish it on Github for free use, otherwise I will revise it based on your comments/suggestions. Thanks! Gist: https://gist.github.com/michaeljarizala/f0719ab7a56c5988a74ceb571805573c -
Page not found don't know how to fix
Starting learning Django and in the very beginning have a problem. Site doesn't see url and then Error 404 urls.py - site from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('webexample/', include ('webexample.urls')), ] urls.py - webexample from django.urls import path from . import views urlpatterns = [ path(r'^$', views.index, name='index'), ] views.py - webexample from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h3>This page isn't set up yet...</h3>") Error photo -
Python, float error: unsupported operand type(s) for +: 'float' and 'list'
I have set the following class: class StatoPatrimoniale(models.Model): reference_date=models.DateField() cassa=models.DecimalField() And I have set the following function: def stato_patrimoniale(request): now=datetime.datetime.now() last_account_year=float(now.year)-1 list_diff=[] list_diff = float(StatoPatrimoniale.objects.filter(reference_date__year=last_account_year).values_list('cassa')[0][0]) But python give me the following error: unsupported operand type(s) for +: 'float' and 'list' list_diff = float(StatoPatrimoniale.objects.filter(reference_date__year=last_account_year).values_list('cassa')[0][0]) Why? Where is the issue? -
Django: How to generate unique order id
This is how my model looks like. When ever user orders. The order id provided by django is simple. Its like 1,2,3 ..... 100. class UserOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='orders', on_delete=models.CASCADE) cart = models.ForeignKey(Cart, related_name="orders", on_delete=models.CASCADE, null=True, blank=True) date = models.DateTimeField(default=datetime.now) total_price = models.IntegerField(null=True, blank=True) note = models.TextField(null=True, blank=True) cancel_reason = models.TextField(null=True, blank=True) cancelled = models.BooleanField(default=False) confirmed = models.BooleanField(default=False) def __str__(self): return self.user.username -
convert html input type with same name into key value jquery
I have this form and on addmorefield button click I'm appending two more fields with same name and <form method="post" id="sampleform" action="#"> <div class="input_fields" style="text-align:center"> <input type="text" name="first_name" id="first_name" placeholder="first name"/> <input type="text" name="last_name" id="last_name" placeholder="Last Name"/> <button class="add_button">Add More Fields</button> <button type="submit">Submit</button> </div> <script> $(document).ready(function() { var max_fields = 10; var wrapper = $(".input_fields"); var add_button = $(".add_button"); var x = 1; $(add_button).click(function(e){ e.preventDefault(); if(x < max_fields){ x++; $(wrapper).append( '<div class="form-group" style="margin-top:5px"><input type="text" name="first_name" placeholder="first name" required/><input type="text" name="last_name" placeholder="last name" required/><a href="#" class="remove_field">Remove</a></div>' ); } }); $(wrapper).on("click",".remove_field", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--; }) }); </script> i'm making post request with DRF api in this format {"first_name":"value","last_name":"value"}. so what i want to achieve here to covert this form input into this format [{"first_name":"value","last_name":" value"},{"first_name":"value","last_name":" value"}] <script> $('#sampleform').submit(function(e){ e.preventDefault(); var form = $(this); $.ajax({ url:"http://localhost:8000/api/", type:"post", data: $('#sampleform').serialize(), //dataType:'json', success: function(data){ console.log(data) }, }); }); </script> -
Column poster_poster.user_id doesn't exist
The error Column poster_poster.user_id doesn't exist LINE 1: SELECT "poster_poster"."id", "poster_poster"."user_id" FROM ... I have app named as poster When I save a model at the django-admin, I get this error ( in the picture ) models.py class Poster(models.Model): id = models.CharField(max_length=50,primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: db_table = 'poster_poster' -
Gmail Two-Step Verification not available in my country, Django password reset
i am trying to implement django password reset, but i need to create app password in gmail which requires two-step verification which is not allowed by google in my country Nigeria settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = "587" EMAIL_USE_TLS = True EMAIL_HOST_USER = "myemail" EMAIL_HOST_PASSWORD = "mypassword" what other option do i have in order to enable password reset with django? -
Django virtual environment wrapper
I just started learning django and kept wondering, do I need to install a virtual environment wrapper everytime I want to start a project before creating the virtual environment? or is the virtual environment wrapper already installed in my system and I just have to go straight to creating the virtual environment? These are the commands I used for creating my virtual environment //creating the virtual environment wrapper pip install virtualenvwrapper-win //creating a virtual environment called test mkvirtualenv test //installing django pip install django //creating my project folder mkdir project -
Sum up 2 values in Django views.py
I just wondering is it possible to sum up the total of B1 + B2 from my code below ? e.g. B1 + B2 = total views.py b1 = Income1.objects.filter(Q(title='Salary')| Q(title='Bonus')).annotate(as_float=Cast('total_amount', FloatField())).aggregate(Sum('as_float')) b2 = Income2.objects.filter(Q(title='Overtime')).annotate(as_float=Cast('total_amount', FloatField())).aggregate(Sum('as_float')) context= { 'b1':b1, 'b2':b2 } html <table> <tr> <th>#</th> <th>Details</th> <th>Amount</th> </tr> <tr> <td>1</td> <td>Salary and Bonus</td> <td>{{ b1.as_float__sum}}</td> </tr> <tr> <td>2</td> <td>Overtime</td> <td>{{ b2.as_float__sum}}</td> </tr> <tr> <td colspan="2">Total Amount</td> <td>{{ total.as_float__sum}}</td> </tr> </table> Really appreciate if you could help me on this. -
django password format is <algorithm>$<iterations>$<salt>$<hash>, isn't it danger?
when we use django framework usually we use user model when i create_user i need to set password and django always hash my password and when i saw database, password format is <algorithm>$<iterations>$<salt>$<hash> it means if our database was stolen attacker get a salt and how many itered each password. is it okay? i mean... i think i need to hide salt value and iterations value from database thank you :) -
User authentication with Django and NextJS
I am building a project that uses Django Rest Framework as the backend and NextJS serves React frontend. How can I integrate user authentication using these two technologies? In the future we might build a mobile app as well, so we need the backend to be consistent. Thank you for your time. -
django allauth, socialtoken table teardown every time when rerun server
I've found some problem with socialtoken table, every time i got rerun my django server (python manage runserver) data in socialtoken table will be deleted, how can i prevent this action Thanks -
'PaieForm' object has no attribute 'Mois' django
i have one app named prets i create new credit then i print a table of emprunteurs when every emprunteur has a table of months to pay her credit so i want to post the table of every emprunteur models.py class Garantie(models.Model): type = models.CharField(max_length=10) def __str__(self): return self.type class NewCredit(models.Model): """ Garantie = ( (1, 'Chéque'), (2, 'Immobilier'), (3, 'Terrain'), )""" Matricule_emprunteur = models.CharField(max_length=30,null=True) Nom_prénom = models.CharField(max_length=100) Num_compte = models.CharField(max_length=20,null=True) Début_paiement = models.DateField('Date_début_paiement (MM/dd/yyyy)', null=True) Fin_paiement = models.DateField('Date_fin_paiement (MM/dd/yyyy)', null=True) Libellé_garantie = models.ForeignKey(Garantie, on_delete=models.CASCADE) Valeur_garantie = models.CharField(max_length=30,null=True) Montant = models.CharField(max_length=30,null=True) Taux_interet = models.CharField(max_length=30,null=True) Interet_rem = models.CharField(max_length=30,null=True) Total_rem = models.CharField(max_length=30,null=True) def __str__(self): return self.Matricule_emprunteur class PaieCredit(models.Model): emprunteur= models.OneToOneField(NewCredit, on_delete=models.CASCADE, primary_key=True,default='0') Mois = models.CharField(max_length=50) Archiver = models.BooleanField(default=False) def __str__(self): return self.Matricule_emprunteur forms.py class CreditForm(forms.ModelForm): class Meta: model = NewCredit fields = '__all__' def __init__(self, *args, **kwargs): super(CreditForm,self).__init__(*args, **kwargs) self.fields['Libellé_garantie'].empty_label = "Select" class PaieForm(forms.ModelForm): class Meta: model = PaieCredit fields = '__all__' views.py def Emprunteurs_detail(request, id=0, emprunteur_id=0): if request.method == "GET": if id == 0: form = CreditForm() frm = PaieForm() else: emprunteur = NewCredit.objects.get(pk=id) form = CreditForm(instance=emprunteur) result = [] debut = emprunteur.Début_paiement fin = emprunteur.Fin_paiement while debut <= fin: result.append(debut) debut += relativedelta(months=1) list_month = [] for x in result: … -
How to speed up reading and writing binary file operation in python?
I have got a binary file(400MB) that I first want to read and then write to another file in python.Currently what I'm doing is very basic. file = 'file.bin' with open('temp','wb+') as dest: for chunk in file.chunks(): dest.write(chunk) This code is a part of my Django app that I want to speed up.Is there any other better way to speed up this operation? -
Django - Management Command - Pandas read_csv - Localhost working - Heroku
I seem to come across unique situations throughout this month. I need to read a file from the web and update the database. I have taken two approaches : Approach 1. Upload the values from the application itself - this could be time consuming and I could hit worker timeout - however, I have retained this approach - as it currently takes 27-29 seconds. Heroku timeout is at 30 seconds. Approach 2. Upload the values from Django Command Management . I have scheduled a job via Heroku. I used pandas - pd.read_csv file for reading a file from the web. Scenario 1: If I use approach 1, Localhost : It works fine Heroku : It works fine Scenario 2 : If I use approach 2, Localhost : It works fine Heroku : HTTP 503 error and not able to read the file What could be the solution for this ? P.S. - I plan to put requests and add a browser header and update this thread. -
RabbitMQ for http/https request queuing in Django
One of my clients wants to use RabbitMQ for request queuing on his Django DRF powered web app. the app is simple just saving and listing information with attachments (over S3 storage) with high traffic. As I know RabbitMQ acts as message broker which can be helpful while doing long tasks/sending emails/ generating PDFs. I am curious to know that in my scenario can I use rabbitMQ? and if yes then what will be the advantages of using it. -
raise ImproperlyConfigured("Error loading psycopg2 module: %s" django.core.exceptions.ImproperlyConfigured:
**I AM NEW TO DJANGO . WHEN I TYPE python manage.py makemigrations I GOT THE FOLLOWING ERROR** PS C:\Users\Aman\employee_project> python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Aman\employee_project\manage.py", line 21, in <module> main() File "C:\Users\Aman\employee_project\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Aman\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File … -
Django notification whenever interrupt happens
I have a django application which is integrated with c++ using subprocess. I need to show notifications whenever interrupt happens, For eg. if camera have any issues like reconnecting,not found etc, if the django part has any issues ... My django app needs to notify as well as it has to send request to corresponding part to solve the issue Could I use signal of django for this purpose? Is there any other way for solve this? -
How do I use python reverse() function to pass list of ids as query parameter?
I need to generate a URL with a list of object ids as query params. i.e Url will look something like admin/app/model/?id__in=1,2,3. I have used reverse('admin:app_model_changelist', kwargs={id__in:<list_of_ids>}) which doesn't seem to work -
Geeting Error "django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")"
i am providing correct credentials still getting this error. as i can access my MYSQL through writting simple python program with same credentials but i could access MYSQL through Django... need help i am attaching my screen capture of error enter image description here enter image description hereI.png -
Forgot to delete model objects before altering model fields in models.py
I am getting this error continuously when I try to open this database through django admin Exception Type: OperationalError at /admin/tasks/task/ Exception Value: no such column: tasks_task.task_name_id Initially I changed a lot a fields in models which already had some objects stored. Now I couldnt have gone back so i started a new app and copied all the files from old app as they were in the same project. deleted the old app and renamed the new app by the name of old one so that in the project wherever refrenced there wont be any problem. but now whenever i try to migrate i get this error: File "C:\Users\sarda\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 326, in check_constraints raise utils.IntegrityError( django.db.utils.IntegrityError: The row in table 'tasks_task' with primary key '1' has an invalid foreign key: tasks_task.task_name_id cont ains a value 'task_name_id' that does not have a corresponding value in tasks_task_list.id. models.py: from django.db import models import datetime from django.utils import timezone class Task_List(models.Model): task_name=models.CharField(max_length=100) c1=models.CharField(max_length=30, default="OTHER") c2=models.CharField(max_length=30, default="OTHER") c3=models.CharField(max_length=30, default="OTHER") time_esc=models.IntegerField(default=1) def __str__(self): return self.task_name class Task_manager(models.Manager): def create_Task(self, title,deadline): Task1 = self.create(title=title,deadline=deadline) # do something with the book return Task1 class Task(models.Model): STATUS = ( ('ONGOING', 'ONGOING'), ('COMPLETED','COMPLETED'), ('PENDING','PENDING' ), ('FINISHED','FINISHED') ) task_name=models.ForeignKey(Task_List, on_delete=models.SET_NULL, … -
make request to django URL's app from celery task
I have a django rest framework application which uses caching for some of the URLS. I am using cache_page decorator for caching these URL's in redis cache. These caches expire after 5 min. Now I want to implemnt a celery task that is called periodically (using celerybeat) after every 30 seconds to check if the cache for a particluar page exists or not in the redis cache. If not we need to create a cache. The problem here is that I don not have the request and response object since it is a celery task. I need a way to make request to the django application which will then perform the caching automatically. what should be the best approach for this ?