Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django mail app not working on cpanel
I hosted a django app on cPanel Trying to use Gmail to send an email but I keep getting Server Error (500) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'email' SERVER_EMAIL = 'email' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' I hosted it on pythonanywhere and its working fine -
How do i pass data from a django function to another function
I have this signup django app and its more like a signup page for a website. I have an issue now, i made a one to one database relationship between the users data and their web profile from django.db import models import datetime from django.utils import timezone class UserDetail(models.Model): SEX = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=60) middle_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) gender = models.CharField(max_length=1, choices=SEX) email = models.EmailField() def __str__(self): return '%s %s' % (self.first_name, self.last_name) class WebDetail(models.Model): user = models.OneToOneField(UserDetail, on_delete=models.CASCADE) username = models.CharField(max_length=60) password = models.CharField(max_length=60) # TODO: i need to search how to do auto_now_add function # time_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.username and here is my views.py from django.shortcuts import render from django.http import HttpResponse from .forms import UserDetailForm, WebDetailForm from .models import UserDetail, WebDetail from django.shortcuts import redirect, reverse def index(requests): form = UserDetailForm() if requests.method == "POST": form = UserDetailForm(requests.POST) if form.is_valid(): UserDetail.objects.create(**form.cleaned_data) # print(requests.POST['first_name']) # return HttpResponse('<h1>Hello</h1>') # return redirect('signup:web_detail_create') context = {'form': form} return render(requests, 'signup/index.html', context) def web_detail_create(requests): form = WebDetailForm() if requests.method == "POST": form = UserDetailForm(requests.POST) if form.is_valid(): # TODO: i need the function above to go with the users data and that … -
what is difference between success_url and get_success_url
class CustomLoginView(LoginView): template_name = 'task/login.html' fields = '__all__' redirect_authenticated_user = True success_url = reverse_lazy('tasks') # def get_success_url(self): # return reverse_lazy('tasks') In this case, I think success_url will work with no error, but there is error It worked well using get_success_url method but i don't know what is difference between them. Furthermore, I'd like to know how works method and attribute in Class. Thanks -
Where to store uploaded files in DRF
I have a simple (for now) full stack web application with DRF on the backend and React as frontend. I have various pages, one of them is user's profile. Any user can change their avatar, this is also handled on the backend. I do it by calling the backend API with a path to a file, it gets uploaded to a media directory and served from backend, so frontend can access it (apps work separately on 2 different ports). That's how it looks in most tutorials/articles on the internet. I actually made this feature just now and while I was happy and wanted to commit my changes I noticed that I have an additional change which is the uploaded avatar. Now the problem is, what do I do with that? Obviously, I cannot just add it to my repo, that would be stupid, right? And if I gitignore it, then the path like avatars/foo.jpg stays in my DB but I won't be able to serve it, because there will be no file. I wanted to ask what's the general solution (or in DRF) to this problem. First thing that comes to mind is storing the images in a separate database … -
Kubernetes share temporary storage to upload file async
Following this post and this, here's my situation: Users upload images to my backend, setup like so: LB -> Nginx Ingress Controller -> Django (Uwsgi). The image eventually will be uploaded to Object Storage. Therefore, Django will temporarily write the image to the disk, then delegate the upload task to a async service (DjangoQ), since the upload to Object Storage can be time consuming. Here's the catch: since my Django replicas and DjangoQ replicas are all separate pods, the file is not available in the DjangoQ pod. Like usual, the task queue is managed by a redis broker and any random DjangoQ pod may consume that task. I need a way to share the disk file created by Django with DjangoQ. The above mentioned post basically mention two solutions: -solution 1: NFS to mount the disk on all pods. It kind of seems like an overkill since the shared volume only stores the file for a few seconds until upload to Object Storage. -solution 2: the Django service should make the file available via an API, which DjangoQ would use to access the file from another pod. This seems nice but I have no idea how to proceed... should I … -
Django password reset token doesn't work after upgrade to v3.1?
I'm scratching my head on this one all day. I have a Wagtail site that was previously running on Django 2.2 that I'm in the process of upgrading to Django 3.1. I'm using the Django internal password reset token functions to generate unsubscribe links for marketing email being sent through Django. Since six was deprecated in 3.x versions of Django I've had to re-write my repurposing of the one-time login links a bit, and despite mimicking the behavior of Django internally the view simply doesn't work, despite working manually in the shell. The last bit is the kicker, if I input the values manually and step through my code in the shell, it seems to work. from django.shortcuts import render from django.contrib.auth import ( REDIRECT_FIELD_NAME, get_user_model, login as auth_login, logout as auth_logout, update_session_auth_hash, ) from django.utils.decorators import method_decorator from django.utils.http import urlsafe_base64_decode from django.core.exceptions import ValidationError from django.contrib.auth.tokens import default_token_generator from wagtailcache.cache import nocache_page UserModel = get_user_model() @nocache_page def unsubscribe(request, uidb64, token): breakpoint() INTERNAL_RESET_SESSION_TOKEN = '_password_reset_token' try: uid = urlsafe_base64_decode(uidb64).decode() user = UserModel.objects.get(email=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist, ValidationError): user = None if user is not None: session_token = request.session.get(INTERNAL_RESET_SESSION_TOKEN) token_generator = default_token_generator if token_generator.check_token(user, token): # If valid token, … -
Problem with getting data from database django
I am facing a big problem . I am using this query in order to get data from database : try : user = UserModel.objects.get(subject_dn=subject_dn,issuer_dn=issuer_dn) except Exception : raise exceptions.NotFound(' User corresponding to the entred Certificate is not found in the System') logger.info('this is the found user %s' %user) The problem that even i have the user in the database :I'm getting all the time user not found ... Can someone explain to me why this could happen ? Thank you -
django-simple-jwt auth on page reload
I'm using django simplejwt for auth for my react django app. I have it all set up but I'm trying to figure out how to authenticate the user on reload. So when they reload the page, I can check local storage for the refresh and access token, but I can't figure out how to make sure these tokens are valid. It seems that the only way is to make an actual api call to the backend (I'm not currently making an api call on page load). I can't seem to find a function in that library that checks that the tokens are valid. So I could just make a dummy endpoint that I hit on page load that will force an authentication, but I was wondering if there's a more proper way to do it. As of now, one could reload the page and access it if they have local storage variables with the correct keys but incorrect values (but obviously not access any data because no api calls have been made yet). -
The code does not work until after restarting the server
I have a problem with the form file I wrote a code, but it does not work properly until after restarting the server def PAYMENT_CHOICES(): check_pay=payment.objects.first() if check_pay.payment == '1': return (('COD', 'Cash on delivery'),) elif check_pay.payment == '2': return (('CARD', 'Credit card'),) elif check_pay.payment == '3': return (('COD', 'Cash on delivery'), ('CARD', 'Credit card')) class paymentForm(forms.Form): payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES()) and in template <div class="col-lg-12 col-md-12"> {% for value, name in form.fields.payment_option.choices %} <div class="agree-label"> <input type="radio" name="payment_option" id="{{ name }}" value="{{ value }}" required> <label for="{{ name }}"> {{ name }} </label> </div> {% endfor %} </div> -
Type object 'Model' has no attribute 'objects' - when it's clearly there..?
I'm getting this error when I try to create a new object via Book.objects.create(): AttributeError: type object 'Book' has no attribute 'objects' For this code: # models.py class BookManager(models.Manager): def get_queryset(self): return super(BookManager, self).get_queryset().filter(type="book") def create(self, **kwargs): return super(BookManager, self).create(**kwargs) class ChapterManager(models.Manager): def get_queryset(self): return super(ChapterManager, self).get_queryset().filter(type="chapter") def create(self, **kwargs): return super(ChapterManager, self).create(**kwargs) class Text(models.Model): type = models.CharField(max_length=255, blank=False) # for STI def __init__(self, *args, **kwargs): super(Text, self).__init__(*args, **kwargs) # If we don't have a subclass at all, then we need the type attribute to match # our current class. if not self.__class__.__subclasses__(): self.type = self.__class__.__name__.lower() else: subclass = [ x for x in self.__class__.__subclasses__() if x.__name__.lower() == self.type ] if subclass: self.__class__ = subclass[0] else: self.type = self.__class__.__name__.lower() class Chapter(Text): objects = ChapterManager() class Meta: proxy = True class Book(Text): objects = BookManager() class Meta: proxy = True Where you can see the Chapter and Book objects clearly have an objects field pointing to the custom manager... For some more context, I'm using single table inheritance for my models. This exact same code works fine for another project I have so I have no clue what's happening. -
cant redirect to success page in django paypal
i have a Django Store Website which use Paypal for payment but in my views.py,Django do everything except go to the directed page that i choose this is my views.py def capture(request,id): do some stuff return redirect(reverse("shop:success")) <script type="text/javascript"> function completeOrder(){ var url = "{% url 'shop:paypal' id=orders.id %}" fetch(url, { method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify("{{orders.id}}") }) } // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { layout: 'horizontal', color:"blue", label:"checkout", tagline:"false", shape:"pill", size:"small", }, // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '{{orders.converter}}' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer completeOrder() alert('Transaction completed by ' + details.payer.name.given_name + '!'); }); } }).render('#paypal-button-container'); -
my PostgreSQL docker image database doesn't exist on Django
I am doing a django API with docker and postgresql, i set up a docker compose file to use a db network which is a postgresql image and an app network which is my django app. I don't know what is happening (i followed a tutorial) but my configuration isn't working, it give me an error on django that the database doesn't exist. Here is the files: docker-compose.yml version: "3" services: app: build: context: . ports: - "8000:8000" volumes: # Any change made on the project will be reflected on the container - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=recipe - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=recipe - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword Dockerfile FROM python:3.7-alpine LABEL maintainer="trolliama" # Recommended - Don't Allow the python buffer the outputs ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt # Dependencies to run postgresql # apk it's the packege install of alpine like: apt # apk add == apt install RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del … -
Getting data from Django models to Google Charts
I'm trying to displays charts of the most sold items in the store. So I would need to take information from the database and into the html. The charts don't seem to load. When I tried static data (the examples from Google), it works fine. However, I cannot seem to do it with dynamic data. I converted the array into a json and did the |safe in the html for escaping. Yet still it doesn't appear. If anyone has an tips on how to fix it, please help! Below is my views.py where I call the html file that has the script of charts. def charts(request): data_arr = [] for item in Item.objects.all(): data_arr.append([item.ItemName, item.quantity_sold]) return render(request,'coffeeapp/charts.html',{'item':json.dumps(data_arr)}) Here is my code in the charts.html file <script src="https://www.gstatic.com/charts/loader.js"></script> <script> google.charts.load('current', { packages: ['corechart'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { // Define the chart to be drawn. var data = google.visualization.arrayToDataTable( ['Item', 'Quantity Sold'], [{{item|safe}}] ); // Instantiate and draw the chart. var chart = new google.visualization.PieChart(document.getElementById('myPieChart')); chart.draw(data, null); } </script> <!--Div that will hold the pie chart--> <div id="myPieChart"/> -
Whenever I use send_mail in django it sends me emails from myself rather than the address I'm providing
So I've been working on this blog website and I wanted to add a form so that users can contact the blog admin. However when they fill out the form and send email.. The email I receive is from myself and not from the user. Someone Please help me to fix it. The form is working correctly and message-email does return the email that they enter. e.g. lets say in my form I add a user email as example1@example.com but when I recieve an email it's not coming from example1@example.com but from my host email myemail@gmail.com. views.py: def contact(request): if request.method == 'POST': message_name = request.POST['message-name'] message_email = request.POST['message-email'] message = request.POST['message'] #send mail send_mail( 'message from ' + message_name + ' their email ' + message_email , message, message_email, ['myemail@gmail.com'], ) return render(request, 'blog/contact.html', {'message_name':message_name}) settings.py: EMAIL_HOST = 'smtp.gmail.com' EMAIL_POST = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = '******' EMAIL_USE_TLS = True -
Couldn't trace back NoReverseMatch Error: Reverse for 'update' with arguments '('',)' not found
I am once again facing an error that is related to NoReverseMatch. Still, I couldn't find the source. Here is my code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:aufgabenzettel_id>", views.details, name="details"), path("add/", views.add, name="add"), path("delete/<int:aufgabenzettel_id>", views.delete, name="delete"), path("edit/<int:aufgabenzettel_id>", views.edit, name="edit"), path("update/<int:aufgabenzettel_id>", views.update, name="update") ] models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) def __str__(self): return f"{self.Aufgabeselbst}" views.py from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import Aufgabenzettel # Create your views here. def index(request): return render(request, "aufgabenzettel/index.html", { "Aufgabenliste":Aufgabenzettel.objects.all() }) def details(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/details.html", { "details":aufgabenzettel }) def add(request): if request.method == "POST": Aufgabe = request.POST["Hinzufügen"] Aufgabenzettel.objects.create(Aufgabeselbst=Aufgabe) return HttpResponseRedirect(reverse("index")) return render(request, "aufgabenzettel/add.html") def delete(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) aufgabenzettel.delete() return HttpResponseRedirect(reverse("index")) def edit(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/edit.html", { "details":aufgabenzettel }) def update(request): if request.method == "post": Aufgabejetzt = request.POST["Bearbeiten"] Aufgabejetzt.save() return HttpResponseRedirect(reverse("index")) return render(request, "aufgabenzettel/edit.html") index.html {% extends "aufgabenzettel/layout.html" %} {% block body %} <h1>Meine Aufgaben</h1> <ol> {% for Aufgabeselbst in Aufgabenliste %} <li> <a href="{% url 'details' Aufgabeselbst.id %}"> {{ Aufgabeselbst }} </a> <form action="{% url 'delete' Aufgabeselbst.id %}" … -
How can I debug get()keywords must e strings?
Based on this, I have a django-import-export resource that I use to upload books into my model. I am not able to upload when I set import-id_fields = ('id',). However, when I set it to import-id_fields = ('reg_no,), it works. My aim is to be able to upload a number of books whose details are similar in most cases, reg_no may be the same.... What I realized before was that when I uploaded with import-id_fields = ('reg_no",), all the books of reg_no same for a particular user were visible in the other users profile,which should not be the case. class Books(models.Model): school = models.ForeignKey(School, on_delete=models.CASCADE) reg_no = models.CharField(max_length=100) book_name = models.CharField(max_length=200) The resource class ImportBooksResource(resources.ModelResource): def __init__(self, school_id,*args,**kwargs): super().__init__() self.school_id = school_id self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Books,'id')) self.fields['department'] = fields.Field(widget=ForeignKeyWidget(Departments, 'name')) def before_save_instance(self, instance, using_transactions, dry_run): instance.school_id = self.school_id def before_import_row(self, row, **kwargs): row['department'] = row['department'].lower() class Meta: model = Books fields = ('reg_no','book_name','book_detail','department') import_id_fields = ('id',) import_order = ('reg_no','book_name','book_detail','department') The view. class uploadBooks(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadBooksForm() self.context['form'] = form return render(request,'libman/upload_books.html',self.context) def post(self, request): school_id = request.user.school.id#Gets the currently logged in user form = UploadBooksForm(request.POST , request.FILES) data_set = Dataset(school = request.user.school) if form.is_valid(): file = … -
How to use OR condition for icontains in multiple fields with graphene-django
I have the following model in Django: class JobPost(models.Model): company = models.CharField(blank=True, max_length=30, null=True) job = models.CharField(blank=True, max_length=30, null=True) category = models.CharField(blank=True, max_length=30, null=True) description = models.TextField(blank=True, max_length=500, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.job And I have the following schema with graphene: class JobPostNode(DjangoObjectType): class Meta: # Assume you have an Animal model defined with the following fields model = JobPost filter_fields = { 'company': ['exact', 'icontains', 'istartswith'], 'job': ['exact', 'icontains', 'istartswith'], 'category': ['exact', 'icontains', 'istartswith'], "description": ['exact', 'icontains', 'istartswith'], } interfaces = (relay.Node,) class Query(graphene.ObjectType): job = relay.Node.Field(JobPostNode) all_jobs = DjangoFilterConnectionField(JobPostNode) schema = graphene.Schema(query=Query) I want to use icontains whereas I will get data based on an OR not on AND; for example the following query: { allJobs(job_Icontains: "t", company_Icontains: "v") { edges { node { company job } } } } Should return data that has the letter "t" in job OR the letter "v" in company, not the letter "t" in job AND the letter "v" in company. How can I do that? -
ValueError: Unable to configure handler 'django_file'
I found a Django project and failed to get it running in Docker container in the following way: git clone git clone https://github.com/NAL-i5K/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: dbik: image: postgres volumes: - ./data/dbik:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres ports: - 5432:5432 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - dbik links: - dbik $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Next, I ran docker-compose up --build Starting djangoblast_dbik_1 ... Starting djangoblast_dbik_1 ... done Recreating djangoblast_web_1 ... Recreating djangoblast_web_1 ... done Attaching to djangoblast_dbik_1, djangoblast_web_1 dbik_1 | dbik_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization dbik_1 | dbik_1 | 2021-05-21 21:05:18.976 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by … -
"could not connect to server: No such file or directory" Django deploy to Heroku Error
Im facing this problem when i tried to deploy Django Rest Framework App to Heroku: Exception Type: OperationalError at / Exception Value: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? This Error is from Heroku, i have a .travis.yml to check errors before deploying on github, and every test went well. The deploy Building on Heroku went well, so this error is coming from the Django Debugger on Heroku App. This is my Procfile web: gunicorn wardogs.wsgi --log-file - I dont know what i have to show you becouse the error is not coming from any local directories. I read on this question that i should execute this command: heroku addons:create heroku-postgresql but the error persist. What should i do? -
Web-App framework suggestions for my CPP backend [closed]
i have a substantial piece of code written in CPP which serves as operator for IOT machines, communicates with the DB and provides REST/Websocket. Now i need a good framework to write the Web-App-Frontend. My initial thought was to use Django. The problem is that Django can not connect to the websocket, it can only provide it own, but that does not work since the Backend server does not know where the frontend clients are. It needs to be able to regularly collect the data from the backend and send commands to the same. cheers Robert -
(1366, "Incorrect string value: '\\xD9\\x86\\xDB\\x8C\\xD9\\x85...' for column '<column_name>' at row <row_number>") Django
Im trying to connect Django project to mysql in my host, when I want to install mysqlclient using pip install mysqlclient I got an error that mysqlclinet cant be install on this host, so I install pymysql and use import pymysql pymysql.install_as_MySQLdb() in init.py file in project folder where settings.py is. also I use DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME'), 'USER': config('USER'), 'PASSWORD': config('DB_PASSWORD'), 'OPTIONS': { 'charset': 'utf8mb4', 'use_unicode' : True, }, }, } Now when I want to run ./manage.py migrate some migrations has been applied but some migrations got an error to me that django.db.utils.DataError: (1366, "Incorrect string value: '\\xD8\\xAA\\xD9\\x86\\xD8\\xB8...' for column 'name' at row 5") As I said some migrations has been applied like as USERs so when I want to save Persian Characters as user first_name or in other columns I got same error that seys (1366, "Incorrect string value: '\\xD9\\x86\\xDB\\x8C\\xD9\\x85...' for column 'first_name' at row 1") so how to fix this problem?! PS: I dont have access to all terminall command like as apt and same things... Python 3.7 Django 3.2 pip 21.1.1 PyMySQL 1.0.2 -
How to send updates to client without polling?
Basically imagine you have a twitter feed and you want to notify the user when new tweets have been made. You could implement this with polling but it would be inefficient, you'd want it to be event driven, so that when a new tweet is made an update is pushed to the frontend. Part of the answer is to use websockets. But the other part I don't know is how the server knows to send an update when there's a new tweet in the database without constantly polling/querying the database to check if there's been a new tweet. It seems inefficient and that there's a better way. Someway to tie a database change to an event listener and send the response to the client. Any help would be greatly appreciated -
Why django-admin startproject creates nested project folders?
django-admin startproject mysite creates something like this: /mysite /mysite settings.py .... I know if I add a period at the end of command (django-admin startproject mysite .) the second folder will not be created, but I don't understand what is the rationale behind creating nested project folders. Maybe I'm missing something critical? -
Python/Django: How to create a loop to identify all related objects
I have two models as follows: class User(AbstractUser): def related_users(self): """Returns list related users if any. Else returns False.""" users1 = RelatedUser.objects.filter(user1=self) if not users1: return False related_users1 = [] for related_user in users1: related_users1.append(related_user.user2) users2 = RelatedUser.objects.filter(user2=self) if not users2: return False related_users2 = [] for related_user in users2: related_users2.append(related_user.user1) related_users = list(set(related_users1 + related_users2)) if self in related_users: related_users.remove(self) return related_users class RelatedUser(models.Model): """Identifies which users are related.""" user1 = models.ForeignKey("User", on_delete=models.CASCADE, related_name="related_users_1") user2 = models.ForeignKey("User", on_delete=models.CASCADE, related_name="related_users_2") Consider the following RelatedUser objects: user1 = a, user2 = b user1 = a, user2 = c user1 = d, user2 = b Now say I execute a.related_users() This returns a list [b, c] However we can see that all of the RelatedUser objects are related indirectly. How do I modify related_users() to incorporate this? So that the list, in the above case, is [b, c, d] I have been unable to come up with a recursive or other function to do this. -
Replace ajax json for python json in Django
I'm trying change Ajax json url to python variable with a json in Django. As you can see the url in both cases are the same so I can't understand what is going on. Thanks in advance. What I'm looking for and does not work <script> $(document).ready(function() { var table = $('#users').DataTable({ "ajax": "{{ es_docs }}", my view: @login_required(login_url="/login/") def index(request): context = {} context['segment'] = 'index' html_template = loader.get_template( 'index.html' ) resp = requests.get("https://gyrocode.github.io/files/jquery-datatables/arrays_id.json").json() context['es_docs'] = resp return HttpResponse(html_template.render(context, request)) Template.html: <script> $(document).ready(function() { var table = $('#users').DataTable({ "ajax": "https://gyrocode.github.io/files/jquery-datatables/arrays_id.json", 'columnDefs': [ { 'targets': 0, 'checkboxes': { 'selectRow': true } } ], 'select': { 'style': 'multi' }, 'order': [[1, 'asc']] });