Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I display a geocoded Google Maps address as a marker on my map?
I used gmaps.geocode python library to produce this: [{'address_components': [{'long_name': 'Alabaster', 'short_name': 'Alabaster', 'types': ['locality', 'political']}, {'long_name': 'Shelby County', 'short_name': 'Shelby County', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Alabama', 'short_name': 'AL', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'United States', 'short_name': 'US', 'types': ['country', 'political']}], 'formatted_address': 'Alabaster, AL, USA', 'geometry': {'bounds': {'northeast': {'lat': 33.2717601, 'lng': -86.752692}, 'southwest': {'lat': 33.1672109, 'lng': -86.8732169}}, 'location': {'lat': 33.2442813, 'lng': -86.8163773}, 'location_type': 'APPROXIMATE', 'viewport': {'northeast': {'lat': 33.2717601, 'lng': -86.752692}, 'southwest': {'lat': 33.1672109, 'lng': -86.8732169}}}, 'partial_match': True, 'place_id': 'ChIJU_ollPgliYgRUDCwXEedAQc', 'types': ['locality', 'political']}] Using Django I can spit out this data for every listing saved in my database. What is the best way of having every geocoded address displayed on my map: html: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <style> /* Set the size of the div element that contains the map */ #map { height: 700px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> <body> <!--The div element for the map --> <div id="map"></div> <script> // Initialize and add the map function initMap() { // The location of Uluru var uluru = {lat: -25.344, lng: 131.036}; // The map, … -
Auto assigning 3 types of user roles on sign up in Django
I am new to Django and trying to create a website that has two user roles primary and member. Member (users) are invited to the website via email. Is there any way to auto assign roles by submitting the sign up form. Right now on the website, all users are directed to the same sign up form on the same url path. Is that an issue in accomplishing my goal? Users models.py import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from rest_framework.reverse import reverse from testapp.common.models import BaseModel class User(AbstractUser, BaseModel): USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] email = models.EmailField(verbose_name="email address", max_length=255, unique=True) first_name = models.CharField(_("First name"), max_length=255) last_name = models.CharField(_("Last name"), max_length=255) is_parent = models.BooleanField('parent status', default=False) is_village_member = models.BooleanField('village member status', default=False) def __str__(self): return self.email def get_api_url(self, request=None): kwargs = {"uuid": self.uuid} return reverse("user-detail", kwargs=kwargs, request=request) @cached_property def stripe_customer(self): return self.djstripe_customers.first() @property def stripe_sources(self): if self.stripe_customer is None: return [] return self.stripe_customer.sources def save(self, **kwargs): if self.pk is None: self.uuid = uuid.uuid4() self.username = str(self.uuid) return super().save(**kwargs) Families models.py from allauth.account.signals import user_signed_up from django.db import models from django.db import transaction from django.db.models.signals import … -
Display fields from foreign key linked model django
So I've created an API with the Django rest framework. I have a simple model relationship which is, User -> Posts. Users are linked to the posts because the user is the AUTHOR of a post. All I want to do is display the username associated with a POST in my rest API. How do I reference other fields from a model that I linked as a foreign key? IF I have a user model that has a username, profile picture and email, how can I display those in my Post model??? Here is an example of what I am trying to do with the models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() image = models.ImageField(default='default.mp4', upload_to='video_thumbnails') videoFile = models.FileField(default='default.mp4', upload_to='videos') date_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User , #Something to get the username here, on_delete=models.CASCADE) Right now this displays { "title": "HOLROYD SWIPE ACCESS(CS ROOMS)", "content": "Yeet", "image": "http://127.0.0.1:8000/media/video_thumbnails/Screenshot_from_2019-08-03_23-37-50.png", "videoFile": "http://127.0.0.1:8000/media/videos/Screenshot_from_2019-08-03_23-37-52.png", "date_posted": "2019-10-22T21:01:07Z", "user": 1 } All I want it to do is display the name of the user instead of the USER ID which is 1 in this case. I JUST want it to look like this instead { "title": "HOLROYD SWIPE ACCESS(CS ROOMS)", … -
How can I start project on domain using gunicorn and nginx?
I have a domain (example.com). How can I run project on this domain using nginx and gunicorn. I'm use Python 3.6 and Django 2.2. Nginx /etc/nginx/sites-available/example.com server { listen 80; listen [::]:80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/project; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful Gunicorn gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/home/project ExecStart=/home/project/projectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Django /home/project/project/settings ALLOWED_HOSTS = ['example.com', 'localhost'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': '1q2w3e4r', 'HOST': 'localhost', 'PORT': '', } } -
Django: For loop inside href attribute
I am playing around with Django, and I wonder if I have pagination together with a search including multiple checkboxes, how can I can pass both the query and the selected checkboxes to the next page. For example, when I provide the link for the next page I want to have something like: {% if results.has_next %} <a href="?page={{ results.next_page_number }}&q={{ request.GET.q }}{{&c=checkbox for checkbox in request.GET.getlist('c')}}">next</a> {% endif %} Please let me know if I need to elaborate a bit more on what I need. -
Getting Heroku Error H10 (App crashed) when pushing
Here is the logs file: (venv) C:\Users\Wasim Rana\PycharmProjects\website>heroku logs --tail 2019-10-22T20:59:23.053699+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path= "/" host=wasimrana.herokuapp.com request_id=8a232e19-10dd-48c8-841c-0f3ece6f54e1 fwd="103.196.233.9" d yno= connect= service= status=503 bytes= protocol=https -
ModuleNotFoundError: No module named 'crispy_forms'
I have installed crispy_forms on both python2 and python3, however, I am still getting an error... I believe I know what the problem is, I just do not know how to solve it. For some reason, I have python2.7, python3.5, and python3.7 installed. When I install crispy_forms using pip, it installs it for python2.7. When I install crispy_forms using pip3, it installs it for python3.5. However, my Django project uses python3.7, hence the error. How can I get crispy_forms over to 3.7? I have already put INSTALLED_APPS [ . . . 'crispy_forms', ... ] -
Django Conditional Choices
I am new to Django and have been working on a project where I am trying to have choice fields dependent on bool values attached to the current user. I have this in the model user = models.OneToOneField(user_model, on_delete=models.CASCADE) #### I_CAT = models.BooleanField(default=False) I_DOG = models.BooleanField(default=False) I_PAW = models.BooleanField(default=False) I_OPTIONS = [ [('star'), ('Star')], When(I_CAT=True, then=Value([('cat'), ('Cat')])), ] icon = models.TextField(choices=I_OPTIONS, default='star') I am looking to have it so that when the value I_CAT for the current user is set to True it will add that option to our choices list which is used as choices list for icon. I don't really know the best way to approach this. I have tried to use When and if statements in the model file itself and also in the views for this page. I haven't managed to get anything to work yet the closest I got was this if I_CAT: I_OPTIONS.append([('cat'), ('Cat')]) This succeeds in adding something to the options list but it doesn't actually check if I_CAT is true or not and just adds it every time no matter what. I also read on another post that if statements inside a model are a bad idea so idk. Any guidance would … -
Why is the GET request for static files returning 404, except for base.css which returns a 200
I am in the process of deploying a simple website written with Django to AWS Elastic Beanstalk. Everything seems to be working, except for some of my static resources (CSS + image files) returning 404 errors. I have run python manage.py collectstatic to organize all my static resources as follows: -project |-... |-static | |-admin | | |-... | | | |-app1 | | |-style.css | | |-img1 | | | |-app2 | | |-style.css | | | |-project | | |-base.css |-... I have identified two EB logs: "GET /static/project/base.css HTTP/1.1" 200 "GET /static/app1/style.css HTTP/1.1" 404 base.css is served up fine, but when attempting to retrieve app/style.css, I get an error, despite the path matching the structure I have above. Any reason why this would be? -
Django Filter Queries in List by the last x Days with Timedelta shows only Queries of substracted Day, not full Range
i am trying to make a list to show the queries of the last 100 Days. If iam using Timedelta in the filter i can list the queries of the substracted Day. Only the exact Day. But i want to list all Queries between the Date in the Datefield and the Day in Timedelta Filter. What iam doing wrong? class Appointment(models.Model): Appointment_Company = models.ForeignKey(Company, on_delete=models.CASCADE) Appointment_Theme = models.CharField(max_length=200) Appointment_Info = models.TextField() Appointment_Date = models.DateField(default=datetime.today) def __str__(self): return self.Appointment_Theme class AppointmentView(DetailView): template_name = 'timecheck/Appointment_100.html' model = Company def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context['Company_list'] = Company.objects.all() context['Appointment_list'] = Appointment.objects.filter(Appointment_Date=datetime.today() - timedelta ( days = 100 )) print (context) return context -
How to send emails to verify users using django-rest-auth
I set up Django custom registration using the Django-rest-auth, I also want to verify the email by sending emails which I heard that Django all auth does out the box. but this doesn't seem to work. I don't know if to install any package or what. I created a custom register which inherits from Django-all-auth, but it doesn't seem to work still. my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' # EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email my custom register views.py from rest_auth.registration.views import RegisterView from django.contrib.auth import get_user_model class CustomRegisterView(RegisterView): def … -
Django Securing Settings Using django-environ
I'm following the documentation and a tutorial to create environment variables to safeguard my keys. They use a DATABASE_URL that they seem to stitch manually in the .env file. For example the documentation uses psql://urser:un-githubbedpassword@127.0.0.1:8458/database. My database might change eventually and I only want to change what I need. When I try to indicate anything other than a DATABASE_URL it says there are is no 'default' for database. I'm assuming that 'default' is a django-environ thing. How can I save my environment variables in this format: .env DEBUG=True SECRET_KEY='AAAAA' ENGINE=BBBBBB NAME=CCCCC DB_USER=DDDDD PASSWORD=EEEEE HOST=FFF.com PORT=5432 settings.py ENGINE = env('ENGINE') NAME = env('NAME') DB_USER = env('DB_USER') PASSWORD = env('PASSWORD') HOST = env('HOST') PORT = env('PORT') DATABASE_URL=ENGINE+'://'+DB_USER+':'+PASSWORD+'@'+HOST+':'+PORT+'/'+NAME DATABASES = { 'default': DATABASE_URL} -
Unexpected behaviour by elasticsearch "query_string" for different fields having same mapping
I am using Elasticsearch version 6.3.1 for a django project. I am using regular expressions supported by query_string filter but two of my fields in same index have same mapping although while searching with spaces, one key is returning values and other is not. As both of my fields have strings stored in them so I have tried with both keyword and full-text search with query_string. Mappings - Field 1 - {u'alias': {u'full_name': u'field1', u'mapping': {u'field1': {u'fields': {u'keyword': {u'ignore_above': 256, u'type': u'keyword'}}, u'type': u'text'}}}, Field 2 - u'extra_fields_values': {u'full_name': u'field2', u'mapping': {u'field2': {u'fields': {u'keyword': {u'ignore_above': 256, u'type': u'keyword'}}, u'type': u'text'}}}}}}} Query For field2 - {'_source': 'field1', 'from': 0, 'query': {'bool': { 'must': [ {'term': {'field3.keyword':'Test1'}}, {'term': {'field4': 1741}}, {'query_string': { 'fields': ['field2.keyword'], 'query': '/.*test abc.*/', } } ], }}]}}, 'size': 50} For field1 - {'_source': 'field1', 'from': 0, 'query': {'bool': { 'must': [ {'term': {'field3.keyword':'Test1'}}, {'term': {'field4': 1741}}, {'query_string': { 'fields': ['field1.keyword'], 'query': '/.*test abc.*/', } } ], }}]}}, 'size': 50} Output for field1 - {u'hits': [{u'_id': u'1', u'_index': u'test', u'_score': 8.594198, u'_source': {u'alias': u'test abc'}, u'_type': u'test'}], u'max_score': 8.594198, u'total': 1} Output for field2 - {u'hits': [], u'max_score': None, u'total': 0} What could be possible reason for this behaviour? -
Filtering data in HTML datatables and Django
I added a Datatable to a page of my Django project. This tables shows some data retrieved from a Django Rest Framework endpoint. Here is how a sample of the data retrieved looks like: { "item": "Someitem", "Price": 120, "Status": "Free" }, { "item": "SecondItem, "Price": 90, "Status": "Taken" }, I want to filter these records so that only the ones with the Status set to Free are shown in the table, but i don't really know how to do that from Jquery. Here is the code i use to load the table: $(document).ready(function() { var table = $('#mydb').DataTable({ "serverSide": true, "ajax": "/myapi/?format=datatables", "columns": [ {data: "item", {data: "Price"}, ] }); setInterval( function () { table.ajax.reload(); }, 10000 ); }); I tried to add an if statement to check data.Pair inside the Ajax call, but it gave me an undefined. Is there any other way to do this? Any advice is appreciated -
How to post to a modelform with two foreign keys?
I am trying to make a ModelForm from witch I can insert data to my model, but the data never gets saved. I believe the problem occur because of my two foreign keys. When i insert data from the admin page, directly to the models it works, so the models themselves should work. However when i use my modelform the data never gets saved. I do however get the desired redirect with a POST /ac/ HTTP/1.1" 200 respons which means my form is valid - right? So no errors, the data just dosen't get saved. I hope one of you are able to help me with this strange problem. My models look like this: class KnittingNeedleType(models.Model): length = models.CharField(max_length=25) def __str__(self): return self.length class KnittingNeedleBrand(models.Model): brand_name = models.CharField(max_length=30) def __str__(self): return self.brand_name class KnittingNeedle(models.Model): width = models.FloatField() type = models.ForeignKey(KnittingNeedleType, on_delete=models.CASCADE) interchangeable = models.BooleanField() brand = models.ForeignKey(KnittingNeedleBrand, on_delete=models.CASCADE) class Meta: ordering = ('width', 'type',) My form: class KnittingNeedleForm(ModelForm): class Meta: model = KnittingNeedle fields = ['width', 'type', 'interchangeable', 'brand'] My view: @csrf_protect def register_needle(request): if request.method == 'POST': form = KnittingNeedleForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('ac:index')) form = KnittingNeedleForm() return render(request, 'ac/registerNeedle.html', {'form': form}) And my template: {% extends 'base.html' … -
How to make API calls in real time with Django?
I'm new in Django world, I'm developing a web application and I need to get data from an external API every time its data changes, I've been looking for different ways to do it, and I found WebSockets can help me, so now I want to try doing it with channels, but still do not understand how to do it, any help? -
Termina linea grapico araña realizada en plotly.graph_objects
Cuando genero mi gráfico no me termina la linea , sin embargo e intentado de muchas formas , pero nada me a funcionada. lo que esta en r , son unas variables que tengo declaradas con valores ya definidos fig = go.Figure() fig.add_trace(go.Scatterpolar( name = "Ideal", r=[ ideal_Funciones_Responsabilidades, ideal_etapas_propias, ideal_Aspectos_Legales, ideal_Gestion_Ambiental, ideal_Gestion_de_Seguridad, ideal_manejo_Informacion, hallado_Tecnicos, ideal_Humanos , ideal_transversales], theta=categories, #connectgaps=True, #line_color = 'darkviolet' type= 'scatterpolar', mode = 'lines', )) fig.add_trace(go.Scatterpolar( name = "Hallado", r=[ hallado_Funciones_Responsabilidades, hallado_etapas_propias, hallado_Aspectos_Legales, hallado_Gestion_Ambiental, hallado_Gestion_de_Seguridad, hallado_manejo_Informacion, hallado_Tecnicos, hallado_Humanos, hallado_transversales], theta=categories, #mode = "markers", type= 'scatterpolar', mode = 'lines', #line_color = 'peru' )) fig.update_layout( polar=dict( radialaxis=dict( #visible=True, range=[0, maximo_valor + 1] ) ), #line_close=True, # showlegend=False ) enter image description here estare atento a su ayuda con este tema. -
AttributeError: 'Product' object has no attribute 'filter'
I'm trying to access the link 'http://127.0.0.1:8000/products/2' in which I'm using a generic view(DetailsView) and in that view I want to use my custom model manager. But I'm getting the error which states AttributeError: 'Product' object has no attribute 'filter'. I'm using python version3.8 and django version 2.2.6 # ModelManager #----------------------------------------------- class ProductManager(models.Manager): def get_by_id(self,id): qs = self.get_queryset().filter(id=id) if qs.count() == 1: return qs.first() return None # View #----------------------------------------------- class ProductDetailView(DetailView): # queryset = Product.objects.all( ) def get_queryset(self, *args, **kwargs): request = self.request pk = self.kwargs.get("pk") instance = Product.objects.get_by_id(pk) if instance is None: raise Http404("Product Couldn't be found") return instance # Error Internal Server Error: /products/2 Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/detail.py", line 106, in get self.object = self.get_object() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/detail.py", line 36, in get_object queryset = queryset.filter(pk=pk) AttributeError: 'Product' object has no attribute 'filter' [22/Oct/2019 18:51:56] "GET /products/2 HTTP/1.1" 500 75133 -
How to iterate over nested lists in django templates
I am trying to iterate over nested lists in django templates. I am getting this error "Unclosed tag on line 213: 'for'. Looking for one of: empty, endfor.". I made sure that both loops are closed. Is it possible at all to do it? lists = [ [1,2,3,4], [2,3,2,5], [3,2,3,4,5,2] ] def xview(request): return render(request, 'xxxx.html', {'lists':lists}) #django template {% for i in lists %} {% for j in i%} ... {% endfor %} {% endfor %} -
For Loop to Find Matching Values and Total in Python
I have a Django project where my Manifests model consist of item codes and quantity. I want to loop through the model and find the total of quantity for each item code. So I have the following in my view: manifest = Manifests.objects.all() How could I use a for loop or something to total the quantity for each item code. Or more clearly, if item code 10 is there 3 times with quantities = 1, 2, and 3. Total should be 6 for item code 10, and if item code 20 is there twice with quantities = 2 and 5 total should be 7. Here is the model for reference: models.py class Manifests(models.Model): quantity = models.IntegerField() item_code = models.ForeignKey(Products, default=None, blank=True, null=True) -
Selectively setting AWS S3 bucket's Metadata to "Content-Disposition:attachment" in order to make images downloadable in browsers
In a web app of mine (developed via Django/Python framework), I serve images to users via an AWS S3 bucket. I now want to provide a "download image" button next to each image served on the website. I understand the best way to do that is to change the Metadata of the Properties of the S3 bucket to Content-Disposition:attachment (guide here: https://docs.easydigitaldownloads.com/article/1172-how-do-i-force-files-to-download-in-amazon-s3) However, if I do that, all images would default to the download behavior on my web app. I only want to impart this functionality via the download button. What's my best course of action given the circumstances? I.e. how do I configure the S3 bucket to respond in a way that enables the download button to actually work (while the rest of the web app's functionality remains the same). I can't seem to wrap my head around this - perhaps some web developers with expertise greater than mine can shed light on how they would have done this. Btw, I know about the download attribute of the <a> tag. It works nicely enough, but only if the domain/subdomain etc of the downloadable resource is the same. In my case, I'm using an S3 bucket to host my files … -
Slow EC2 Performance with Python Threading?
I'm using Python threading in a REST endpoint, so that the endpoint can launch a thread, and then immediately return a 200 OK to the client while the thread runs. (The client then polls server state to track progress of the thread). The code runs in 7 seconds on my local dev system, but takes 6 minutes on an AWS EC2 m5.large. Here's what the code looks like: import threading [.....] # USES THREADING # https://stackoverflow.com/a/1239108/364966 thr = threading.Thread(target=score, args=(myArgs1, myArgs2), kwargs={}) thr.start() # Will run "foo" thr.is_alive() # Will return whether function is running currently data = {'now creating test scores'} return Response(data, status=status.HTTP_200_OK) I turned off threading to test if that was the cause of the slowdown, like this: # USES THREADING # https://stackoverflow.com/a/1239108/364966 # thr = threading.Thread(target=score, args=(myArgs1, myArgs2), kwargs={}) # thr.start() # Will run "foo" # thr.is_alive() # Will return whether function is running currently # FOR DEBUGGING - SKIP THREADING TO SEE IF THAT'S WHAT'S SLOWING THINGS DOWN ON EC2 score(myArgs1, myArgs2) data = {'now creating test scores'} return Response(data, status=status.HTTP_200_OK) ...and it ran in 5 seconds on EC2. This proves that something about how I'm handling threads on EC2 is the cause of the … -
How do I filter a django queryset based on pairs of fields from another queryset?
I have a table that handles ordering of tasks, and each user can have a different order for the same task. This might be difficult to explain, so I have a discrete example at the bottom of this post. Object representing the order of tasks for each user: class TaskOrdering(models.Model): task = models.ForeignKey(Task, related_name='ordering') user = models.ForeignKey(User, related_name='task_ordering') order = models.PositiveIntegerField(null=True) When I delete a task, I need to decrement the order of all tasks in each user's view that have an order greater than the deleted task's order. However, this deleted task's order is different for each user since they have their own view of the task list. Right now I am doing: # Instance is a Task object def perform_destroy(self, instance): # deleted_task_ordering is a set of TaskOrdering objects # representing the order of the task in EACH user's view deleted_task_ordering = instance.ordering.all() # deleted_task_ordering is a set of TaskOrdering objects # representing the order of OTHER tasks in EACH user's view other_tasks_ordering = TaskOrdering.objects.exclude(task=instance) for o in deleted_task_ordering: need_decrement = other_tasks_ordering.filter(user=o.user, order__gt=o.order) need_decrement.update(order=F('order') - 1) This works, but there must be a more efficient way by using django queries instead of a for loop. The reason I … -
update django json array with one that is populated without droping other fields
Hello I am developing a django web app where I am sending data from frant end and I would like to up make sure that this form can be posted without errors in Django rest So my django rest expect some data like this dat = { 'age':"", 'gender':"", 'description':"", ...others } my front however is sending data that is incomplete coz I expect to allow user fill other details later raw_dat = { 'age':"20", 'gender':"male", } I was was wondering if i can append the data in the second array to the first one keeping all those other fields that the second array does not have, I will really appreciate any help I can get -
Authentiaction error for "Single sign on" in Django application
I am trying to add SSO to my Django application. When I do token= token.get_token('user','Password'), it calls get_token method which will call HTTPBasicAuth with my credentials, from requests.post. I don't understand where my password is getting changed(trimmed or some special character, might be '/0' getting added), because of which I am not able to validate my request. I can directly do curl with my credentials to the authentication site and can see curl request getting response, but if I change anything in my password I will get the same error what I am getting from SSO integrated in my application. How can I figure out, where my password getting messed up.