Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'UserDetailView' object has no attribute 'object_list'
everyone! In the user detail page I have user's posts, which I want to paginate(planning to make infinite pagination later on). Trying to to that, I get the error 'UserDetailView' object has no attribute 'object_list'. I was searching a lot for solution, but did not find clear example how to paginate related objects in detail view. Any help on this higly appreciated. This is my DetailView for user: class UserDetailView(DetailView,MultipleObjectMixin): model = CustomUser template_name = 'users/user_detail.html' context_object_name = "user" paginate_by = 5 def get_object(self): id_ = self.kwargs.get('id') return get_object_or_404(CustomUser, id=id_) def get_context_data(self, **kwargs): posts = self.object.posts_set.all().order_by('-created_at') #context['posts'] = self.object.posts_set.all().order_by('-created_at') context = super(UserDetailView, self).get_context_data(posts=posts, **kwargs) context['main'] = Main.objects.get(pk=1) context['supporters'] = CustomUser.objects.filter(team = self.object.team) return context And the error I get : 'UserDetailView' object has no attribute 'object_list' Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/user/1/ Django Version: 3.0.7 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'team.apps.TeamConfig', 'posts.apps.PostsConfig', 'main.apps.MainConfig', 'crispy_forms', 'django.contrib.humanize', 'rest_framework', 'pytils'] 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 (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
Django response with additional headers returns 500
Our application developed in Django needs to pass some additional headers in selected requests. We do so this way: original_response = Response(status=status.HTTP_204_NO_CONTENT) original_response['X-Status-Type'] = 'info' original_response['X-Status-Message'] = 'Il cliente è stato avvertito' return original_response In our method. However, while this works on our local setup, on heroku this generates a 500 error which we cannot figure out. -
Problem connecting to websocket on my django App after deployment on Azure
After deploying the django App on Azure via VS Code, html pages are working fine but seems that I have a problem connecting to the websocket, even though that I enabled the websocket on my azure portal app. Console log: Firefox can’t establish a connection to the server at wss://myapp.azurewebsites.net:8080 The app is running on docker: FROM python:3.7-buster # Define environment variables ENV ACCEPT_EULA=Y ENV PYTHONUNBUFFERED=1 # Expose port EXPOSE 8080/tcp # Create app directory WORKDIR /django_ui # Copy all files to image COPY . . # Install recuired apt packages RUN apt-get update && apt-get install -y --no-install-recommends gcc unixodbc unixodbc-dev build-essential curl # Install microsoft sql driver for debian RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - && \ curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list && \ apt-get update && \ apt-get install -qq -y msodbcsql17 && \ apt-get install -qq -y mssql-tools && \ echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile && \ echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc # Install recuired pip packages RUN pip install -r ./req/requirements.txt # Remove requirements RUN rm -rf ./req # Run django websocket server 0 0 0 0 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8080"] The endpoint in my .js file looks like this: // Get endpoint var … -
Django how to import value in request function from another one?
I have the following views function: def stato_patrimoniale(request): now=datetime.datetime.now() last_account_year=float(now.year)-1 #definizione dell'ultimo anno contabile now = now.year if request.method == 'POST': year = request.POST['year'] if year != '': now = year last_account_year = float(now) - 1 context= { 'last_account_year': last_account_year} return render(request, 'stato_patrimoniale/stato_patrimoniale.html', context) Now I want to use the last_account_year value in another views.py. It's possible? -
i got an error. django.urls.exceptions.NoReverseMatch
l am started to learn Django for few days, i got an error. django.urls.exceptions.NoReverseMatch: Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']* urls.py path('create_order/<str:pk>/', views.createOrder, name='create_order'), views.py def createOrder(request, pk): customer = Customer.objects.get(id=pk) form = OrderForm(initial={'customer': customer}) if request.method == 'POST': # print('Printing:', request.POST) form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'form': form } return render(request, 'accounts/order_form.html', context) order_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <br> <div class="row"> <div class="col-12 col-md-6"> <div class="card card-body"> <form action="" method="post"> {% csrf_token %} {{form}} <input class="btn btn-sm btn-danger" type="submit" value="Conform"> </form> </div> </div> </div> {% endblock %} customer.html <div class="row"> <div class="col-md"> <div class="card card-body"> <h5>Customer:</h5> <hr> <a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a> <a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a> </div> </div> -
Call a pop up delete modal usin g django DeleteView
i am using django generic deleteview for deleting my object. i want to delete object from list of objects. There is a trash icon. If user clicks the trash icon a popup modal will come to ensure whether the user wants to delete the object or not. The popup will have a cancel button and a delete button. If the user choses delete button the object will be deleted forever. But the problem is the listview is in one html and deleted popup modal html is in other html. As i am using django generic class for ListView and DeleteView, I have to keep two separate html. now I dont know how can i connect both htmla and show a popup delete option employe_list.html: this html shows the listview of employees. {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> <div class=""> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Employees</b></h2> </div> <div class="col-sm-6"> <a href="{% url 'employee:employee-add' %}" data-target="exampleModal" class="btn btn-success" data-toggle="modal"> <span ></span> <i class="material-icons"></i> <span data-feather="plus"></span>Add New Employee </a> <!--<a href="#deleteEmployeeModal" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE15C;</i> <span>Delete</span></a>--> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <th> <span class="custom-checkbox"> … -
Best way to get all model fileds names
What is the best way to get the list of all fields names of a model: I use: list_of_model_field = Mymodel_meta.get_fields() is there any other way? -
Translate response django geoip2 maxmind
I need localization response geoip GeoLite2 maxmind. The site on django, trying to fasten the location. I do according to the instructions from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() g.city('72.14.207.99') Response: {'city': None, 'continent_code': 'NA', 'continent_name': 'North America', 'country_code': 'US', 'country_name': 'United States', 'dma_code': None, 'is_in_european_union': False, 'latitude': 37.751, 'longitude': -97.822, 'postal_code': None, 'region': None, 'time_zone': 'America/Chicago'} Fine work, but I need to get an answer in another language, for example ru-RU. How to do it? Maybe you need to specify some argument? I would be grateful for any help. -
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?