Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webpack 3.1 Issues with Semantic UI imports
After migration to newer version of Webpack (from <2 to 3.1.0) I have a problem with Semantic UI imports. Consider following template structure: There is root template: <head> {% render_bundle 'global' 'css' %} {% block stylesheets %}{% endblock %} {% render_bundle 'global' 'js' %} {% block header_javascripts %}{% endblock %} </head> and there is second level template: {% extends "core/_global.html" %} {% load render_bundle from webpack_loader %} {% block stylesheets %} {% render_bundle 'accounts/register' 'css' %} {% endblock %} {% block javascripts %} {% render_bundle 'accounts/register' 'js' %} {% endblock %} Previously I had required Semanic UI imports in global.js: global.js (old) import '../semantic/dist/components/modal.min.css' import '../semantic/dist/components/modal.min.js' ... import '../styles/global.scss' $(document).ready(function() { }); With such structure I had access to required Semantic UI components from withing register.js. For instance I could call modal inside register.js: register.js (old) $(function() { init_modal(); function init_modal() { $("#terms_modal_link").click(function() { $('#terms_modal').modal('show'); }) } }) After switching to newer Webpack components imported in global.js are not visible inside register.js. I have to explicitly import required components inside register.js in following way: register.js (new) import '../../semantic/dist/components/modal.min.css' import '../../semantic/dist/components/modal.min.js' $(function() { init_modal(); function init_modal() { $("#terms_modal_link").click(function() { $('#terms_modal').modal('show'); }) } }); The change seems to be not so critical, … -
A page's urls are not worked properly
A page's urls are not worked properly.I made common header's html(header.html). I wrote in it {% load static%} <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="{% static 'header.css' %}"> <header class="clearfix"> <h1 class="title">WEB SITE</h1> <ul class="top-menu"> <li class="top-menu-item"><a class="icon_head" href="send">SEND</a></li> <li class="top-menu-item"><a class="icon_head" href="see">SEE</a></li> <li class="top-menu-item"><a class="icon_head" href="know">KNOW</a></li> </ul> <a class="logout_button" href="logout_view">LOGOUT</a> </header> In index.html,header.html is read like <html lang="ja"> <head> <meta charset="UTF-8"> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="/static/accounts/detail.css"> <link rel="stylesheet" href="/static/bootflat/css/bootflat.min.css"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <title>WEB SITE</title> </head> <body class="relative"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="/static/accounts/header.css"> {% load static%} <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="{% static 'header.css' %}"> <header class="clearfix"> <h1 class="title">WEB SITE</h1> <ul class="top-menu"> <li class="top-menu-item"><a class="icon_head" href="send">SEND</a></li> <li class="top-menu-item"><a class="icon_head" href="see">SEE</a></li> <li class="top-menu-item"><a class="icon_head" href="know">KNOW</a></li> </ul> <a class="logout_button" href="logout_view">LOGOUT</a> </header> <main> <div class="container"> <p>Hello World</p> </div> </main> <footer> <div class="footers"> <ul class="bottom-menu"> <li class="bottom-menu-item"><a class="bottom_index" href="">XOXO</a></li> </ul> </div> </footer> </body> </html> When I put header's SEND&SEE&KNOW links,they worked properly. On the other hand,I wrote in detail.html like <html lang="ja"> <head> <meta charset="UTF-8"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootflat/2.0.4/css/bootflat.min.css"> <link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootflat/2.0.4/js/jquery.fs.selecter.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootflat/2.0.4/js/jquery.fs.stepper.min.js"></script> <title>WEB SITE</title> <body class="relative"> <header class="clearfix"> <h1 class="title">WEB SITE</h1> <ul class="top-menu"> <li class="top-menu-item"><i class="fa … -
Issues with pre-signed Image urls in S3
I am uploading files to AWs S3, Everything is working fine, images are getting upload and in return I am getting a pre-signed url But when I am trying to access that image I am getting below error. PermanentRedirectThe bucket you are attempting to access must be addressed using the specified endpoint. I can solve this issue by using AWS_S3_CUSTOM_DOMAIN but then pre-signed url will not be genertaed. The main aim is to genertae pre-signed urls. My settings are as follows: AWS_STORAGE_BUCKET_NAME = '********' AWS_ACCESS_KEY_ID = '****************' AWS_SECRET_ACCESS_KEY = '***************' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' DEFAULT_FILE_STORAGE = '******.PrivateMediaStorage' AWS_DEFAULT_ACL = 'private' AWS_QUERYSTRING_AUTH = True AWS_S3_ENCRYPTION = True S3_USE_SIGV4 = True AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } PrivateMediaStorage : class PrivateMediaStorage(S3Boto3Storage): location = getattr(settings, 'AWS_PRIVATE_MEDIA_LOCATION', 'media/private') default_acl = 'private' file_overwrite = False custom_domain = False -
django get user's client list tree from database
I had asked a question few days ago that is (django reverse lookup query within three tables). That answer helped me so much but I want implement something more. So is it possible to make a query that fetch all clints in my tree. here we are fetching clients that are created by me only. For example here I'm a reseller and I make clients which can be resellers and end clients also. So now I want fetch all clients that are in my tree. -
how to attach variable inside a dictonary in django application
{% with alertnames as name %} {{name}} I have data in this variable {{name}} and now If I want to attach in a dictionary as "Dictonary.name" and display it.How can I do that? -
Categories in wagtail not resolving
This is kind of a long shot, but will be glad if I can get help at this point, this is the only thing stopping me from completing this project. P.S been at it for 2 days. Can someone please point out what I am doing wrong here? as I keep getting can't resolve Keyword categories into Field Error. The exception thrown on this line services = services.filter(categories__category__name=category) However, looking through the code, one would see that there is a relationship between service_categories field and ServiceCategory through ServiceCategoryServicePage which has a related name of 'categories. So I was thinking that shouldn't throw an exception error of Cannot resolve field. Any help at this point will be extremely appreciated. def get_service_context(context): context['all_categories'] = ServiceCategory.objects.all() context['root_categories'] = ServiceCategory.objects.filter( parent=None, ).prefetch_related( 'children', ).annotate( service_count=Count('servicepage'), ) return context class ServiceIndexPage(Page): header_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) heading = models.CharField(max_length=500, null=True, blank=True) sub_heading = models.CharField(max_length=500, null=True, blank=True) body = RichTextField(null=True, blank=True) def get_context(self, request, category=None, *args, **kwargs): context = super(ServiceIndexPage, self).get_context(request, *args, **kwargs) services = self.get_children().live().order_by('-first_published_at') #.prefetch_related('categories', 'categories__category') if category is None: if request.GET.get('category'): category = get_object_or_404(ServiceCategory, slug=request.GET.get('category')) if category: if not request.GET.get('category'): category = get_object_or_404(ServiceCategory, slug=category) services = services.filter(categories__category__name=category) # Pagination … -
Best aproach in limiting django model entries
I have a model Events that has a ForeignKey to Users. What will be the best approach to limit users to post only one event. In the models, in the view or both? I've set a variable in settings.py because at some point the users will be able to increase their "quota" of events so a OneToOneField isn't an option. -
publish 5 words from model title django [duplicate]
This question already has an answer here: how to show first 50 words of a text field in django template 1 answer I have a model : class publish(models.Model): publish_time=models.DateTimeField(auto_now_add=True) owner=models.ForeignKey(User, on_delete=models.CASCADE) Publish_Your_Story=models.TextField() def __str__(self): return '{}'.format(self.Publish_Your_Story) I have views.py : class Index(ListView): model=publish Template: <h1>Articles</h1> <ul> {% for article in object_list %} <li>{{ article }}</li> {% empty %} <li>No articles yet.</li> {% endfor %} </ul> Now i want to publish only 10 words from Publish_Your_Story row from models as article in Template . Kindly help . -
What is better performance between ManyToMany and a model with two forigen keys?
The case is I have a model User which is the teacher and student and I differ between them using a flag type, Now Teachers may have many students and vice versa so.. Which is better as a performance Case 1: class UserAccount(AbstractUser): type = models.PositiveSmallIntegerField(choices=TYPES, default=1) grp = models.ManyToMany("self",blank=True) Case 2: class UserAccount(AbstractUser): type = models.PositiveSmallIntegerField(choices=TYPES, default=1) class Group(models.Model): teacher = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students') student = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='teachers') For sure I can handle this based on the type in the form.. etc, but Now I can't determine which is better as a performance and code modularity -
Error while reading csv file in pandas
I am reading a CSV file whose name I have stored in Django session in function1 in views.py : request.session['filename'] = csvfilenamenew Here csvfilenamenew is the name of the CSV file.When I try to read this file using pandas in function2 in views.py, csvname = request.session['filename'] df = pd.read_csv(csvname) I get the KeyError error.I have also tried the following for retrieving the filename from Django session: csvname = request.session.get('filename', None) In this case, I get ValueError at /userlog/ Invalid file path or buffer object type: What am I doing wrong? -
Django - remove primary_key=True from an existing model?
I have a table that I've already migrated into the MySQL database and one of the fields has primary_key = True. I realized this needs to be different and I need to remove the primary_key = True. I'd like Django to create its own auto incrementing primary key fields (like it does with all models if you don't specify a primary_key). If I simply remove the primary_key = True, Django complains because it can't auto-assign an auto-increment value to its new id field (which is now the primary key field). What's the best way to change this one field to not have primary_key = True? This particular model doesn't have any records yet in the database, so I think I'm in a better position than if I had records in there. I'm not sure if I should just drop the table and migrate as if it's a brand new table or if I need to take some other approach? -
Webpack 3.1. jQuery is added multiple times
After migration to Webpack 3, I have noticed that jQuery inclusion works not as I expected. My template structure has core/_global.html root template in which I render common js and css assets like: <head> {% render_bundle 'global' 'css' %} {% block stylesheets %}{% endblock %} {% render_bundle 'global' 'js' %} {% block header_javascripts %}{% endblock %} </head> Second level templates extend the root template and add additional js and css to html: {% extends "core/_global.html" %} {% load render_bundle from webpack_loader %} {% block stylesheets %} {% render_bundle 'accounts/register' 'css' %} {% endblock %} {% block javascripts %} {% render_bundle 'accounts/register' 'js' %} {% endblock %} In previous verions of Webpack at the beginning of global.js I had: import 'expose?jQuery!expose?$!jquery' After removing this line and changing webpack.config to: plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", }), I have following problem - each of the rendered files, global.js and register.js contain jQuery. As result the size of each file is increased by appr. 300 kb. I expect jQuery should be loaded only once and it should be accessible both in global.js and register.js Are there any workarounds which allow to include jQuery in such way and have access to it … -
How best would I keep track of frontend version in a Django app?
I currently deploy frontend and backend together, but I'd like to split them into two independently deployable components. For the backend I use Django. What I'd like to know is how best to manage versioning from Django. For example, I have just pushed a new frontend deploy, which means I now have a new bundle-{VERSION}.js sitting in S3, where {VERSION} is the commit-hash. I now need to update Django to serve new pages so that {VERSION} is correctly sent down with templates. What's the best way to store a global variable like this, in such a way that it can be updated easily? I don't want to add a database hit to every pageload, so storing in the database is not ideal. I could save it to a file, but that's not great either. In order to use settings.py, I'd have to restart the server process every time I deploy the frontend, which is not ideal. Is there a way of storing the version so that it's stored in memory in the server process, but it can be updated easily? -
Django-IIS - FastCGI exited unexpectedly
I am encountering this FastCGI exited unexpectedly and I do not know how to resolve this error. I have looked around stackoverflow for solutions but the either the suggested solutions don't apply or no answers provided to the question. I want to run very basic django website (in fact I just created it) using IIS server with WFastCGI. Here is my spec: IIS 10.0 Windows Server 2016 Django 1.11.4. Python 3.6.2 wfastcgi 3.0.0 My python installation is in C drive. I am creating a virtualenv in D drive and pointing path to virtualenv's Python when configuring. When I point to virtualenv's Python, this error 'FastCGI process exited unexpectedly'. If I point my path to C's python, this error disappears (There is another python cant find module error but I can resolve that). I do not know the reason for this fastcgi exited issue when I use virtualenv's python. Kindly enlighten me if possible. Here is the detailed error info: Module FastCgiModule Notification ExecuteRequestHandler Handler djangohandler Error Code 0xc0000135 Requested URL http://localhost:8089/ Physical Path D:\inetpub\django\foo Logon Method Anonymous Logon User Anonymous -
Django REST Framework - OneToOne Relation through JSON
I want to create an API that allows to send JSON through a POST request. The JSON should then get passed on to a serializer which takes care of creating a new object and populate it with the existing data. It works fine for the 'simple' cases such as basic character-only inputs like usernames and alike, but I am seriously stuck when it comes to creating a OneToOne relation. Here's the sample code. Function called employee_list in views.py - data['account'] is a valid username, a User instance is successfully being selected! data = JSONParser().parse(request) user_object = User.objects.get(username=data['account']) data['account'] = user_object # this is now a valid User object serializer = EmployeeSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) The model class Employee(models.Model) id = models.AutoField(primary_key=True) name = models.CharField(...) surname = models.CharField... account = models.OneToOneField(User) role = ... salary = ... picture = ... And the serializer class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = (...) # all fields of the `Employee` model So far so good, however, the serializer never validates! When I remove the need for a OneToOne relation, it works.. How can I create a new Employee objects with a working OneToOne relationship to a … -
CSRF token issue using dynamic login
I have have been looking in previous answers on Stack but nothing seems to apply to my app issue I am getting a CSRF issue Forbidden (CSRF token missing or incorrect.): /registration/auth_HRlogin/ It worked perfect until I modified my views.py in order to reverse to different page in function of the kind of user that login .. if he is HR or Employee or Candidate def HR_login(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = MyUser.objects.filter(email=email) if user: user=user[0] if user.is_active & user.is_hr & user.check_password(password): login(request,user) return HttpResponseRedirect(reverse('website:hr_index')) elif user.is_active & user.is_employee & user.check_password(password): login(request,user) return HttpResponseRedirect(reverse('website:employee_index')) elif user.is_active & user.is_candidate & user.check_password(password): login(request,user) return HttpResponseRedirect(reverse('website:candidate_index')) else: HttpResponse("Account not active, please contact Admin") else: print("Someone tried to login and failed") return HttpResponse("Invalid login detailed supplied!") else: return render(request,'HR_login.html',{}) No need to mention that I do have the CSRF token in my form and in my setting.py ;) Any Idea ? -
I am new to django and want to use a google api? How should I proceed?
I want to use the google classroom api but I am facing difficulty in getting started... any suggestions? -
Pick up multiple variables with get_context_data Django
I have a question about CBV Django process and get_context_data(). I would like to get some different variables and I don't overcome to do it with my function. This is the function : class IdentitySocietePDFCreatingView(LoginRequiredMixin, TemplateView) : template_name = 'Identity_Societe_PDF.html' model = Societe def get_context_data(self, **kwargs) : SID = Logger.login(lib.Global_variables.GED_LOG_USER, lib.Global_variables.GED_LOG_MDP) context_data = super(IdentitySocietePDFCreatingView, self).get_context_data(**kwargs) id = self.kwargs['id'] societe = get_object_or_404(Societe, pk=id) obj = Societe.objects.filter (Nom=societe.Nom, SIRET=societe.SIRET, SIREN=societe.SIREN, Ville=societe.Ville) if obj: sc_obj = obj[0] ''' Rest of my script '''' ''' I have a variable named folderID which must be in my template '''' context_data['queryset'] = obj return context_data My question is : How I can add folderID variable inside context_data ? I have to display in my template obj and folderID but I don't overcome to add both variable in context_data. -
How to check if the value of a field has been deleted in Python/ Django
i'm trying to check if a value of field has been deleted and then return False or return true if all the fields contain values. My code actually doesn't check the value in the fields but just check if the fields exists, how to heck the values of every specific fields? This is my models and in my views i have to check the function. class CompanyDirector(models.Model): username = models.CharField(max_length=128, blank=True, null=True) directorTitle = models.CharField(max_length=8, blank=True, null=True) directorName = models.CharField(max_length=64, blank=True, null=True) directorSurname = models.CharField(max_length=64, blank=True, null=True) directorId = models.CharField(max_length=16, blank=True, null=True) proffessionStartDate = models.DateTimeField(blank=True, null=True) ret = {'complete': False} try: company_director = CompanyDirector.objects.filter(company__token=token).first() if company_director: ret['complete'] = True for field in company_director._meta.get_all_field_names(): if not getattr(company_director, field): ret['complete'] = False break; except ValueError as e: print (e) return Response(ret) -
Django serialization: AttributeError when attempting to get a value for field on serializer
I am getting the following error, AttributeError: Got AttributeError when attempting to get a value for field devicedetails on serializer DISerializer. The serializer field might be named incorrectly and not match any attribute or key on the Device instance. Original exception text was: 'Device' object has no attribute 'devicedetails'. My models.py :- class DeviceInfo(models.Model): vendor = models.CharField(max_length=250) device_type = models.CharField(max_length=250) modelname = models.CharField(max_length=100) class Device(models.Model): name = models.CharField(max_length=100, primary_key=True) username = models.TextField() password = EncryptedTextField() deviceinfo = models.ForeignKey(DeviceInfo, null=True) class DeviceDetails(models.Model): device = models.ForeignKey(Device) serial_number = models.CharField(max_length=100) version = models.CharField(max_length=100) serializer.py :- class DeviceInfoSerializer(serializers.ModelSerializer): class Meta: model = DeviceInfo fields = ("id", "vendor", "device_type", "modelname") class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ("name","username", "password", "deviceinfo") class DeviceDetailsSerializer(serializers.ModelSerializer): class Meta: model = DevieceDetails fields = ("device", "serial_number", "version") class DISerializer(serializers.ModelSerializer): deviceinfo = DeviceInfoSerializer(read_only=True) devicedetails = DeviceDetailsSerializer(many=True) class Meta: model = Device fields = ("name", "username", "password", "deviceinfo", "devicedetails") views.py :- def list(self, request): list = Device.objects.all() serializer = DISerializer(list, many=True) -
Checksums are calculated after the form validation: how to notify the users of an error
Django 1.11.6 I'm developing a document archive. So, I calculate checksums to control that documents are still present, that they are not corrupt etc. Another side of this is that I can control whether a file has already been uploaded. It is important: no need to duplicate the files. I upload files through Django admin. There is a form prepared. But the problem is: form validators seems to be not very useful here. At least I can't invent how to use a form validator here. But post_save signal are useful: here we have a file already uploaded. We calculate the checksum of the file (using md5). But if unique=True for the checksum, IntegrityError is risen. It is Ok and predictable. But could you help me understand how to notify the user about this? Any method would suffice. It is just for our staff: no need to organize a brilliant html layout. But what is important is to show that the uploaded file coincides with an existing file with the following id. Could you help me with this? models.py class FileChecksum(models.Model): checksum = models.CharField(blank=True, null=False, unique=True, max_length=255, verbose_name=_("checksum")) def __str__(self): return self.checksum class Image(models.Model): file = models.ImageField(blank=False, verbose_name=_("Image"), max_length=255, upload_to=get_sheet_path) file_checksum … -
Loading fixtures in both public and test schemas with Django-tenant-schemas
I am trying to move tests written for a single tenant approach to a multi tenant approach (Django + Django REST Framework + django-tenant-schemas). I am wondering how the fixtures are handled using the FastTenantTestCase and rest_framework.test.APITestCase (inheriting from django TestCase). Indeed, it is loading all the fixtures in the public schema of the test DB but nothing is loaded in the test schema, thus leading all the tests to fail because nothing is present in the database. Did I miss something in the documentation or is it a missing feature ? Does anyone manage -
Django: Queries and calculations inside CreateView
I am relatively new to Django, so I am not sure is what I am asking possible to do. I am building a website with funcionality to rate users and write reviews about them. I have model for users (that has average rating field) and model for reviews (with fields of author, user_profile, grade and review. I am using CreateView for making reviews. I am trying to do the following: To make query to get all previous grades of that person (from Reviews model). Make calculations (sum all previous grades, add the new one and all that divide by number of grades(including new grade) Save new average grade to UserProfile model Save review to Review model Redirect user to current detail view Models.py class UserProfile(models.Model): ... avg_grade = models.FloatField(blank=True, null=True) ... class Reviews(models.Model): user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) grade = models.PositiveIntegerField() review = models.CharField(max_length=256, null=True, blank=True) author = models.CharField(max_length=256) In views.py I managed to make query of grades of that user, but not sure where to do calculations for new average grade(if this is possible inside Class-Based-View): class CreateReview(LoginRequiredMixin, CreateView): form_class = Forma_recenzije success_url = reverse_lazy('detail') template_name = 'accounts/recenzija.html' def get_queryset(self): u = UserProfile.objects.get(id=int(self.kwargs['pk'])) return Reviews.objects.filter(user_profile=u) def form_valid(self, form): form.instance.author = … -
Django Allauth different login redirection for facebook and twitter python 2.7
I am trying to redirect the different pages for the Facebook and Twitter in Django 1.11.5 using the Django-Allauth. I have tried something like this but it didn't work in my case: import allauth.socialaccount.providers as ASP if ASP == 'facebook': LOGIN_REDIRECT_URL = '/test/' else: LOGIN_REDIRECT_URL = '/' I want to know how I can redirect the url for different social media on different links? Kindly suggested me the improvements in the code. -
Clustering two queries from Neo4j python, creating a json for Alchemy.js to visualize the data
I have two querysets nodes_query, edges_query set how to cluster them and create a json so that alchemy.js can be used for data visualisation? Dependencies Mac Osx, python 3.4.3, django 1.9, neo4j-driver Default datasets provided by NEO4j movie dataset, person dataset. **My Views.py** def my_own(request): driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "password")) session = driver.session() # match (n) optional match (n)-[r]-() return n,r: nodes_query = session.run("MATCH (a:Person)-[:ACTED_IN]->(:Movie)RETURN DISTINCT ID(a) AS id, a.name AS name") edges_query = session.run("MATCH (a1:Person)-[:ACTED_IN]->(:Movie)<-[:ACTED_IN]-(a2:Person)RETURN ID(a1) AS source, ID(a2) AS target") result = session.run("MATCH (n) OPTIONAL MATCH (n)-[r]-() RETURN n,r") session.close() return render(request, "friends.html")