Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't test uploading file with Django clien.post method
I have problem with testing API method. I have model Game with such field: background = models.ImageField(max_length=255, null=True, blank=True, storage=s3_storage, upload_to='game_back/%Y/%m/%d') Serializer for that model looks like: class GameSerializer(serializers.ModelSerializer): class Meta: model = Game fields = (<list_of_fields>, 'background') I tried to write test that cat pass image to this model. But i have problem with Djnago test build-in method for post. If i write: file = open('<path_to>/test_image.png', 'rb') content_bytes = file.read() img = SimpleUploadedFile("uni_image.png", content_bytes, content_type="image/png") response = self.client.post( reverse('game_create'), data={'background': img}, format="multipart" ) Django raise an exception UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte on row with client.post I tried to pass base64 encoded data instead of SimpleUploadedFile use, but in this case my API serializer cant validate and save image file. Thanks for reacting! -
Django Rest Framework: Get field name from model definition
Within the Django Rest framework documentation it is suggested to declare the "field" list explicitly to avoid providing the data of new columns just by adding them to the model which may contain sensitive information. The field list is an array of strings, containing the field ids. To avoid declaring field ids, which actually do not exist in the model (e.g. typos or changed models) I tried to declare the list using object references - but always end up with "DeferredAttribute: object has no attribute ". I have read something that meta information is not available in objects and that you could solve that by defininig your own Meta class using Object._meta.get_fields() and store it in the class, but I thought there might be a simpler/more elegant way (and I do now know, how, in detail ;-)). Example: class Samples(models.Model): # Meta data, primarily used in AdminSite. class Meta: verbose_name = _('Samples') verbose_name_plural = _('Samples') samples_boolfield = models.BooleanField samples_textfield = models.CharField(max_length=2000, blank=True) views.py: class SamplesView(viewsets.ModelViewSet): serializer_class = SamplesSerializer queryset = Samples.objects.all() serializers.py: Version 1, which does not show any errors in pyCharm or makemigrations, but calling the API reults in "TypeError at /api/samples/: argument of type 'DeferredAttribute' is not iterable": … -
Django and Amazon Lambda: Best solution for big data with Amazon RDS or GraphQL or Amazon AppSync
We have a system with large data (about 10 million rows in on a table). We developed it in Django framework and also we want to use Amazon Lambda for serving it. Now I have some question about it: 1- If we want to use Amazon RDS (MySql, PostgresSQL), which one is better? And relational database is a good solution for doing this? 2- I read somewhere, If we want to use a relational database in Amazon Lambda, Django for each instance, opens a new connection to the DB and it is awful. Is this correct? 3- If we want to use GraphQL and Graph database, Is that a good solution? Or we can combine Django Rest-API and GraphQL together? 4- If we don't use Django and use Amazon AppSync, Is better or not? What are our limitations for use this. Please help me. Thanks -
Django channels on Elastic Beanstalk - is this config file correct?
Following this guide https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 to deploy a django project which uses channels. In the guide they mention to create the file <PROJECT_DIR>/.ebextensions/01_env.config with the following: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: <PROJECT_DIR/.../>wsgi.py aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: <PROJECT_DIR...CONFIG.FILE> PYTHONPATH: /opt/python/current/app/<PROJECT_DIR>:$PYTHONPATH If my project is called dashboard, is the following correct? option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "dashboard/dashboard/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "dashboard/dashboard/settings.py" PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH -
Django User and Group model permissions fields as manytomany
In my project, I'm using custom overridden admin templates but I cannot figure out how to change the permissions and groups selector in the User and Group models. I want to change them to how the ManyToMany field handles it or a multi-select. How to I change it? Thank you for reading this. -
'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 -
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 :)