Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unzip a file and save its content into a database
I am building a website using Django where the user can upload a .zip file. I do not know how many sub folders the file has or which type of files it contains. I want to: 1) Unzip the file 2) Get all the file in the unzipped directory (which might contains nested sub folders) 3) Save these file is into the database. I managed to unzip the file and to output the files path. However this is snot exactly what I want. Because I do not care about the file path but the file itself. In addition, since I am saving the unzipped file into my media/documents, if different users upload different zip, and all the zip files are unzipped, the folder media/documents would be huge and it would impossible to know who uploaded what. Unzipping the .zip file myFile = request.FILES.get('my_uploads') with ZipFile(myFile, 'r') as zipObj: zipObj.extractall('media/documents/') Getting path of file in subfolders x = [i[2] for i in os.walk('media/documents/')] file_names = [] for t in x: for f in t: file_names.append(f) -
How to make django screen dynamic with user choices?
So i work in a company and we constantly need to add view fields for the user, I would like to know if there is a way to make this option available to the end user, for example a dropdown with the options that the model admin where he is allowing. Today we use the django way of doing admin, for example: list_display = ( 'course', 'class', 'discipline', 'teacher', 'start_date', 'end_date' ) -
NGINX + Gunicorn: zero size buf in writer
we've run into a weird issue with NGINX and Gunicorn (serving pages from Django) and can't really figure out where to look next. The problem: The problem is that some seemingly random URLs of our site will return 502's instead of their correct content. After some unknown and again seemingly random amount of time the URL will return correctly again. This has happened repeatedly over a few months and over multiple different endpoints (some list routes, some detail routes, etc.) Relevant Architecture Setup: Our site is running in AWS with an Elastic Load Balancer in front and various ECS containers in back. Each ECS Container has two tasks running in it, one NGINX task and one Gunicorn/Django task. NGINX config: worker_rlimit_nofile 20000; # max usable file descriptors, should be about double the worker_connections and less than the OS `nofile` ulimit events { worker_connections 10000; } http { include /etc/nginx/mime.types; upstream app-server { server app:8000; } log_format json_combined escape=json '{ "time_local": "$time_local", ' '"remote_addr": "$remote_addr", ' '"request": "$request", ' '"status": "$status", ' '"message": "$remote_addr - $request - $status - $request_time - $body_bytes_sent - $http_user_agent", ' '"forwarded_for": "$http_x_forwarded_for", ' '"body_bytes_sent": "$body_bytes_sent", ' '"request_time": "$request_time", ' '"http_referrer": "$http_referer", ' '"http_user_agent": "$http_user_agent" }'; error_log … -
GraphiQL query returning CSRF_FAILURE_VIEW
I'm just doing the tutorial @ https://docs.graphene-python.org/projects/django/en/latest/tutorial-plain/ to understand graphQL and graphene with Django 2. I haven't used Django in a while, and the tut seems to be for Django 11. I'm getting a CSRF_FAILURE_VIEW when I try a GraphQL query like so: query { allIngredients { id name } } The underlying json fixture looks like this: [{"model": "ingredients.category", "pk": 1, "fields": {"name": "Dairy"}}, {"model": "ingredients.category", "pk": 2, "fields": {"name": "Meat"}}, {"model": "ingredients.ingredient", "pk": 1, "fields": {"name": "Eggs", "notes": "Good old eggs", "category": 1}}, {"model": "ingredients.ingredient", "pk": 2, "fields": {"name": "Milk", "notes": "Comes from a cow", "category": 1}}, {"model": "ingredients.ingredient", "pk": 3, "fields": {"name": "Beef", "notes": "Much like milk, this comes from a cow", "category": 2}}, {"model": "ingredients.ingredient", "pk": 4, "fields": {"name": "Chicken", "notes": "Definitely doesn't come from a cow", "category": 2}}] Forgive a noob, but there must be something that changed with Django 2? Is there another setting I need to apply? In settings.py I have: GRAPHENE = { 'SCHEMA': 'cookbook.schema.schema' } My folder structure is slightly different to the tut in that I have my ingredients app not nested within my cookbook app. The cookbook app is the main app like so: -
Django custom LoginView not logging user in
I'm fairly new to Django, but I'm trying to build a customized authentication system by subclassing the generic Django authentication components. The main issue is that my custom LoginView does not seem to do anything besides refresh the page. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm, ReadOnlyPasswordHashField, AuthenticationForm, UsernameField from django.utils.translation import gettext, gettext_lazy as _ from .models import CustomUser BUREAU_CHOICES = [ ('HR', 'Human Resources'), ('CRT', 'Creative'), ('ACC', 'Accounting'),] class CustomAuthForm(AuthenticationForm): bureau = forms.ChoiceField(widget=forms.Select, choices=BUREAU_CHOICES) username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True, 'placeholder': 'Username'})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'placeholder': 'Password'}), ) class Meta: model = CustomUser fields = ('email', 'password',) views.py from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.views import LoginView from django.contrib.auth import authenticate, login from django.contrib.auth.forms import AuthenticationForm from .forms import CustomAuthForm class CustomLoginView(LoginView): form_class = CustomAuthForm authentication_form = CustomAuthForm template_name = 'users/login.html' urls.py from django.urls import path from . import views app_name='users' urlpatterns = [ path('login/', views.CustomLoginView.as_view(), name='login'), ] So I've read answers here, here and here which all seem to involve overriding methods from the superclass LoginView. When I rewrite my CustomLoginView to override a method, they are not being called. For example: views.py class CustomLoginView(LoginView): form_class = CustomAuthForm authentication_form … -
create ManyToManyField using field in through table as condition
This is what I want to achieve: class Event(Model): attendees = ManyToManyField(User, through='Involvement', related_name='attended_events') interested_users = ManyToManyField(User, through='Involvement', related_name='interested_in_events') organizers = ManyToManyField(User, through='Involvement', related_name='organized_events') class Involvement(Model): event = ForeignKey(Event, CASCADE) user = ForeignKey(User, CASCADE) involvement = CharField(choices=(('INTERESTED', 'Interested'), ('ATTENDED', 'Attended'), ('ORGANIZED', 'Organized'))) The error I'm receiving: The model has three identical many-to-many relations through the intermediate model 'app.ActivityInvolvement'. I know limit_choices_to doesn't work on ManyToManyField, how would I go about making this happen, without creating 3 through tables with the same structure? -
Installed_Apps Django How to Name
What different between 'index'(app name) and 'index.apps.IndexConfig' in INSTALLED_APPS settings -
Can't filter empty queries in Django search bar
absolute beginner in Django, i'm trying to write my own search form on my website. Results appear, but the "no results" always appear on the website even with no search. I wonder if it's an error in my if/endif loop. <div class="col-6"> <form action="{% url 'home' %}" method="GET" value="{{request.GET.q}}" class="form-inline md-form form-sm mt-0"> <i class="fa fa-search" aria-hidden="true"></i> <input class="form-control form-control-sm ml-3 w-75" aria-label="Search" name="q" type="text" value="{{request.GET.q}}" placeholder="Chercher livre, plat, auteur, ISBN..." aria-label="Search"> </form> </div> </div> </div> {% if request.method == 'GET' and request.GET.q != '' %} {% if results %} <h1>Results for <b>{{ request.GET.q }}</b></h1> <br/> {% for result in results %} <a href="{% url 'detail_biblio' result.pk %}">{{result.titre_livre}}</a>, {{result.annee}} <br/> {% endfor %} {% else %} No search results for this query {% endif %} {% endif %} thanks for your help ! joao -
Django custom AppConfig breaks the project
I've got a bare-bones demonstration Django project created with Django 2.2. The structure looks like: my_project/ ├── db.sqlite3 ├── my_app │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── urls.py │ └── views.py ├── manage.py ├── my_project │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── requirements.txt This started as a tiny issue: "my_app" was showing up in the Django admin as "MY_APP" (with an underscore). The Django docs say that you can make this prettier by defining a custom app config that subclasses "django.apps.AppConfig", and that typically this subclass would be defined in (using my example) "my_app/apps.py". In fact, using manage.py startapp my_app even generates this for you: # my_app/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'my_app' The docs also say to "put the dotted path to that subclass in INSTALLED_APPS". Another approach is to set the default_app_config variable in your app's "__init__.py", but that "New applications should avoid default_app_config. Instead they should require the dotted path to the appropriate AppConfig subclass to be configured explicitly in INSTALLED_APPS." However, if I do add the path to the custom app config into INSTALLED_APPS like this: # settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', … -
Calculating file size using python which comes from a request (HTTP)
Does anyone know how to calculate the size of a file which comes from a client's storage via request (HTTP) with Python? In the normal scenario there must be a file path, but in this special case, there is no and the file is as a data! So how can I calculate it without using os modules? -
How do I compare two querysets in Django and filter those which don't match exactly?
I have three models, Fridge, Recipe and Ingredient and I want to get queryset of all recipes and compare their ingredients with the food contents of my fridge object. I want to filter out all of the recipes, which don't have the matching ingredients to my food contents and return the queryset only of those matching. I am pretty new to Django and I wasn't able to find a way how to do it. I only managed to filter out recipes using a search input, but that is just a single word. class Fridge(models.Model): name = models.CharField(max_length=20) belongs_to = models.ForeignKey(User, related_name="my_fridge", on_delete=models.CASCADE) food_contents = models.ManyToManyField(Food, related_name="in_fridges") slug = models.SlugField(allow_unicode=True, unique=True) class Recipe(models.Model): name = models.CharField(max_length=255, unique=True) rating = models.CharField(max_length=255) preparation_time = models.CharField(max_length=255) servings = models.CharField(max_length=255) instructions = models.CharField(max_length=1000) slug = models.SlugField() class Ingredient(models.Model): name = models.CharField(max_length=255) recipe = models.ForeignKey(Recipe, related_name="ingredients", on_delete=models.CASCADE) -
Redirect domain to .com in django in url.py
I have a website in Django, hosted in Heroku. I have 2 domains, registered in different places: mysite.com and mysite.com.br I don't want to be penalized by Google for having 2 domains with the same website, therefor I would like to redirect everyone who enters mysite.com.br to mysite.com. I entered in the DNS mysite.com.br(Not hosted anywhere) CNAME mysite.com(hosted in Heroku), which makes the user actually access the Heroku content, but the url keeps the .BR .... So the Heroku support told me to do the redirection in the application. In this case, what's the best practice to redirect? I would imagine to do that in the url.py, but how can I do that if the "path" doesnt read the domain? Thanks. -
Which one is better to user API View or Function based view or Generic Viewset
I am confused which one to use in which scenario in Django view official documentation -
Django - Get objects from a squared many-to-many relation
I'm starting a Django project with models like: Vendor <- many to many -> Product <- many to many -> Category Is there an efficient way to get all the categories linked to the products of a vendor ? Current inefficient way: Get all the products of a specific vendor For all products get their specific categories Remove duplicates of the categories list If possible I would like to avoid creating a fake many-to-many relation between Category and Vendor. Thanks in advance, -
Cannot access FileResponse.streaming_content and return FileRespone
The situation: I can return an HTTP response containing a file. I can return an HTTP response containing the hash of the file. I cannot return both the file and the hash at the same time. When trying to access the streaming_content property of a Django FileResponse object, the HTTP request times out and fails to return. This code correctly returns the requested file. class DownloadFile(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: user = request.user most_recent_report = Reports.objects.filter(user_id=user).latest("created_date") most_recent_report_filepath = settings.BASE_DIR + most_recent_report.filepath filename = 'report.pbf' response = FileResponse(request, open(most_recent_report_filepath, 'rb'), content_type='application/json') response['content-disposition'] = 'attachment; filename="%s"' % filename return response except Exception as e: return Response({'status': str(e)}, content_type="application/json") This code correctly returns the SHA256 hash of the requested file. class DownloadFile(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: user = request.user most_recent_report = Reports.objects.filter(user_id=user).latest("created_date") most_recent_report_filepath = settings.BASE_DIR + most_recent_report.filepath filename = 'report.pbf' response = FileResponse(request, open(most_recent_report_filepath, 'rb'), content_type='application/json') response['content-disposition'] = 'attachment; filename="%s"' % filename h = hashlib.sha256() partial_data = b''.join(response.streaming_content) h.update(partial_data) partial_hash = h.hexdigest() return Response({'status': str(partial_hash)}) except Exception as e: return Response({'status': str(e)}, content_type="application/json") This code fails to return anything and times out. class DownloadFile(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: user = request.user most_recent_report = Reports.objects.filter(user_id=user).latest("created_date") … -
Polymorphic model fixtures fail when loading from Django tests
I'm running a few test using fixtures to create initial data I need. The fixtures dump/load correctly to populate the actual db, but when loading the fixtures during tests I get the error: polymorphic.models.PolymorphicTypeInvalid: ContentType 9 for <class 'attributes.models.Attribute'> #5 does not point to a subclass! Here is that fixture: - model: items.item pk: 1 fields: polymorphic_ctype: 12 name: White T-Shirt plural_name: White T-Shirts - model: items.item pk: 2 fields: polymorphic_ctype: 12 name: Black Jeans plural_name: Black Jeans - model: items.item pk: 3 fields: polymorphic_ctype: 11 name: Firebomb plural_name: Firebombs - model: items.item pk: 4 fields: polymorphic_ctype: 10 name: Gold plural_name: Gold - model: items.item pk: 5 fields: polymorphic_ctype: 9 name: Fork plural_name: Forks - model: items.weaponitem pk: 5 fields: {} - model: items.apparelitem pk: 1 fields: {} - model: items.apparelitem pk: 2 fields: {} - model: items.combatitem pk: 3 fields: {} - model: items.materialitem pk: 4 fields: {} Here is the actual line where the test fails: fixtures = ['characters/fixtures/tests', 'items/fixtures/tests', 'skills/fixtures/tests'] user_character = None def setUp(self): human_class = CharacterClass.objects.get(name='Human') self.user_character = UserCharacter.objects.create(name="Ratboi", character_class=human_class) def test_inventory_methods(self): user = self.user_character fork = WeaponItem.objects.get(name='Fork')``` Fails here at last line, getting "fork". The other fixtures load appropriately, but items are the only … -
How do I write a queryset to display all products linked to a category?
I am new to Django and am trying to display my products on a page that are linked to a certain category. I have tried codes such as queryset = Product.objects.filter(category__exact='Badges') Here are my models. class ProductCategory(models.Model): title = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.PROTECT) class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(ProductCategory, null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) image = models.ImageField(upload_to='products/', null=True, blank=True) I am expecting to get the objects in products that are linked to a certain category to print. -
Django python: 'init_command' is an invalid keyword argument for this function
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'bookingsystem'), 'USER': 'root', 'PASSWORD': '', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } When I enter: python manage.py migrate It returns the error: TypeError: 'init_command' is an invalid keyword argument for this function I'm looking to create new tables on my database, but when I reload phpmyadmin through XAMPP nothing changes. I can't seem to figure out the error, so any help is greatly appreciated. I was trying to follow the guide: https://data-flair.training/blogs/django-database/ -
Establish connection to (another) server on server startup
I currently have a requirement where I'll need my Django server to establish a connection to a 3rd party provider (via sockets) and listen for events. The 3rd party uses TCP to send/receive messages and requires me to do some socket programming to integrate their services. What I think is supposed to happen: Django server acts as client socket, 3rd party server will send messages to my Django server and I'll have to appropriately decrypt each message and have respective functions to handle those messages. Things I'm confused about: The correctness of this setup / architecture. Where to place code in Django so that when I run python manage.py runserver my python socket code will execute (the socket.connect($HOSTNAME, $PORT) step) -
Django get Visitor's Location
I am trying to build a Django web application that will store internal tracking metrics (along with doing it's own work). I have so far created models to get API hit counters. I want to check from which location user accessed my application. For that purpose I have to store data in GeoDjango Model. from django.contrib.gis.db import models class AccessLocation(models.Model): location = g_models.PointField() user = models.ForeignKey(User,on_delete=models.PROTECT) class Meta: abstract = True db_table = "location_info" Now I want to capture User's location when they access my views and store in data-base. Is there any django/pythonic way to do it? For eg: hidden form fields that captures user location (latitude and longitude)? -
TypeError at post/4/remove : 'str' object is not callable
I am trying to delete a post(confirm delete) using DeleteView. I run into the below error: TypeError at /post/4/remove/ 'str' object is not callable New to Django-working on a blog application. Other functionalities are working fine but when I attempt to delete a post(confirm delete). I run into the below error: urls.py: http://codepad.org/SP55psyf urlpatterns = [ ... url(r'^post/(?P\d+)/remove/$',views.PostDeleteView.as_view(),name ='post_remove'), ... ] views.py: http://codepad.org/BVsApXhB(complete file) class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') Models.py : http://codepad.org/TLUo4NJG post_confirm_delete.html : http://codepad.org/795iD3RB -
static files not serving in django
I'm trying to deploy my django app since last tuesday using this tutorial , https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 .I redeployed my droplet five times still no avail.Whenever i run collecstatic, it's not showing static files but correctly showing admin styles files. The droplet is live at, https://157.245.108.160:8000 . I'm disapointed from digitalocean . It's a way more easier to deploy at pythonanywhere. Please help me. I also checked twice that files are at correct location -
Django 2.2.6: Reading JSON data returns "None" as output
Trying to send a basic POST request, read the data, and send it back as a response. The JSON data sent looks like this { "user": "user1" } The python code: class User(View): def post(self, request): data = request.POST.get("user") return HttpResponse(data) Expected response: user1 Actual response: None (It prints the word 'None') -
When calling super().save() in overriden save method, model is not updating ManyToManyField
If I have a model with a field that is a ManyToManyField, calling super().save() inside of the overidden save method, the model object is not getting updated if referenced inside of the save method. models.py class AddOn(models.Model): name = models.CharField(max_length=100) class Invoice(models.Model): additional_options = models.ManyToManyField(AddOn) def save(self, *args, **kwargs): super().save() # this prints the objects that were selected prior to the save. # this isn't helpful if the selected objects have changed. print(self.additional_options.all()) -
How to restrict access for staff users to see only their information in Django admin page?
I have created a custom Django admin page. I have two types of users who can access admin page (staff user and superuser). Superuser can see all the users and can change their settings. He can also add or delete users. The staff user can only see their settings and can change some of them. I currently have a problem that staff users can see all users of the web application and can add or delete them. I restricted staff users to see certain settings but could not change it. I do not know how to restrict staff users to see only their settings. Here is my code: Admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserAdminChangeForm, UserAdminCreationForm from .models import UpLoadFile User = get_user_model() admin.site.site_header = 'SRC Orkestracija' admin.site.index_title = 'Administration' admin.site.register(UpLoadFile) class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserAdminChangeForm add_form = UserAdminCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('username', 'superuser', 'active', 'staff') list_filter = ('superuser', 'active', 'staff') readonly_fields = …