Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass external server IP to SSO service through Gunicorn and Nginx?
I'm setting up SSO using: Django (with django_auth_adfs), Gunicorn, NGINX, and Active Directory federation. I have successfully setup the Federation on active directory, however my server will only pass http://localhost or http://127.0.0.1 to AD for the Redirect URI. When I add these to the federation and test from my local machine this works, expected. But I can't get my server, CentOS7, to pass anything but localhost or 127.0.0.1. I'm not sure how to change, or what to change, on the server side to alter the outbound IP address from the internal Gunicorn to the external IP on the box itself. I have tried playing with the reverse proxy settings in NGINX, this didn't change what AD was receiving. I have tried changing the return 301 setting for the enabled site and this results in an infinite redirect. Currently using proxy pass for inbound through NGINX to Gunicorn to point to the socket. Expected results when a user navigates to the web page is that they are redirected to sign in on AD, this currently happens. After this AD should send them back to the web page with an authentication token, this currently happens but it fails because AD tries to … -
Is it possible to use django countries in manytomany field
Hello I have a quiz that maybe will help me reduce the number of model instances I will have for my code, I am working with django countries and I was asking if I can save more than one country in a model when I use the country field, again django countries serializer am working with does not return django full details about a country class CountrySerializer(serializers.Serializer): country = CountryField() my models has country being country = CountryField() any idea on how i can make this country model hold more than one counrty -
Pass javascript variable to views.py
I have the following script in a template.html function updateArea(e) { var data = draw.getAll(); var answer = document.getElementById('calculated-area'); if (data.features.length > 0) { var area = turf.area(data); // restrict to area to 2 decimal points var rounded_area = Math.round(area*100)/100; answer.innerHTML = '<p><strong>' + rounded_area + '</strong></p><p>square meters</p>'; var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data)); document.getElementById('export').setAttribute('href', 'data:' + convertedData); document.getElementById('export').setAttribute('download','data.geojson'); } else { answer.innerHTML = ''; if (e.type !== 'draw.delete') alert("Use the draw tools to draw a polygon!"); } } I want to take the area variable and convertedData variable and pass them to this view @login_required def fertisatmap(request): mapbox_access_token = if request.method == "POST": o_form = FertidbForm(request.POST, request.FILES) if o_form.is_valid(): fertidb = o_form.save(commit=False) fertidb.user = request.user # o_form.user = request.user.username() # fertidb.data = Fertidb.objects.create(convertedData) fertidb.save() messages.success(request, f'Vos informations ont été envoyées') return redirect('fertisat-map') else: o_form = FertidbForm() context = {'title': title, 'o_form': o_form} return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token}) how do i use request.post.get() to take the value of the area and convertedData in the view.py ? -
Serializer with custom response
I have the following example of serializer: class CallSerializer(serializers.Serializer): call_status = serializers.BooleanField() call_type = serializers.CharField() weight = serializers.IntegerField() How can I get the response including data on the results: { "results": [ { "call_status": True, "call_type": "open", "weight": 10, }, { "call_status": "data", "call_type": "result", "weight": "weight", }, ], "data": { "total": "2", "status": "1", } } Thank you. -
Is there a way, using queryset, for get count for certain field with more 3 values using Count model?
I'm trying get count of alternative field by certain question using one queryset. I tried this: Answer.objects.filter( evaluation_instance=EvaluationInstance(code=code), alternative__in=[1,2,3,4,5],question__type_question='RA' ).values('alternative') .annotate(count=Count('alternative')) And I got this output: <QuerySet [{'alternative': 1, 'count': 2}, {'alternative': 2, 'count': 4}, {'alternative': 3, 'count': 4}, {'alternative': 4, 'count': 4}, {'alternative': 5, 'count': 18}]> but I need to know how many answers with 5 (or 4 or ..1) has one question, so I added idquestion in the queryset: Answer.objects.filter( evaluation_instance=EvaluationInstance(code=code), alternative__in=[1,2,3,4,5], question__type_question='RA' ).values('alternative', 'question__id').annotate(count=Count('alternative')) But I got this: <QuerySet [{'alternative': 1, 'question__id': 5, 'count': 1}, {'alternative': 1, 'question__id': 13, 'count': 1}, {'alternative': 2, 'question__id': 4, 'count': 1}, {'alternative': 2, 'question__id': 6, 'count': 1}, {'alternative': 2, 'question__id': 12, 'count': 1}, {'alternative': 2, 'question__id': 14, 'count': 1}, {'alternative': 3, 'question__id': 3, 'count': 1}, {'alternative': 3, 'question__id': 7, 'count': 1}, {'alternative': 3, 'question__id': 11, 'count': 1}, {'alternative': 3, 'question__id': 15, 'count': 1}, {'alternative': 4, 'question__id': 2, 'count': 1}, {'alternative': 4, 'question__id': 8, 'count': 1}, {'alternative': 4, 'question__id': 10, 'count': 1}, {'alternative': 4, 'question__id': 16, 'count': 1}, {'alternative': 5, 'question__id': 1, 'count': 2}, {'alternative': 5, 'question__id': 2, 'count': 1}, {'alternative': 5, 'question__id': 3, 'count': 1}, {'alternative': 5, 'question__id': 4, 'count': 1}, {'alternative': 5, 'question__id': 5, 'count': 1}, {'alternative': 5, 'question__id': 6, … -
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax;"
I've been trying to use Django's built in test module with no luck I've tried changing my database, running it locally, etc and keep getting hit with the same error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'error' at line 1") test.py module below from rest_framework.test import APITestCase from universal.models import * from django.urls import reverse # Create your tests here. class UPCImageSearchTestCase(APITestCase): def setup(self): self.url = reverse('UPCImageSearch') testUpc = Item.object.create(item_upc = '001100110011') print(self.url) def test_fetch_success(self): self.data = { 'upc':'' } response = self.client.get(self.url,self.data) self.assertEqual(200,response_status_code) def test_fetch_failed(self): self.data = { 'upc':'' } response = self.client.get(self.url,self.data) self.assertEqual(500,response_status_code) -
Update context processor on Ajax .done()
I've an ecommerce page, where user can add items to their shopping cart. And when a user adds an item, the counter should reflect this new added item. For now, I have a context processor variable called {{cart_items_counter}} that gets update everytime the page reloads. But the new requirement is to not refresh the hole page but only the navbar item that contains the {{cart_items_counter}}: <li class="nav-item active"> <a class="nav-link" href="{% url 'carrito_de_compras:cart_detail' %}"><i class="fas fa-shopping-cart" style="color:white !important;"></i> ( {{ cart_items_counter }})</a> </li> I think I can achieve this using AJAX, and calling not the context_processor but a counter view to update the counter. And my guess is that I need to call this new view in the done method of the AJAX post call. How do I go about updating that navbar item content on AJAX done method? So only this part gets updated. Original cart_items_counter - context processor: def cart_items_counter(request): cart_id = request.COOKIES.get("cart_id") cart_items_count = CartItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() sample_items_count = SampleItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() pack_items_count = PackItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() unitary_product_items_count = UnitaryProductItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() total_items = cart_items_count + sample_items_count + pack_items_count + unitary_product_items_count return {'cart_items_counter': total_items} New cart_items_counter view: def update_cart_items_counter(request): cart_id = request.COOKIES.get("cart_id") cart_items_count = CartItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() sample_items_count = SampleItem.objects.filter(cart_id=cart_id, step_two_complete=True).count() pack_items_count … -
Django CSV upload UploadForm to database Clean
i would like to store the data from my uploaded CSV file, called data_file I cant loop over the rows by column name in my csv file. I get Encoding errors(UTF, ASCII), also when i use IO String. I am new to django so i dont know what i do wrong. I tried to do this in my view with: def upload(request): form = UploadForm(request.POST, request.FILES) if form.is_valid(): f = io.TextIOWrapper(form.cleaned_data['data_file'].file, enconding='utf-8') reader = csv.DictReader(f) for row in reader: print(row['customer']) the error i get is: utf-8' codec can't decode bytes in position 10-11: invalid continuation byte -
How to union basic queryset with a queryset with grouped data?
I want to union two django querysets where the first queryset is just basic queryset and the seconds one is the queryset with grouped data. Obviously the second queryset will have less fields and some extra fields. For example I have ReceivedNotification model and this model have 4 main fields. class ReceivedNotification(models.Model): receiver = FK(User) initiator = FK(User) event = Char(choices) created = DateTime() So my goal is to get a queryset of all received notifications for user and some of notifications should be grouped with other of the same event type. The first queryset will be: q1=ReceivedNotification.objects .filter(receiver=request.user, event__in=[list of some event types]) The second one will be: q2=ReceivedNotification.objects \ .filter(receiver=request.user, event__in=[list of different event types])\ .values('receiver', 'event')\ .annotate(created=Max(F('created')))\ .annotate(grouped_users=ArrayAgg(F('initiator'))) These querysets are pretty similar except that q1 doesn't have grouped_users column. So i added it: q1=q1.annotate(grouped_users=Values('', CharField()) At this point I am trying to union q1 with q2 but I got an error: django.db.utils.ProgrammingError: each UNION query must have the same number of columns Can it be a problem that q1 is a queryset with objects of ReceivedNotification model and q2 is like queryset with dict data? -
Unsuccessful to run Docker-Compose
$ docker version Client: 18.03.0-ce API version: go1.9.4 Git comFri Mar 23 08:31:36 2018 OS/Arch: falsews/amd64 Orchestrator: swarm Server: Docker Engine - Community Engine: 18.09.9 API version: go1.11.13imum version 1.12) Git commit: Wed Sep 4 16:55:50 2019 OS/Arch: false/amd64 Experimental: I am trying to build a Django project in Docker which is installed in my Windows 7 64bit machine. It failed. Please help. enter image description here -
How do I filter the created objects of a model by user, to apply an update, with two forms?
I have 2 forms (models.forms) which I am calling in my function, where I try to instantiate 2 related models for 1 foreign key (user). Through 2 forms, to which, I want to apply an update, but I want to call the object by user. what am i wrong please? views.py def update_permisos(request, pk, pk1): p = get_object_or_404(Permiso, pk=pk) form = Permiso_update(request.POST, instance=p) u = get_object_or_404(Users, pk1=pk) form2 = Users_up(request.POST, instance=u) if request.method == 'POST' and request.is_ajax(): if form.is_valid(): permiso = form.save(commit=False) permiso.usuario.d_pendientes = request.POST['d_pendientes']#valores, que van al campo permiso.usuario.h_pendientes = request.POST['h_pendientes']#valores, que van al campo permiso.save() return JsonResponse({'status':'true', 'msg':'Datos procesados correctamente'})#retornando JSon en jsConsole else: return JsonResponse({'status':'false', 'msg':'Datos procesados incorrectamente'})#retornando respuesta en jsConsole else: form = Permiso_update(instance=p) form2 = Users_up(instance=u) asrg = {'form':form, 'form2':form} return render(request, 'plantillas/permisos_update.html', asrg) I tried to do with the "Update View" class, but I still do not give, with what is wrong, thanks for everything views.py class PermisoUpdateView(UpdateView): model = Permiso second_model = Users template_name = 'plantillas/permisos_update.html' form_class = Permiso_update second_form_class = Users_up def get_context_data(self, **kwargs): context =super(PermisoUpdateView, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) p = self.model.objects.get(id=pk) u = self.second_model.object.get(id=p.pk) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in context: context['form2'] = … -
Python Django: Sending a message from server to client on database save()
I want to notify the client when my model is saved. I started by creating a django-signal on post_save. @receiver(post_save, sender=Scooter) async def scooter_post_update(sender, instance, created, **kwargs): # Notify client here Next I created the AsyncConsumer class from django-channels and provided its routing. // routing.py application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ path('scooters/', ScootersUpdateConsumer) ] ) ) ) }) // consumers.py class ScootersUpdateConsumer(AsyncConsumer): async def websocket_connect(self, event): print("Connected!", event) await self.send({ "type": "websocket.accept" }) async def send_message(self): await self.send({ "type": "websocket.send", 'text': 'Oy, mate!' }) async def websocket_receive(self, event): print("Receive!", event) async def websocket_disconnect(self, event): print("Disconnected!", event) Now my question is how can I call send_message() from the scooter_post_update() method. -
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