Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, why is my jquery url view duplicating?
I'm new to javascript and have just set up jquery/ajax and got it working in my Django project. I haven't amended my view to accommodate the GET requests yet. My ajax functions are sending the following Request URL: http://127.0.0.1:8000/myportfolio/add_transaction/myportfolio/add_transaction when i expect them to sending: http://127.0.0.1:8000/myportfolio/add_transaction/ Why is this happening? My jquery file: $(document).ready(function() { // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $('#id_buysell').on('change', function(){ console.log("buysell"); var $formData = $(this).attr("id_buysell"); console.log($formData); $.ajax({ method: "GET", url: "myportfolio/add_transaction", data: $formData, }); }); $('#id_coin').on('change', function(){ console.log("coin change") var $formData = $(this).attr("id_coin"); console.log($formData); $.ajax({ method: "GET", url: "myportfolio/add_transaction", data: $formData, }); }); }); My view: def add_transaction(request): print(request.method) print("test1") form … -
SQL Alchemy the data types text and text are incompatible in the equal operator
In part of my django API I have the following, to update old notes: old_note = request.databaseSession.query(Tmemo).\ filter(Tmemo.memosern1 == serial).\ one() This query works without any problem as I am using it many other places. The weird problem comes with: old_note.memotext = newtext Then when I commit the following errors happens: ProgrammingError: (pyodbc.ProgrammingError) ('42000', u'[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The data types text and text are incompatible in the equal to operator. (402) (SQLExecDirectW)') [SQL: u'UPDATE tmemo SET memotext=? WHERE tmemo.memosern1 = ? AND tmemo.memosern2 = ? AND tmemo.memotype = ? AND tmemo.memotext = ?'] [parameters: ('asassasasasaassaassaasas2121', u'P03000000060445', u'MEMO', u'5', u'asassasasasaassaassaasas')] (Background on this error at: http://sqlalche.me/e/f405) Tmemo is just a table with column for a serial number memosern1 and memosern2, type with memotype and the notes itself as memotext, serials and type are varchar and memotext as text. I really don't understand what text and text are incompatible means really, it makes no sense, also I am just filtering the serial number, nothing else, so what is up with this weird query? And I can perfectly create another row in the table with the exact same variables being used (newtext), I just can't update an existent one. … -
Django create a subtable
I have three models as below: class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class PersonSession(models.Model): start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) person = models.ForeignKey(Person, related_name='sessions') class GameSession(models.Model): score = models.PositiveIntegerFeild() person_session = models.ForeignKey(PersonSession, related_name='games') Now I want get list of persons with calculated all scores they get plus the time they spend in all their game sessions and branch sessions, the query I currently use is as below: Person.objects.annotate(game_score=Sum(Case(When(Q(sessions__games__isnull=True), then=0), default=F('sessions__games__score'), output=models.PositiveIntegerField())))\ .annotate(spent_time=Sum(Case(When(Q(branch_sessions__isnull=False) & Q(branch_sessions__end_time__isnull=False), then=ExpressionWrapper(ExtractHour(ExpressionWrapper(F('sessions__end_time')-F('sessions__start_time'), output_field=models.TimeField()), output=models.PositiveIntegerField()) * 60 + \ ExtractMinute(ExpressionWrapper(F('sessions__end_time')-F('sessions__start_time'), output_field=models.TimeField()), output=models.PositiveIntegerField()), output_field=models.PositiveIntegerField())), default=0, output=models.PositiveIntegerField()))) \ .annotate(total_score=F('game_score') + F('spent_time') * SCORE_MIN)\ .order_by('-total_score') The problem is that this query join all tables together so for each PersonSession may be we have many GameSession and the resulting table contains the repeated row of a person session which causes time of a person sessions sums together repeatedly and generates a wrong result. In a sql query I must first construct a subtable with sum of game socres and then join that table with persons session, but I do not know how could this possible in django? I am using django 1.11 and postgres. -
Django2 and path: order insensitive optional paramters?
I do not even know if this makes sense to do, so please let me know if it doesn't. Suppose I have an api that can take 3 parameters, but requires none. e.g. <host>:<port>/my-api ? arg1=<a1_1,a1_2,...> & arg2=<a2_1,a2_2,...> & arg3=<a3_1,a3_2,...> where each arg takes a comma separated list. I would like the Django url to represent this, but also be order insensitive as the above example also works like this: <host>:<port>/my-api ? arg3=<a1_1,a1_2,...> & arg1=<a2_1,a2_2,...> & arg2=<a3_1,a3_2,...> I know that using the path method from django.urls allows me to add a default like so app_name = "my_app" urlpatterns = [ ... path("base/", views.base, {'arg1':'', 'arg2':'', 'arg3':''}, name='base'), path("base/arg1=<arg1>", views.base, {'arg2':'', 'arg3':''}, name='base'), path("base/arg1=<arg1>/arg2=<arg2>", views.base, {'arg3':''}, name='base'), path("base/arg1=<arg1>/arg2=<arg2>/arg3=<arg3>", views.base, name='base'), ... ] but this is still order sensitive as base/arg2=<a2_1,a2_2,...> does not match any of the patterns. Is there a way to get around this? I would prefer to not use nested routes if possible: Django optional url parameters -
how to routing multiple domain name in server to the same django project?
I have two domain names for the same website. I want to domain names routing to this server cpanel . how to do it ? and I listed strings representing the host/domain name into ALLOWED_HOSTS but second domain name does not working coreectly. 1. static files not found 2. after login (with google login ) redirected to old domain -
How to complex search trough JSONField in django?
Here is a json stored in my json field: (SomeModel.datetimes_json) [ [ 1526687940.0,# <---filter by this value 1526706000.0 ], [ 1526687950.0,# <---filter by this value 1526706010.0 ], ] How to select only SomeModels where first element of any pair of values is greater than some special? Now I'm using qs.filter(datetimes__0__gte=int(datetime.strptime(min_start_datetime, '%Y-%m-%dT%H:%M:%S').strftime('%s'))) and it doesn't work Thanks -
Filter Queryset using another queryset date field
I´m stuck on the following. My two simplified models: Class Transaction(models.Model): ticker= models.ForeignKey(Stock, on_delete=models.CASCADE) dateOfPurchase = models.DateField() Class Dividend(models.Model: ticker = models.ForeignKey(Stock, on_delete=models.CASCADE) date = models.DateField() value = models.DecimalField(max_digits=8, decimal_places=5) I managed to do: If ticker in Dividend is not in Transaction I exclude the Dividend instance: transaction_qs = Transaction.objects.all() qs = Dividend.objects.all() dividend_qs = qs.filter(ticker__in=transactions_qs.values('ticker')) Now I want to filter down dividend_qs instances so that for each one of them I check if at least one instance of Transaction exists whose dateOfPurchase is lower_than_equal date. I tried some for loops approaches but didn´t quite get what I want. Any help? -
Django cross table relation
I'm creating an API for some podcasting applications using Django and Django Rest Framework. Among others I do have a Show model and an Episode model currently with a foreign Key relationship in Episode: show = models.ForeignKey(Show, on_delete=models.PROTECT) Now I need to add a sequential number within a show, so the first episode of a show should be number 1, second number 2 and so on. Let's call this episode_nr for now and I need the API to be able to query from a combination of show and episode_nr as of course the episode_nr isn't unique. I wonder what the more DRF/Django way would be to solve this: a) add an additional feed to the Episodes model and just hold the number there. b) create an additional model that holds relations to Show and Episode As all of the data in the Episode model gets importet from an external system and the episode_nr is generated on import and not natively imported I thought b) would be better to keep this number separate from the imported data but then I don't know if this just overcomplicates things. I also didn't get an idea yet on how to query solution a) from … -
How to use custom domain name in bitnami (AWS EC2)?
I am using bitnami for hosting my django website. My website is running with static ip and also domain provided by bitnami. But I want to use my own custom domain name which I have bought from Bigrock. How can i use my custom domain in place of that static IP? Documentation of bitnami is a bit confusing for me. Please help! -
Django Haystack / Solr doesn't index files
I'm trying to connect my django app to solr search engine using Haystack. I also want my file to be indexed so I rewrite prepare function as in example from docs http://django-haystack.readthedocs.io/en/master/tutorial.html#installation. my search_index.py looks like this: class ResourceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') creator = indexes.CharField(model_attr='creator') created = indexes.DateTimeField(model_attr='created') edited = indexes.DateTimeField(model_attr='edited') description = indexes.CharField(model_attr='description') def prepare(self, obj): data = super(ResourceIndex, self).prepare(obj) file_obj = obj.file.open() extracted_data = self.get_backend().extract_file_contents(file_obj) t = loader.select_template(('search/indexes/opendata/resource_text.txt',)) data['text'] = t.render({'object': obj, 'extracted': extracted_data}) return data def get_model(self): return Resource def index_queryset(self, using=None): return self.get_model().objects.all() I have tried to render using Context, but Haystack yields an error - that's why I am using dict instead. Plus my template looks like this: {{ object.name }} {{ object.editor.username }} {{ object.file }} {{ object.text }} {{ object.creator.username }} {{ object.created }} {{ object.description }} {% for k, v in extracted.metadata.items %} {% for val in v %} {{ k }}: {{ val|safe }} {% endfor %} {% endfor %} {{ extracted.contents|striptags|safe }} After making schema and rebuild_index I can see instances in solr admin site but i cant search anything from those instances. Everything works just find when using curl request. curl request = < … -
Creating many_to_many relations between objects outside of Django to add fake data in db
I'm using the faker library to ad data to a database. I have 2 models Entity and Item with a many to many relationship between them. I want to create a random relation between Item and Entity. item_list = Item.objects.all() for item in item_list: item.entities = Entity.objects.order_by('?')[0] entities is the M2M that exist in the Item Model; class Item(models.Model) entities = models.ManyToManyField(Entity, related_name='items') I get the following error: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use categories.set() instead. So I tried item.entity_set = Entity.objects.order_by('?')[0] item.save() No error, but no relation is created -
Django login from code without password not working
from panel.helpers import get_random_string from django.contrib.auth import login as auth_login, logout as auth_logout login_no_password(request, slug=None): user = User.objects.get(slug=slug) #hijacked_user user.backend = 'django.contrib.auth.backends.ModelBackend' #request.user is old user that tryies to login this slug_user here user auth_login(request, user) resp = redirect('/') rand_str = get_random_string() request.session[rand_str] = 'staff-login-as' request.session.set_expiry(900) resp.set_cookie('SPA_USER', rand_str) # this is used to notify this request is from hijacked_user(not normal login). return resp I have tried to login using this technique for my special case and it works normally. Although sometimes, this response works fine but while refreshing or clicking for next response (quickly, not the session was expired, just within 10 sec) the hijacked user is not persist there in the browser and the initially requested user is logged_in automatically. What is the issue here ? -
How to dynamically modify <div> tag in Django for loop using JavaScript?
I have a Django template which iterates through records, and I want to modify the div tag based on the average value calculate from the element of the each record. And I try to do it in the way below, but it's not working. Any idea how to dynamically modify tag inside Django for loop using JavaScript? {% for resource in result_basic %} <script type="text/javascript"> var loc_rating = "{{resource.loc_rating}}"; var fac_rating = "{{resource.fac_rating}}"; var tran_rating ="{{resource.tran_rating}}"; var property_avg = (Number(loc_rating)+Number(fac_rating)+Number(tran_rating))/3; document.getElementsByClassName('pratings-{{forloop.counter}}').innerHTML=property_avg; </script> <p>Property Ratings: <div class="pratings-{{forloop.counter}}"></div></p> {% endfor %} -
run django manage.py command in cron
I've written few management commands to run from cron. I'm using pipenv virtual environment running from terminal directly is working great. cd <project_path> pipenv run python manage.py <my_command> I added same script as cron cd /home/project_path && pipenv run python manage.py <my_command> But this is giving error as /bin/bash: pipenv: command not found I also tried following command cd /home/project_path && python manage.py <my_command> which is giving error as File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax -
Joining 2 Models in Django
Im trying to join 2 tables in a django view. I currently have two models SSALiReport.objects.all() NELiReport.objects.all() NELI looks like this { "clout": 40000, "date": "2018-05-15", "sentiment": 500, "ticker": "AAPL" }, SALI looks like this { "date": "2018-05-15", "market": "NYSE", "prediction": 0.6, "price": 300, "ticker": "AAPL" }, I want a third view that looks like this, lets call it FullReport { "date": "2018-05-15", "market": "NYSE", "prediction": 0.6, "price": 300, "ticker": "AAPL", "clout": 40000, "sentiment": 500 }, How do I pull this in a view? -
Django form field display name
I m trying to make a form on the basis of a model. Trouble is that when i create a category via django shell, let's say "Wedding" category, having id=1 and name = "weddings", when i display it in a dropdown(in html form) it shows as Categories object (1) and i would like it to be shown by the name, which is weddings. As in the documentation i understand that i can attach labels when in the Meta form class but i don't fully understand how i can display dynamically all the category names instead of Categories object 1,2,3,4. Models.py class categories(model.Model): id = models.AutoField(primary_key =True) name = models.Charfield(max_length = 50) class Event(models.Model): id = models.AutoField(primary_key =True) category = models.ForeignKey(Categories,on_delete=models.SET_NULL,null = True) owner = models.Charfield(max_length = 50) Forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ['category','person','owner'] So the actual result when rendering the form is : Category:(dropdown) - Categories object (1) Desired result: Category:(dropdown) - weddings -
Django server error 403 forbidden nginx/1.10.3 (ubuntu)
I have some media content in ubuntu server. I can upload files. but when I try to load files it shows 403 forbidden nginx/1.10.3 (ubuntu).In file permission, it displays rw--------. How can I retrieve all content without error? I'm not familiar with Ubuntu I used this snippet to recover files. However, it only works the single time. After some while, it shows the same error. sudo chmod -R 664 /home/django/media/image/ sudo chmod -R a+X /home/django/media/image/ -
How to create links in Django if we use filters
Django == 1.11 I want to implement a simple filter. I will use https://django-filter.readthedocs.io django-filter==1.1.0. I created views it look like @login_required def all_task(request): tasks_list = Task.objects.all().filter(Q(executive_man=request.user) | Q(author=request.user)).order_by( '-created_date') tasks_filter = CategoryFilterTask(request.GET, queryset=tasks_list) return render(request, 'task/task_list.html', {'filter': tasks_filter}) urls look like url(r'^all_task/$', views.all_task, name='all_task'), url(r'^task/(?P<pk>\d+)/$', views.task_detail, name='task_detail'), I want to say filter work good. It is my HTML <form method="GET"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <h4>Need tasks</h4> <ul> {% for category in filter.qs %} <li><a href="{% url 'task_detail' pk=task.pk %}">{{ category }}</a></li> {% endfor %} </ul> And I don't understand how to create url task. If simple show tasks - {% url 'task_detail' pk=task.pk %} - it works very well, but if work filter I get NoReverseMatch at /all_task/ . I hope for your help. Thank you very much. P.S. Screenshot with errors - https://www.dropbox.com/s/entnqb6r7ia9udz/Screenshot%20from%202018-05-15%2013-34-23.png?dl=0 and text file with errors - https://www.dropbox.com/s/eflqiavfhep9xmt/eroor.txt?dl=0 -
Django model design for many identical users
There is a company serving many customers (more than 5000), each customer has a set of data with identical fields, but each set is very large (has many documents) and keeps growing daily; the data can soon be classified as big data, but not there yet. I use MongoDB for storing the data. All customers' data is internal for the company, so there is no need to create different users. Now my original design was to have one collection per customer with Django models like this: class CustomerInfo (models.Model): Time = models.DateTimeField() CustomerID = models.CharField(max_length = 200) Status = models.CharField(max_length = 200) # More fields here... class Meta: abstract = True class customer_1 (CustomerInfo): pass class customer_2 (CustomerInfo): pass # So on for 5000 customers: class customer_5000 (CustomerInfo): pass Each customer_N represents a collection in the database. With this design I can use Django queries directly (I also use djongo to connect Mongo and Django, so this part works perfectly). I can do something like this in the view: customer = apps.get_model('customer_list', customer_number) data = customer.objects.all().order_by('-Time') I use get_model so I don't have to from .models import customer_N for 5000 of them. But I still have to fill my models.py … -
How get instance in a method clean from some forms
How get instance a model Article in method clean? I'm need get instance from form, but I get None value. How to get previous field values? model class Article(models.Model): name = models.CharField(max_length=25) value = models.CharField(max_length=25) forms class ArticleForm(forms.ModelForm) class Meta: model = Article fields = '_all_' def clean(self): cleaned_data = super().clean() get_instance = self.instance print(get_instance) and I get None views def test(request) form = ArticleForm({'name':'test', 'value':'test'}) if form.is_valid(): print(1) else: print(form.errors) -
How do I send payload to another app to a specific model in django rest framework
I building an RESTful API with django 1.11 + djangorestframework==3.8.2 + python3. I have to applications one is HR and the other is the Payroll app. In the hr.models I have defined and Employee class and also implemented a class based view to create an Employee instance. I have a slight problem though, I would like to make it possible when I create the employee instance the payroll application would be updated with the same employee details. How do I implement this: So far this is how I have implemented in hr.views: class AddEmployeeAPIView(APIView): def post(self, request, format=None): try: company = Company.objects.get(id=request.data['company']) department = Department.objects.get(id=request.data['department']) job_group = JobGroup.objects.get(id=request.data['job_group']) contract_type = Contract.objects.get( id=request.data['contract_type']) skill = Skill.objects.get(id=request.data['skill']) unit = Unit.objects.get(id=request.data['unit']) try: c_user = User.objects.get(id=request.data['user']) except: new_user = request.data['new_user'] c_user = User.objects.create(first_name=new_user['first_name'], last_name=new_user['last_name'], username=new_user['username'], email=new_user['email'], password=new_user['password']) try: job_title = Job.objects.get(id=request.data['job_title']) except: new_job = request.data['new_job'] if new_job: job_title = Job.objects.create( name=new_job['name'], job_code=new_job['job_code'] ) employee = Employee.objects.create( user=c_user, company=company, department=department, job_group=job_group, contract_type=contract_type, skill=skill, unit=unit, job_title=job_title, hr_number=request.data['hr_number'], nhif_no=request.data['nhif_no'], nssf_no=request.data['nssf_no'], identification_number=request.data['identification_number'], induction_date=request.data['induction_date'], orientation_date=request.data['orientation_date'], tax_id_number=request.data['tax_id_number'], joining_date=request.data['joining_date'], is_manager=request.data['is_manager'], active=request.data['active'] ) employee.save() # Update Payroll with Employee Details # #### url = 'http://0.0.0.0:9000/payroll/employee_create/' try: payload = { 'subject_type': 'EMPLOYEE-DETAILS', 'user': employee.user.username, , 'company': employee.department, 'job_group': employee.job_group, 'contract_type': employee.contract_type, 'skill': employee.skill, … -
Decoupling Django signals from classes that touch the DB
I have one app that dispatches a signal, let's call it signal_x. In another app, a @receiver for signal_x is defined, and in it's apps.py's ready() function is the file containing the receiver imported. The @receiver function has one issue though. It has a dependency to an object, let's call it object_y, that has in it's constructor a dependency to the DB. With the values extracted from the DB, some heavy objects are built. These heavy_objects must be in memory, for very fast computations and thus they can't be lazily loaded as it would take too long when they're used for the first time. self.location_ids can't be lazily loaded either, as it's used by the two compute_heavy_... functions. Everything works completely fine until we drop the database, create it again and run manage.py makemigrations. Now makemigrations will fail because Django first runs django.setup(), which runs the ready() function of each app. When it reaches the ready() function with the import it will, as expected, import the file and try creating object_y. But object_y needs models which don't yet exist and thus the error. How could I elegantly solve/circumvent this? class Recommender: def __init__(self): self.location_ids = self.get_location_ids() self.heavy_object1 = self.compute_heavy_object1(location_ids) self.heavy_object2 … -
Django template optimization
With a list of dicts containing a total of over 30,000 values and looks something like [ { "line": "First Item", "data": {"2019-01-01": 1234, ..., "2040-01-01": -3123} }, { "line": "Second Item", "data": {"2018-01-01": 1512, ..., "2037-12-01": -4123} }, ] and calling 10-15 template tags per value for 300k to 500k template tag calls, my performance in rendering a request has degraded materially. My template tags do things like get value from data given date, format number with specific format string that is distinct per line, format for negative numbers or zeroes, etc. In an effort to make more readable code and be DRY, I also do a lot of nested template includes, resulting in over 12,000 calls to template rendering. My choices seem to be to Reduce the number of template includes Return data easier to parse and requiring fewer template tag calls. This only works up to a point. Return formatted data or even html snippets instead of calling template tags as much Do something else - and I don't know what something else is I'm seeking pointers/ways to address the huge performance hit problem I have created for myself. -
DeserializationError when trying to load my saved data to my new database
So before I changed databases from sqlite to postgresql, I performed python manage.py dumpdata > datadump.json which saved a datadump.json file and dumpdata.json file in my app directory.: To retrieve this data in my new database I performed python manage.py loaddata datadump.json however it returned this error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 166, in load_label for obj in objects: File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/serializers/json.py", line 88, in Deserializer six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2]) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/serializers/json.py", line 81, in Deserializer objects = json.loads(stream_or_string) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/zorgan/Desktop/project/app/datadump.json': Expecting value: line 2 column 1 (char 1) Any idea what the problem is? -
django output with array or list of object
I am doing my first django project and i am stuck here. i need two array in result output 1. Pending reservation 2. Approved Reservation Reservation contain type of services user opted for. there can be multiple reservation. Status=1 aprroved status= pending Required output result: { "upcoming_pending": [{reservation_id,location_id,location_name,arrival_date,arrival_time, departure_date,departure_time, services:[{service_id,service_title,service_description},{}], add-ons:[{service_id,service_title,service_description},{}],comments}, {},etc]}, "upcoming_approved": [{reservation_id,location_id,location_name,arrival_date,arrival_time, departure_date,departure_time, services:[{service_id,service_title,service_description},{}], add-ons:[{service_id,service_title,service_description},{}],comments}, {},etc]} My code i am trying something like this below data={} data["upcoming_pending"]=[] data["upcoming_approved"]=[] queryset1 = reservations.objects.filter(user_id=user_id,arrival__gte=datetime.now(),status=0) for a in queryset1: data["upcoming_pending"][a.id]=reservations.objects.filter(id=a.id) data["upcoming_pending"][a.id]["services"]=services.objects.filter(service_id__in=ser,type=1) data["upcoming_pending"][a.id]["add-ons"]=services.objects.filter(service_id__in=ser,type=2) queryset2 = reservations.objects.filter(user_id=user_id,arrival__gte=datetime.now(),status=1) for b in queryset2: data["upcoming_pending"][b.id]=reservations.objects.filter(id=a.id) data["upcoming_pending"][b.id]["services"]=services.objects.filter(service_id__in=ser,type=1) data["upcoming_pending"][b.id]["add-ons"]=services.objects.filter(service_id__in=ser,type=2) return Response({"result":data}, status=status.HTTP_200_OK)