Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Confusion with viewset in Django
I was learning Viewset in Django Rest framework and found out that we need to add these variables: queryset = User.objects.all() serializer_class = UserSerializer inside viewset or say ModelViewSet to be exact. THe question is why need queryset and serializer_class variables in ModelViewSet? -
ineed to be inside an array name {"urllist": []} so it will look like this
I want to be like this picture I'm being this way -
How to return two dictionaries in views.py
How to return infos and data in views.py? I tried: return render(request, 'index.html', {'infos':infos}, data) return render(request, 'index.html', {'infos':infos, 'data':data}) but nothing works views.py def contact(request): infos = Info.objects.all() if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): messages.success(request, 'Success') admin_address = "mail" responder_address ="responder@site.pl" client_address = request.POST['email'] message_for_admin = """ name: %s; E-mail: %s; Subject: %s; Text: %s; """ % (request.POST['name'], request.POST['email'], request.POST['subject'], request.POST['message']) message_for_client = """ text """ try: send_mail(request.POST['subject'], message_for_admin, responder_address, [admin_address,]) #send_mail(request.POST['subject'], responder_address, message_for_client, [client_address,]) except BadHeaderError: print('wrong subject') data['form'] = form data['info'] = 'thanks for message' else: data['form'] = ContactForm() return render(request, 'index.html', {'infos':infos}) -
Django, returning out parameters of a stored procedure when using cursor (Oracle)
I have written the below function to simplify the way i call stored procedures. I need help on how to return the out parameters. def call_procedure(dbname,procedure_name,parameters_list=[]): with connections[dbname].cursor() as cursor: try: cursor.callproc(procedure_name, parameters_list) except Exception as e: raise Exception(e) Procedure call: call_procedure('testdb',[1,2,3,'']) In the call I need to print the out parameters. -
Wait for current task to complete before stopping celery
I have created a systemd process that runs celery. I have set the concurrency to 1 since I need to tasks to run on a first in first out(FIFO) queue. If i need to stop celery for some maintenance, how do I make celery wait for the currently running task to complete before stopping? I don't want it to wait for the entire queue to complete. I just need celery to wait for the current task to complete running before celery itself stops. This is my systemd service file [Unit] Description=celery daemon After=network.target [Service] User=<username> Group=<group> WorkingDirectory=/path_to_django_project/project_name ExecStart=celery -A project_name worker concurrency=1 [Install] WantedBy=multi-user.target -
Web development using Django in python?
Recently three 3 weeks ago, I took fullstack web-development course on demy but now when i want to built something on my own i feels no confident that i can write the code for my website . the instructor to go through the documentation once to get deep knowledge about Django so you can feel confident about the concepts . my question is how shall i go through the docs , should i read it whole or get help only when i want to know something about want i want? keeping in mind that ,i am programmer in python . so,if any one who has good exprience about it can share an idea how to go through this process! And how much time should it take to get good at. Thanks for your response in advance! -
how to use only two field for login authentication among various fields in django?
I have made a custom user model with fields like email, age, username, name, password. but whenever I try to make a login interface it needs to use all the fields for authentication other wise gives an error . but I want to do authenticate using only email and password not using all the fields that database have. how can I do that in Django? . when I have tried authenticating using all the fields that database have, login interface works. -
(Django) How do I make 'objects.get()' to work with an argument that exists?
I am trying to emulate Instagram login which takes either one of 'username', 'fullname', or 'email'. views.py class SignInView(View): def post(self, request): account_data = json.loads(request.body) try: if Account.objects.filter(email=account_data['email']).exists() or Account.objects.filter(username=account_data['username']).exists() or Account.objects.filter(fullname=account_data['fullname']).exists(): #############THIS IS WHERE IT NEEDS SOME WORK############################################ account = Account.objects.get(email=account_data['email']) ######################################################################################### encoded_pw = account.password.encode('utf-8') encoded_input = account_data['password'].encode('utf-8') if bcrypt.checkpw(encoded_input, encoded_pw): token = jwt.encode({ 'email' : account.email }, 'secret', algorithm='HS256').decode('utf-8') return JsonResponse({ 'access_token' : token }, status=200) return HttpResponse(status=403) return HttpResponse(status=402) except KeyError: return JsonResponse({"message": "INVALID_KEYS"}, status=400) I am trying to insert the account data into 'account' variable and the Account.objects.get() is supposed to take either one of 'email', 'username', or 'fullname' - which is decided by the user trying to log in. Is there any method in Python that automatically decides which data is the one given by the user? Thank you so much! -
Nested serializers: Rest API Server Error 500
class RacuniizlaznifinancijskiSerializers(serializers.ModelSerializer): pp = PoslovnipartneriSerializers(many=True, read_only=True) class Meta: model = Racuniizlaznifinancijski fields = ["__all__", "pp"] I want all fields from Racuniizlaznifinancijski and also all fields from Poslovnipartneri... What is wrong here? -
Best way to store user activity in Django
I know this question has been asked before, but this was either from many years ago, or the answers did not quite apply. And please forgive me if this question is vague, I'd be more than happy to edit my question if required. What I want to do is log user activity, so we can track user behaviour in our application for statistical analysis and user behaviour. I imagine this is a very common requirement, but I couldn't really find any good articles on how to do this. The following things are on my mind: There are third party applications dedicated to this purpose, but I intend to keep the data in our own hands. You can extend the Django LogEntry model, but this does not include viewing of objects There are packages like [Django Activity Log 2][1], but they do not include the object relations conveniently like django's logentry does. In the case of using something like the logentry model from django I'm considering using a separate database for this purpose and use either signals or middleware to create the logs. Since some of you must have done this before. I'm really interested in what your approach was. If … -
MultiValueDictKeyError when click the submit button but not choose any file, using Django
I made an input on the HTML File and the HTML code is <form method="post" enctype="multipart/form-data"> {%csrf_token%} <div class="row justify-content-center"> <input type="file" name="document"/> </div> <br/><br/> <center> <input type="submit" value="Upload file" /> </center> </form> and my views.py is if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() file_exist = request.POST.get('document') fs.save(uploaded_file.name, uploaded_file) # --- my another stuff --- else: return render(request, 'index.html') I made a code like that and when running a server that is no problem until I click the submit button by not choose any file (no file is chosen) and I have got an error MultiValueDictKeyError at /creative/ 'document' Request Method: POST Request URL: http://127.0.0.1:8000/creative/ Django Version: 2.2.12 Exception Type: MultiValueDictKeyError Exception Value: 'document' Exception Location: C:\Users\User\Envs\pp\lib\site-packages\django\utils\datastructures.py in getitem, line 80 Python Executable: C:\Users\User\Envs\pp\Scripts\python.exe Python Version: 3.5.5 Python Path: ['C:\Users\User\Desktop\crrnt wrk\Perfect Pitch\PerfectPitch', 'C:\Users\User\Envs\pp\Scripts\python35.zip', 'c:\programdata\anaconda3\DLLs', 'c:\programdata\anaconda3\lib', 'c:\programdata\anaconda3', 'C:\Users\User\Envs\pp', 'C:\Users\User\Envs\pp\lib\site-packages'] Server time: Tue, 19 May 2020 08:55:22 +0000 so how should I solve this problem? Thank you all for your help. -
How to use .schema to display tables that Django creates?
I was following the Django tutorial Writing your first Django app, part 2, it mentions using .schema in the command-line client, sqlite3.exe in my case, to display the tables Django created on running the command python manage.py migrate. I am new to SQLite, and the SQLite tutorial SQLite Describe Table doesn't seem to help me much. Can you elaborate on where and how to look for the tables? -
why django does not find the url?
I'm new to django, and I'm trying to access the following web page by clicking on "dataset celiac" and acces so to "celiac.html". On the html side, here is my code which corresponds to this part of the page where I click on "dataset celiac": <div class="visit"><a href="celiac.html">dataset celiac</a></div> Then, on the views.py side, here is the code corresponding to the view which is supposed to return the html page to celiac.html: def CeliacView(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = forms.CeliacForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required columns = form.cleaned_data['columns'] algo = form.cleaned_data['algo'] if algo == "Logistic regression" and columns == 'CDR3_IMGT': return render(request, 'data/cdr3.html', locals()) else: tableData = get_table_data_to_representation() context = {'form': forms.CeliacForm(), 'tableData': tableData} return render(request, 'data/celiac.html', context) And regarding the urls.py file here is my code: app_name = 'data' urlpatterns = [ path('datasets/', views.SetView, name='datasets'), path('celiac/', views.CeliacView, name='celiac'), ] Finally, here is what django shows me when I click on celiac dataset: Page not found (404) Can someone tell me what … -
Bitbucket pipeline with docker and mysql
I want to implement some CI/CD for a Django web using the bitbucket pipeline. The goal is: Test the Docker builds correctly and next run Django test. But I get this error: django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'127.0.0.1\' (111 "Connection refused")') Here is the bitbucket-pipelines.yml: options: docker: true definitions: services: mysql: image: mysql:5.7 variables: MYSQL_DATABASE: 'foo' MYSQL_USER: 'default' MYSQL_PASSWORD: 'default' MYSQL_RANDOM_ROOT_PASSWORD: 'yes' steps: - step: &test-docker name: "docker builds" services: - docker - mysql caches: - docker script: - export IMAGE_NAME=foo:$BITBUCKET_COMMIT - export CONTAINER_NAME=test-foo - docker build -t $IMAGE_NAME . - docker run -p 8080:8080 --name $CONTAINER_NAME --rm -d $IMAGE_NAME - docker exec $CONTAINER_NAME python /app/manage.py test tests --noinput - docker stop $CONTAINER_NAME pipelines: default: - step: *test-docker I already tried some solutions and workarounds like. Linking the ports from the services and the docker; using volumes; and test the Django outside docker. This one have more problems because it needs 2 DB (original and test) and a user with full access, and using the entrypoint didn't work. -
Multiple views in one url address in Django
The problem is this: I have two classes Posts and Pubs in models.py, I need them to be displayed simultaneously on the main page, I have in views.py file: def pubs_list(request): publications = Pubs.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'app/pubs_list.html', {'publications': publications}) def posts_list(request): posts = Posts.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'app/posts_list.html', {'posts': posts}) in urls.py: path('', views.posts_list, name='posts_list'), # path('', views.pubs_list, name='pubs_list'), accordingly, if we uncomment the second condition, then the first will work. The question is, is it possible to make 2 views have one path, or is it somehow necessary to register in the view? Thanks. -
update quantity number in online shopping cart and change the quantities in storage django
i'm trying to make an online order with django , class Product(models.Model): product_name = models.CharField(unique=True, max_length=50) price = models.PositiveIntegerField() quantity_in_storage = models.PositiveIntegerField() active = models.BooleanField(default=True) class Order(models.Model): cutomer = models.CharField(max_length=50) phone = models.CharField(max_length=13) products = models.ManyToManyField(Product ,through='ProductOrder') date_time = models.DateTimeField(default=datetime.now()) class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ordering = models.ForeignKey(Order, on_delete=models.CASCADE) quantity_order = models.PositiveIntegerField(default=1) active = models.BooleanField(default=True) my forms.py class ProductOrderForm(forms.ModelForm): product = forms.ModelChoiceField(queryset=Product.objects.filter(active=True,quantity_in_storage__gte=1),empty_label='') class Meta: model = ProductOrder fields = ['product','quantity'] def __init__(self,*args , **kwargs): super(ProductOrderForm,self).__init__(*args,**kwargs) for field in self.fields.values(): field.error_messages = {'required':'cant be blank'} class RequiredFormSet(BaseFormSet): def __init__(self,*args,**kwargs): super(RequiredFormSet , self).__init__(*args,**kwargs) for form in self.forms: form.empty_permitted = False ProductOrderFormSet = formset_factory(ProductOrderForm,formset=RequiredFormSet , extra=1) and this is for updating quantity of items in my storage def save_post(sender,instance,created,**kwargs): order_quantity = list(ProductOrder.objects.values_list('quantity_order ',flat=True).reverse().order_by('pk'))[0] if created and instance.active == True: Product.objects.filter( pk=instance.product_id).update(quantity_in_storage=F('quantity_in_storage')-order_quantity) post_save.connect(save_post,sender=ProductOrder) and if someone return back the product all ordered items quantity_in_storage will update successfully def deactive_pre_save(sender , instance , *args,**kwargs): if instance.active == False: Product.objects.filter(pk=instance.product_id).update( quantity_in_storage=F('quantity_in_storage') + instance.quantity_order) pre_save.connect(deactive_pre_save , sender=ProductOrder) but sometimes the user will update the ordered items , for example in my quantity_in_storage i have 10 blue t-shert someone order 3 blue t-shirt in my storage quantity quantity_in_storage remains only 7 blue, but sometimes happens the user … -
Django - pdf response has wrong encoding - reportlab
I'm working on a PDF generator on the Django back-end. I use reportlab. It seems to work, but the encoding is not correct. When I use diacritic characters, it gets the wrong characters/signs. The problem is very similar to: Django - pdf response has wrong encoding - xhtml2pdf But I use reportlab, which allows font adding. I registered in reportlab the font that supports Polish diacritics: "Aleo". pdfmetrics.registerFont(TTFont('Aleo', './resources/fonts/Aleo/Aleo-Light.ttf')) pdfmetrics.registerFont(TTFont('AleoBd', './resources/fonts/Aleo/Aleo-Bold.ttf')) pdfmetrics.registerFont(TTFont('AleoIt', './resources/fonts/Aleo/Aleo-Italic.ttf')) pdfmetrics.registerFont(TTFont('AleoBI', './resources/fonts/Aleo/Aleo-BoldItalic.ttf')) registerFontFamily('Aleo', normal='Aleo', bold='AleoBd', italic='AleoIt', boldItalic='AleoBI') Example outputting pdf in djagno: file_response = Album.pdf_generator(request.user, request.data.get('album_id')) # Make copy to save local pdf file and send via django binary_copy = deepcopy(file_response) with open('test.pdf', 'wb') as f: f.write(binary_copy.read()) content_type = {'pdf': 'application/pdf'} response = HttpResponse(file_response, content_type=content_type) response['Content-Disposition'] = 'attachment; filename=moja_nazwa.pdf' # response = FileResponse(file_response, as_attachment=True, filename='hello.pdf') return response Example two files generate from the same bytesIO: A. Local file B. Shared FileResponse or HttpResponse file: What's strange is if I use the "open with" option after clicking on the link "download" in swagger and I choose some other program, e.g. "wps pdf" I will get other characters in generated pdf.. Opened pdf directly from link from swagger using wps pdf: -
Sort and keep count of data in python
My list of data is like this where I have converted timestamp to an hour, minute, and second and exception that occurred during the time. The data is already in sorted manner and so the order will only be changed if the times(hour, minute, and second) are likewise but the exception name is different. In that case, the data will be sorted in alphabetically order. (for that particular time only) Expected Output : 21:15-21:30 IllegalAgrumentsException 1, 21:15-21:30 NullPointerException 2, 22:00-22:15 UserNotFoundException 1, 22:15-22:30 NullPointerException 1, 22:30-22:45 UserNotFoundException 3, 22:45-23:00 UserNotFoundException 1, 23:00-23:15 NullPointerException 1, 23:15-23:30 UserNotFoundException 1, 23:30-23:45 NullPointerException 2, 23:45-00:00 IllegalAgrumentsException 1, 00:00-00:15 UserNotFoundException 1, 00:30-00:45 NullPointerException 1, 00:45-01:00 UserNotFoundException 1, 01:00-01:15 IllegalAgrumentsException 1, 01:15-01:30 UserNotFoundException 1, 01:30-01:45 NullPointerException 1, 01:45-02:00 IllegalAgrumentsException 1, 02:00-02:15 IllegalAgrumentsException 1, 02:15-02:30 UserNotFoundException 1, 02:30-02:45 NullPointerException 1, 03:00-03:15 IllegalAgrumentsException 1 The data in the following manner. data = {'second': 12, 'data': 'NullPointerException', 'hour': 21, 'minute': 27} {'second': 12, 'data': 'NullPointerException', 'hour': 21, 'minute': 27} {'second': 12, 'data': 'IllegalAgrumentsException', 'hour': 21, 'minute': 27} {'second': 32, 'data': 'UserNotFoundException', 'hour': 22, 'minute': 0} {'second': 12, 'data': 'NullPointerException', 'hour': 22, 'minute': 17} {'second': 52, 'data': 'UserNotFoundException', 'hour': 22, 'minute': 33} {'second': 52, 'data': 'UserNotFoundException', 'hour': 22, 'minute': 33} … -
Apache2 server times out on public IP address
So i have an apache2 server set up to serve a django project and a php one. It used to work just fine until a week ago when it suddenly started timing out on the public IP address. If i use the local IP of the server it seems to be working just fine however whenever I try to access it from outside my local IP using the IP address from whatsmyip.com I get ERR_CONNECTION_TIMED_OUT. I have tried a lot of fixes from various posts on StackOverflow and none of them had any effect. I enabled port forwarding on my router on port 80 (actually it was already enabled since the server used to work just fine until a week ago, but i checked and its still enabled). Also the output of sudo netstat -tulpn | grep LISTEN is as follows: tcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 614/vncserver-x11-c tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 7095/apache2 tcp 0 0 0.0.0.0:8084 0.0.0.0:* LISTEN 447/mono tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 616/sshd tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 3069/cupsd tcp6 0 0 :::5900 :::* LISTEN 614/vncserver-x11-c tcp6 0 0 :::1998 :::* LISTEN 974/java tcp6 0 0 :::22 :::* LISTEN 616/sshd tcp6 0 0 … -
Django Rest Framework: Order by Serializer Method Field
I am currently using Django rest framework 3.11.0 with Django 3.0.6. I am still very new to DRF and I am not sure how to approach this problem. I am trying to apply sort to SerializerMethodField and an enum. I was able to find some documentation that states that I could make my own OrderFilter but I dont know how. Are there any examples I could use? Here is my code. View from rest_framework import generics from V1.assets.models.asset_main import Asset from V1.assets.serializers.asset_serializer import AssetSerializer from rest_framework import filters from django_filters.rest_framework import DjangoFilterBackend class AssetsView(generics.ListCreateAPIView): queryset = Asset.objects.all() serializer_class = AssetSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filter_fields = ['asset_type'] search_fields = ['asset_type', 'asset_properties', 'current_employee_name'] Model class AssetType(models.TextChoices): LAPTOP = 'LPT', _('Laptop') MOUSE = 'MSE', _('Mouse') MONITOR = 'MTR', _('Monitor') AC_ADAPTER = 'ADR', _('AC Adapter') TELEPHONE = 'TLP', _('Telephone') LOCK = 'LCK', _('Lock') HEADSET = 'HDS', _('Headset') class Asset(CreatedModified): asset_type = models.CharField( max_length=3, choices=AssetType.choices, default=None ) asset_properties = JSONField(default=dict) current_employee = models.ForeignKey( Employee, related_name='assets_current_employees', related_query_name='assets_current_employee', default=None, on_delete=models.CASCADE, null=True, blank=True ) class Meta: app_label = 'assets' default_related_name = 'assets' def __str__(self): return self.asset_type Serializer from V1.general.enums import AssetStatus, AssetType from V1.accounts.models.employee_main import Employee class AssetSerializer(serializers.ModelSerializer): current_employee_name = serializers.SerializerMethodField('get_full_name_from_employee') asset_type = serializers.CharField(source='get_asset_type_display') class Meta: … -
django shell not working, is there a problem in my ipython?
./manage.py shell /usr/lib/python3/dist-packages/IPython/core/interactiveshell.py:935: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv. warn("Attempting to work in a virtualenv. If you encounter problems, please " Python 3.8.2 (default, Apr 27 2020, 15:53:34) Type 'copyright', 'credits' or 'license' for more information IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help. Hello, all. does anyone know why this error? I want to type the command python manage.py shell I have installed ipython in virtualenv I still get errors like this -
How to read .pickle files from django app?
I have a django app, and a sentiment analysis model. I created a python module using the model. The model uses .pickle files but when I run the app, I get the following error Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\amitk\appdata\local\programs\python\python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\amitk\appdata\local\programs\python\python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\amitk\Desktop\sentiment_analysis\venv\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "c:\users\amitk\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", … -
Python3 commmands not working in my virtual environment
I have Python-3.8.1 installed in my virtual environment, but still the default version is Python-2.7 only (because of MacOS). Now, whenever I try to run a command starting with "python3", (for my Django project)---like -"python3 manage.py startapp .." or "python3 manage.py runserver", I get this error-->"SyntaxError: Generator expression must be parenthesized" enter image description here -
Django ORM - Please check this multiple table relationship query I'm not sure what I am missing here
Hi there please check the below ORM query and I'm new for ORM, I'm getting this error, AttributeError: Got AttributeError when attempting to get a value for field name on serializer HospitalsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'name'. hospitals = [Hospitals.objects.filter(site_id=_otl.site_id) for _otl in OTL.objects.filter(salesEmail=sales_person_email)] hospital_serializer = HospitalsSerializer(hospitals, many=True) Any suggestions would help thanks in advance. -
How to insert list data in javascript data value
Guys i have javascript line chart: var chart = new Chart(ctx, { type: 'line', data: {labels: ['Oct 2010', 'Oct 2011', 'Oct 2012', 'Oct 2013','Oct 2014'], datasets: [{ backgroundColor: 'blue', , data: [{{a.0}}, {{a.1}},{{a.2}},{{a.3}},{{a.4}}]}] },}); Which works, however i want to make the code more efficient and replicable. so insetad of manually typying {{a.0}} i want to insert the list of a data ( list is in python (django)): a=[23,46,24,35,17] and label where i indicate year : 'Oct 2010' replace by list year: Oct + year list year=[2010,2011,2012,2011,2014] i tried putting a however it did not work and the same with year i tried to put 'Oct + year' How can i achive that ? I would be grateful for your help.