Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem when reconfiguring Nginx for SSL with self-signed certificate
I have a VPS on Digital Ocean with Ubuntu 18.04, Nginx, Gunicorn, Django, and a test web application, all configured (ufw) to work with http: 80. Everything works perfectly. Tutorial Now I modify the file /sites-available/LibrosWeb to allow SSL traffic with a self-signed certificate, since I do not have a domain. Tutorial. Result "Error 502 Bad Gateway". This is the initial code that works well with http: 80: server{ #Configuracion http listen 80; listen [::]:80; server_name 15.15.15.15; location = /favicon.ico { access_log off; log_not_found off; } location /robots.txt { alias /var/www/LibrosWeb/robots.txt ; } location /static/ { root /home/gela/LibrosWeb; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } And this is the code to allow SSL (error 502): server{ #Configuracion SSL listen 443 ssl http2; listen [::]:443 ssl http2; server_name 15.15.15.15; include snippets/self-signed.conf; include snippets/ssl-params.conf; location = /favicon.ico { access_log off; log_not_found off; } location /robots.txt { alias /var/www/LibrosWeb/robots.txt ; } location /static/ { root /home/gela/LibrosWeb; } location / { include proxy_params; proxy_pass https://unix:/run/gunicorn.sock; } } server{ #Configuracion http listen 80; listen [::]:80; server_name 15.15.15.15; return 302 https://15.15.15.15$request_uri; } UFW configured as: 80,443/tcp (Nginx Full) ALLOW IN Anywhere 80,443/tcp (Nginx Full (v6)) ALLOW IN Anywhere (v6) The files /etc/nginx/snippets/self-signed.conf and … -
Adding Disqus comment count to Django page
I have successfully enabled Disqus comments to the individual articles, but am so far unable to add a comment count to the contents page. According to the documentation Place the following code before your site's closing </body> tag: <script id="dsq-count-scr" src="//my-site.disqus.com/count.js" async></script> However, I'm extending from base_layout and don't have any <body> tags. I don't think this is the problem, however. It seems to be the next instruction to Append #disqus_thread to the href attribute in your links. This will tell Disqus which links to look up and return the comment count. For example: <a href="http://example.com/bar.html#disqus_thread">Link</a> This is my HTML for the contents page: {% extends 'base_layout.html' %} {% load avatar_tags %} {% block content%} <h1>MY TITLE</h1> <div class="articles"> {% for article in articles %} <div class="article"> <h2><a href="{% url 'articles:detail' id=article.pk slug=article.slug %}#disqus_thread">{{ article.title }}</a></h2> <p>{{ article.snippet }}</p> <p>{{ article.date|date:"d M Y" }}</p> <a href="{% url 'accounts:view_profile' slug=article.author id=article.author_id %}"> <p class="author">{% avatar article.author.username 40 class="img-circle img-responsive" id="user_avatar" %} <br>{{ article.author.username }}</p> </a> </div> {% endfor %} </div> <script id="dsq-count-scr" src="//my-site.disqus.com/count.js" async> </script> {% endblock %} This addition to the <href> tag just renders the actual text article.title instead of the actual title. I've tried it several places within … -
How to query a model by a related object and get the related object in the queryset using the Django ORM
I know it's possible to query a model using a reverse related field using the Django ORM. But is it possible to also get all the fields of the reverse related model for which the query matched. For example, if we have the following models: class Location(models.Model): name = models.CharField(max_length=50) class Availability(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() price = models.PositiveIntegerField() would it be possible to find all Locations that are available in a specific timeframe AND also get the price of the Location during that availability. We are under the assumption that Availability objects that have the same location can not have overlapping start/end datetimes. if user_start_datetime and user_end_datetime are inputted by the user, then we could possibly do something like the following: Location.objects.filter( availability__start_datetime__lte=start_datetime, availability__end_datetime__gte=end_datetime) But I'm not sure how to also get the price field for the specific availability that did result in a match for the query. In raw SQL, the behavior I'm talking about might be achievable via something like this: SELECT l.id, l.name, a.price FROM Location l INNER JOIN Availability a ON a.location_id = l.id WHERE /* availability is within user-inputted timeframe */ I've considered using something like prefetch_related('availability_set'), but … -
Heroku is using the wrong requirements.txt when I try to git push my app
I'm trying to install a django app to Heroku for the first time. I've been following tutorials and things were going fine until git push heroku master. I get an error with postgrequl/psycopg2: Collecting psycopg2==2.6.2 (from -r /tmp/build_9a1b9401a05f6186e32ef1f993bdd183/requirements.txt (line 10)) remote: Downloading blah...blah../bc/psycopg2-2.6.2.tar.gz (376kB) remote: Complete output from command python setup.py egg_info: remote: running egg_info remote: creating pip-egg-info/psycopg2.egg-info remote: writing pip-egg-info/psycopg2.egg-info/PKG-INFO remote: writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt remote: writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt remote: writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' remote: Error: could not determine PostgreSQL version from '10.5' remote: remote: ---------------------------------------- remote: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-mu5yzi1s/psycopg2/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to django-randomizer. I did some searches and I read where other people had problems because they had an older version of psycopg2. So I edited my requirements.txt file to include psycopg2-2.7.5, which is the latest. I think try `git push heroku master' again and I get the same error. The error references psycopg2-2.6.2. I even deleted my app and started again, but when it came to the git push, I get the same error. At this time … -
Bokeh Server and Django
Ultimately, I'm trying to serve interactive bokeh plots on a website. I'm using Ubuntu 18.04 nginx/1.14.0, Django==2.1, gunicorn==19.9.0, Python 3.6.5, bokeh-0.13.0 I am successful at seeing the bokeh plot locally and I was successful without django by using directives in nginx's website.conf ... location /bkapp { proxy_pass http://127.0.0.1:5100; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_http_version 1.1; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host:$server_port; proxy_buffering off; } and : bokeh serve bkapp.py --port 5100 --prefix=bkapp --allow-websocket-origin=www.website.com ...to communicate with the bokeh server at www.website.com/bkapp in my browser (not locally). I did not have to add any port triggers or virtual servers for port 5100 on my router. !!!!!!!!!!!!!!!!!!!! HOWEVER, I WOULD LIKE TO ROUTE THROUGH django/gunicorn: currently I'm receiving Server Error (500) !!!!!!!!!!!!!!!!!!!! I think my problem is routing/communication once the request enter's the views.py. I think my problem is here and I've been tweaking the code from Embed an interactive Bokeh in django views . views.py is properly configured to respond to typical requests but can't connect/work with the local bokeh server views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): script = autoload_server(model=None, app_path="/bkapp", url="http://localhost:5100/") return render(request, 'bkapp/index.html', { 'script': script}) bkapp/index.html: {% extends 'home/base.html' … -
Django JSONFIeld (.objects.create) data is not getting inserted
I am new to django / postgres. I have created a JSONField model, by following along with the documentation. In this instance I am attempting to store a json file in psql. class TestResults(models.Model): name = models.CharField(max_length=200) data = JSONField() This model is then used in a celery task. # task for running tests by marker def run_tests_mark(test_marker): os.chdir('/lib/tests') # only allow specific strings to be passed in by the user if test_marker not in ['smoke', 'regression']: return 'You have entered an invalid term. Please use either smoke of regression.' # run pytest command with self contained reporting results = pytest.main(['-p', 'no:django', '-v', '--json-report', '-m', test_marker]) # convert report to json report_json = json_report('.report.json') # insert the json report: TestResults.objects.create(name='test_run_id_00', data=report_json) return None I am using a helper to grab the resulting report def json_report(filename): with open(filename, 'r') as json_file: data = json.load(json_file) return data I can also see that the report itself is generated and in the expected directory. A table named test_automation_app_testresults has been created when I connect to psql however when I run select * from test_automation_app_testresults nothing comes back. My questions are: Am I using JSONField correctly? Should there be some kind of 'commit()' following the … -
How to end a forloop as soon as the nested if statement is true in Django Template
I have tried slice the forloop many ways in the template but have failed. I need only 1 result from the loop Either "Do A" or "Do B" Depending on the the condition. Even if I have a million applications. but as soon as I get 3 applications Either I have 2 "Do A" or 2 "Do B". |slice:":1" does not work unless I am using it wrong. Below is my code {% for app in applications %} {% if applicant.username in app.user.username %} <p> Do A </p> {% else %} <p> Do B </p> {% endif %} {% endfor %} Below is what I need to achieve I wish the below code existed but I know it doesn't {% for app in applications %} {% if applicant.username in app.user.username %} <p> Do A </p> {{ break }} {% else %} <p> Do B </p> {{ break }} {% endif %} {% endfor %} -
Django reverse id of choicefield in template
I need to show the status of a busstop (example data) on a page. I create a class with multiple values here is what is most important of it: class Busstop(models.Model): TYPE = (('O', 'Open'), ('C', 'Closed'), ('M', 'Maintenance')) stop_status = models.CharField(max_length=100, choices=TYPE, default='Open') When I call {{ busstop.stop_status }} in my HTML template it only shows the 'O' and not the 'Open' (...). How can I reverse this "ID" to its counterpart and show the 'Open'? -
Is it possible to restart only specific apps in Django, withhout restarting the whole server?
Similar to the concept of microservices, is there a way to issue a signal to Django (using a script/package), to restart only a specific app? Let's say we have apps APP1 and APP2, each being developed by a different developer, with shared interdependancies, all in the same Django project. The project is live in production, and rather than restart the whole server, inducing unnecessary downtime for unrelated features, we just want to reload the code existing in APP1. Currently using apache + gunicorn -
How to add/access image file in django javascript not going through the template
I have css and javascript files that extend my Django admin, through the Media class. Is there a compatible way for image files too? I need to provide with a simple image to one of my js files (that are not going through the templating engine, just extending django admin via jquery...). If I would have extended Django through the templating engine (AKA providing alternative django admin templates) I could have used the {%static_files%} explained/discussed everywhere. But I wont. It's plain hard work, and I am going around using simple js. which is standard. Uploading images seems ... oddly hard. Any clue where to put the images, and what is the pass to refer to from the html code to access it? It's a dev machine... -
adding comments form Django
I am trying to add a form to my topics.html page so that a user can submit a comment. When the user submits the comment I want to display who posted the comment and the time and date (see image) When I am submitting the data I am receiving the following error: I believe it has to do with the fact that I am not specifying the user who's posting the comment properly.and also I'm not passing the current topic that the user is posting to. views.py from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from comments.models import Comment from .models import Category, Entry, Topic from .forms import CategoryForm, TopicForm, EntryForm, CommentForm def topic(request, entry_id): """Show entry for single topic""" topic = Topic.objects.get(id=entry_id) entries = topic.entry_set.all() comments = Comment.objects.all() if request.method != 'POST': # No comment submitted form = CommentForm() else: # Comment posted form = CommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user form.save() return HttpResponseRedirect(reverse('blogging_logs:topic')) context = {'topic': topic, 'entries': entries, 'comments': comments, 'form': form} return render(request, 'blogging_logs/topic.html', context) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] labels = {'text': ''} widgets = {'text': forms.Textarea(attrs={'cols': … -
is there a way to rename python virtual environment?
Our production and development python virtual environments seem to have different names, it is causing problem when configuring other services like celery etc, Now we have to maintain 2 different conf files. Is there a way to rename one environment? -
How to temporarily disable ForeignKey relationship between Django models
class Season(models.Model): """ unique season object per clothing drop """ name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='season', blank=True) season_available = models.BooleanField(default=True) class Meta: """ meta-data per season """ ordering = ('name',) verbose_name = 'season' verbose_name_plural = 'seasons' def __str__(self): return '{}'.format(self.name) Class Season, which i want to only be related to Category iff Apparel(category) class Category(models.Model): """ categories for products """ name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) season = models.ForeignKey(Season, on_delete=models.CASCADE) class Meta: """ meta-data per category """ ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def foreign_key_controller(self): """enable foreign key relationship with specific models.""" def __str__(self): """ :return: '{}'.format.(self.name) :rtype: str """ return '{}'.format(self.name) class Apparel(models.Model): """ unique product per category per season """ category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) price = models.DecimalField(decimal_places=2, max_digits=10) image = models.ImageField(upload_to='product', blank=True) stock = models.IntegerField() product_available = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_latest_update = models.DateTimeField(auto_now=True) here i want to create a function using if/else to disable to foreignkey relationship between Season and Category whenever the foreignkey in Category() !=Apparel. class Meta: """ meta-data for product """ ordering = ('name',) verbose_name = 'product' … -
how to make sure uWSGI and celery workers reconnect to MongoDB after a new primary is voted
Whenever MongoDB votes a new primary uWSGI workers and celery start throwing the exception AutoReconnect("connection closed") pymongo.errors.AutoReconnect: connection closed Until the workers are restarted, MongoDB connection does not happen. What is the best way to handle this? -
Sync local and remote database
So I have finished writing this inventory project in django it includes a sales app I intend on having 2 version of the project one on local machine the other uploaded to heroku. In a situation were network won't be available (most time there is none) I want to use the offline version to print invoice and make sale. Later when the network kicks in I can sync it to the remote database to match the local database. I've read django sync-tool didn't get it that much I also read django multi database in the doc but I guess that is not suitable for what I intend to do. I also read django-replicated but seems to be mysql driven as I currently run my project using postgres. Thanks for any help in adv. And I am running django 2.1, python 3.6 -
Connect to 3rd party web socket and pass data after manipulation to Django Channel
I have the following standalone code that connects to a 3rd party via a web socket. It does some statistical computation on the message that is received and then outputs the results to terminal. The type of data received over this socket varies and is handled based on what the data is. I want to port it over to Django via Channels such that my clients connect to me via a web socket and they get placed into a channel's group, awaiting the data corresponding to their group. My clients will get pushed the data from the 3rd party socket after manipulation for their respective group. from autobahn.asyncio.websocket import WebSocketClientProtocol, WebSocketClientFactory class MyProtocol(WebSocketClientProtocol): def onConnect(self, response): # Do Something def onOpen(self): # Do Something def onMessage(self, payload, isBinary): # Perform heavy calculations on each message. def onClose(self, wasClean, code, reason): # Do Something if __name__ == '__main__': import asyncio factory = WebSocketClientFactory("wss://example.com") factory.protocol = MyProtocol loop = asyncio.get_event_loop() sock = loop.create_connection(factory,"example.com", 9443, ssl=True) loop.run_forever(sock) The connection to the 3rd party socket should run in the background without interruption and then push to the channel group when it has finished its calculations on the data received. Ideas on how to go … -
Relate three models together based on profile field
I want to be able to relate my User model, profile model, and a seperate model together. My current model structure looks like this: class Profile(models.Model): COORDINATOR = 1 LEADER = 2 ADMIN = 3 ROLE_CHOICES = ( (COORDINATOR, 'Coordinator'), (LEADER, 'Leader'), (ADMIN, 'Admin'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.PROTECT,null=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) agent_code = models.CharField(max_length=15, null=True, blank=True) class DailyReports(models.Model): agent_code = models.CharField(max_length=15, blank=True, null=True) product = models.CharField(max_length=15) num_free = models.IntegerField(blank=True, null=True) apps_submitted = models.IntegerField(blank=True, null=True) apps_activated = models.IntegerField(blank=True, null=True) prem_submitted = models.DecimalField(max_digits=20, decimal_places=2,blank=True, null=True) date = models.DateField(auto_now=False,auto_now_add=False,null=True,blank=True) I can relate Profile and User, but I'm attempting to relate Profile to DailyReports on agent_code, and then relate to the User model. So with something like the following: test_query = DailyReports.objects.filter(product__in=['LT15', 'LT121']) \ .values('agent_code') \ .annotate(premium=Sum('prem_submitted')) \ .order_by('-premium') \ I get the output as expected: {'agent_code': 'ABC123', 'premium': Decimal('50015.87')} {'agent_code': 'DEF456', 'premium': Decimal('44818.20')} {'agent_code': 'GHI789', 'premium': Decimal('35322.35')} ... But I also want to get the information from the Profile based on agent_code, and then the related User information based on the relation made between the agent_code between Profile and DailyReports, such that my output would look like: {'agent_code': 'EGA62BDK', 'premium': Decimal('479872.55'), user.profile.first_name, user.profile.last_name, profile.user_id, profile.role} {'agent_code': … -
Django URL patterns have stopped matching
I have been cutting my teeth on python and django with a specialized membership application (My_Members). The slightly edited footprint is: |-- Billing | |-- __init__.py | |-- admin.py | |-- apps.py | |-- models | | |-- __init__.py | | |-- account.py | | |-- fees.py | | `-- payment.py | |-- tests.py | |-- urls.py | |-- views | | |-- __init__.py | | |-- account.py | | `-- fees.py | `-- views.py |-- My_Members | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- Manager | |-- __init__.py | |-- admin.py | |-- apps.py | |-- models | | |-- __init__.py | | `-- group.py | |-- tests.py | `-- views | |-- __init__.py | `-- group.py |-- Members | |-- __init__.py | |-- account_adapter.py | |-- admin.py | |-- apps.py | |-- forms | | |-- __init__.py | | |-- profile.py | | `-- student.py | |-- models | | |-- __init__.py | | |-- profile.py | | |-- rank.py | | |-- student.py | | `-- title.py | |-- urls.py | `-- views | |-- __init__.py | |-- group.py | |-- index.py | |-- profile.py | `-- student.py The urls.py under My_Members … -
How would the architecture be in an web application that uses Django REST for back-end and Angular for Front?
I'm required to make a web application that used DJango REST and Angular so I want to get an idea how to do this by creating a diagram of how everything will communicate bettween each other. I assume the best way is to put the angular project inside the statics files of the Django Framework. Here's my diagram. Architecture Diagram I'm not sure if I should be more deatiled or I'm missing something important. -
DataTables - Map Data and correcting table layout
I am integrating the DataTables in Django 2.1. But the table is broken and I can not map the data sent by the server to JS. This is my configuration JS: <!-- Bootstrap CSS Section --> <link href="{% static 'bootstrap/dist/css/bootstrap.min.css' %}" type="text/css" rel="stylesheet"> <link href="{% static 'datatables.net-bs4/css/dataTables.bootstrap4.min.css' %}" type="text/css" rel="stylesheet"> <!-- Bootstrap core JavaScript--> <script src="{% static 'jquery/dist/jquery.min.js' %}"></script> <script src="{% static 'bootstrap/dist/js/bootstrap.min.js' %}"></script> <!-- Datatables plugin JavaScript--> <script src="{% static 'datatables.net/js/jquery.dataTables.js' %}"></script> <script src="{% static 'datatables.net-bs4/js/dataTables.bootstrap4.js' %}"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#user-datatable').DataTable({ language: { "sEmptyTable": "Nenhum registro encontrado", "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros", "sInfoEmpty": "Mostrando 0 até 0 de 0 registros", "sInfoFiltered": "(Filtrados de _MAX_ registros)", "sInfoPostFix": "", "sInfoThousands": ".", "sLengthMenu": "_MENU_ Resultados por página", "sLoadingRecords": "Carregando...", "sProcessing": "Processando...", "sZeroRecords": "Nenhum registro encontrado", "sSearch": "Pesquisar", "oPaginate": { "sNext": "Próximo", "sPrevious": "Anterior", "sFirst": "Primeiro", "sLast": "Último" }, "oAria": { "sSortAscending": ": Ordenar colunas de forma ascendente", "sSortDescending": ": Ordenar colunas de forma descendente" } }, "processing": true, "serverSide": true, "ajax": { "url": "{% url 'authentication:get_users' %}", "type": "GET", "dataSrc": "" }, "columns": [ {"data": 'name'}, {"data": "email"}, {"data": "last_login"}, {"data": "is_active"}, ] }); }); </script> My Views.py code: @login_required def get_users(request): object_list = CustomUser.objects.all() data … -
MultipleObjectsReturned Django
Im trying to display a page that shows all the bookings in a Booking model on a page. views.py def bookings(request): booking_list = get_object_or_404(Booking.objects.filter().order_by("-day")) return render(request, 'roombooker/base.html', {'booking_list': booking_list}) models.py class Booking(models.Model): day = models.DateField(u'Booking Day',help_text=u'Day of Booking') start_time = models.TimeField(u'Start Time', help_text=u'Start Time') end_time = models.TimeField(u'End Time', help_text=u'End Time') user = models.ForeignKey('User', on_delete=models.SET_NULL,null=True) room = models.ForeignKey('Room', on_delete=models.SET_NULL,null=True) urls.py urlpatterns =[ url(r'^bookings/',views.bookings, name='bookings'), ] There are currently 10 dummy entries in the db that I put in. When I try to go to the bookings page however I get MultipleObjectsReturned at /bookings/ get() returned more than one Booking -- it returned 10! Which is what I want, I wanted 10 Booking objects. The idea was to pass it to the html for rendering. How can I solve this error please? Thanks -
Django GET Request Data Persistence w/ Pagination
I have a django app that does some filtering and returns the data using pagination. Here is an example of the view def sample(request): v = request.GET.get('v') # DB querying and filtering here with v-value # pagination here return render_to_response(template_name, locals(), context_instance = RequestContext(request) So, this is an example of what the url dispatcher would look like for this view: http://sample.com/v=1 This would essentially filter the database and return the data using pagination. The issue arises when I used Django's pagination and attempt to get pages > 1. For example, clicking the next button of pagination would bring: http://sample.com/?page=2. Quickly, you can see where I have lost the filter value from the previous request (v=1). My view ends up throwing and error because no values for v is being specified like on page 1. I have considered using request.get_absolute_url() within the view and parsing the url query parameters to reconstruct the filtered GET request within the view, but this is not working as expected. How do I continually set this value for each pagination's subsequent call to the view? For example, page 2 would be http://sample.com/v=1?page=2. My problem is not quite this simple in that I have about 4-5 different … -
Django Restaurant Managment App Help on Models
I am building an App for my brother's Bar. He will take orders and charge. I have a 'Food' and a 'Order' model. Let's say: class Food(models.Model): Name = models.CharField(max_length=50) Price = models.DecimalField(max_digits=7, decimal_places=2) Stock = models.BooleanField() class Order(models.Model): Date = models.DateField(auto_now=True) Product = models.ForeignKey(Food, on_delete=models.PROTECT, null=True, blank=True) Quantity = models.IntegerField() TotalPrice = models.DecimalField(max_digits=7, decimal_places=2) I cannot figure out how to add, on the same order, more than one food. Also specify quantity for each food. Could someone please help? Thanks in advanced. -
Multiple lists in single json output
So I need a certain json format for a chart, I've added the following to the views views.py def booking_add_to_timeline(request): data = Booking.objects.all().values( 'booking_no', 'arrival_date', 'departure_date', ) data_list = list(data) return JsonResponse({"data": data_list}) Which gives me the following output: JSON { "data": [ { "booking_no": "1", "arrival_date": "2018-09-03", "departure_date": "2018-09-10", }, { "booking_no": "2", "arrival_date": "2018-09-12", "departure_date": "2018-09-19", } ] } I'm looking to add another list, creating the following: JSON { "data": [ { "booking_no": "1", "arrival_date": "2018-09-03", "departure_date": "2018-09-10", }, { "booking_no": "2", "arrival_date": "2018-09-12", "departure_date": "2018-09-19", } ], "room": [ { "nr": "102" "persons": "2" }, { "nr": "103" "persons": "2" } ] } I've tried to add anoter list by combining both list_all = data_list + room_list but that doesn't create a seperate array... -
Django Tastypie filter OR statement
Suppose I'm filtering products in the Django Tastypie API and I want to return all products with product_type = 'cracker' OR product_name = 'oreo'. Using this syntax: localhost:8000/api?product_type=cracker&product_name__icontains=oreo This will return products which are crackers AND are named oreo. How can I turn that into an OR statement?