Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I render multiple datasets for charts js in Django?
My view: from django.shortcuts import render from django.apps import apps Item = apps.get_model('inventory', 'Item') Cancellations = apps.get_model('cancellations', 'Cancellations') def chart_display(request): labels = [] data = [] queryset = Item.objects.all() for item in queryset: labels.append(item.item_name) data.append(item.quantity) data = { 'inv_labels': labels, 'inv_data': data, } return render(request, 'pie_chart.html', data) My HTML: <div class="grid-container"> <div class="inv-class"> <h2>Inventory Stats</h2> <canvas id="inventory-chart"></canvas> </div> <div class="item2"> <h2>Cancellation Stats</h2> <canvas id="layanan_subbagian"></canvas> </div> </div> <script> $(function () { var data = { type: 'bar', data: { datasets: [{ data: {{ inv_data|safe }}, backgroundColor: [ '#3c8dbc', '#f56954', '#f39c12', '#ff0000', '#008000', ], label: 'Quantity' }], labels: {{ inv_labels|safe }} }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('inventory-chart').getContext('2d'); window.myPie = new Chart(ctx, data); } }); </script {% endblock content%} My question is what would be the best way to render the data from a different model but on the same page? When I make a second dataset in my chart_display view and try to render it alongside the first, it doesn't render. I tried changing my view to: def chart_display(request): inv_labels = [] inv_data_qs = [] queryset = Item.objects.all() for item in queryset: inv_labels.append(item.item_name) inv_data_qs.append(item.quantity) inv_data = { 'inv_labels': inv_labels, 'inv_data': inv_data_qs, } can_labels … -
Remove specific instance when serializing multiple objects (many=True) and one of them has an error
I've a serializer similar to this: class ExampleSerializer(serializers.ModelSerializer): attr3 = serializers.SerializerMethodField() class Meta: model = ModelExample fields = ["attr1", "attr2", "attr3"] def get_atrr3(self, instance): try: # Do something except Exception: raise I'm a serializing a list of objects. ExampleSerializer(object_list, many=True).data Is there a way to exclude instances raising errors when serializing.. so I still get the rest of the correct object in the list serialized anyways? Btw, I can't pre-filter the object_list in order to exclude the problematic items. -
Could not parse the remainder in Django If/else statements in templates
I have a couple if/else statements that all seem to return this same parse error regardless of what page or other content exists on the page. For all intents and purposes have dumbed it down. My actual logic makes sense, don't worry, I just want to know what of my syntax is causing this problem: <div> {% if True and 10 - 1 > 5 %} <p>1</p> {% else %} <p>2</p> {% endif %} </div> When I do the above, I expect it to show the <p>1</p> tag but instead returns a "TemplateSyntaxError at " URL, Could not parse remainder: '-' from '-'. -
How do I get an item into a hidden form field in django?
I guez whatever I'm unable to do is possible for many of us here. I have a form and a view. I'd like to pass a value from a forloop into the form silently as a hidden field. def new_issue_book(request,pk): if request.method == 'POST': form = NewIssueForm(request.POST,school= request.user.school,pk=pk) if form.is_valid(): name = form.cleaned_data['borrower_id'] form.save(commit=True) books = Books.objects.filter(school = request.user.school).get(id=pk) semest = Student.objects.filter(school = request.user.school).get(student_id=name).semester departm = Student.objects.filter(school = request.user.school).get(student_id=name).depart Books.Claimbook(books) return redirect('view_issue') else: form = NewIssueForm(school= request.user.school,pk=pk) return render(request, 'new_issue_book.html', {'form': form}) The model form class NewIssueForm(forms.ModelForm): def __init__(self,*args, pk,school, **kwargs): super(NewIssueForm, self).__init__(*args, **kwargs) self.fields['borrower_id'].queryset = Student.objects.filter(school=school) self.fields['book_id'] = forms.ModelChoiceField(queryset=Books.objects.filter(id = pk)) class Meta: model = Issue fields = ['book_id','borrower_id'] -
Jira API django connection adapters error
Not sure what this django error is trying to tell me. If I hardcode that URL into the jira object, a request is sent to the Jira api and there is no error. If I do it via postman and a viewset, it errors with: No connection adapters were found for "['https:/uk- ssdo.atlassian.net']/rest/agile/1.0/board?maxResults=50" i.e jira = Jira( url='https://uk-ssdo.atlassian.net/', username='paul.macdonald@uk-ssdo.net', password='<password>', cloud=True, ) -
Django - TypeError: must be real number, not F (annotate)
I'm trying to create a method that returns a QuerySet or parcels with their distance from a given point (by LAT, LNG). The problem is that it returns error: @classmethod def get_closest_parcels(cls, lat: decimal.Decimal, lng: decimal.Decimal, county=None) -> ParcelQuerySet: return Parcel.objects.annotate(distance=point_dist(lat, lng, F('lat'), F('lng'))) ERROR geo.pyx in h3._cy.geo.point_dist() TypeError: must be real number, not F My goal is to find 5 closest parcels. Do you know how can I do that using Django ORM? -
how can i align my radio button like 2 in a row in Django Template
{% for t in test%} <label> <input type="radio" name="radio" checked/> <span class="choice">{{t.choice}}</span> </label> {% endfor %} this is my code for printing n numbers of radio button and I want to format them 2 in a row but it gets difficult because we have a loop. What should I do to display 2 radio button in a single line. -
How to combine multiple websocket streams into a unique stream with Python?
I have a trading application that monitor market order books with websocket streams (s1, s2, s3, etc). The application also manages user accounts and all accounts should monitor the all streams (s1, s2, s3). Up to now I'm able to monitor these streams with a single account but I would like to find a solution to avoid establishing the same WS connection with all the accounts. How can I do that ? Do you think it's a good idea to combine all websocket streams into a single stream and then serve that stream to the user accounts with a websocket server ? or maybe there is an alternative ? This is how my asyncio code looks like : import asyncio import traceback import nest_asyncio nest_asyncio.apply() async def watch_book(i, j, client, market): loop = 0 while True: try: ob = await client.watch_order_book(symbol) if ob: loop += 1 if loop == 50: break print(loop, market.symbol) # <- I get all streams here await client.sleep(5000) except Exception as e: traceback.print_exc() raise e async def create_client(j, loop, exchange, default_type): client = getattr(ccxtpro, exchange.exid)({'enableRateLimit': True, 'asyncio_loop': loop, }) # configure client for market if account.exchange.default_types: client.options['defaultType'] = default_type # Filter markets to monitor markets = … -
Django REST User Login
I am looking to login a user with a username and password in django. This is my code: if request.method == 'POST': username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user=user) return Response({'Message': "Success!"}, status=status.HTTP_200_OK) else: return Response({"Message": "Invalid"}, status=status.HTTP_400_BAD_REQUEST) The authentication works fine, but when i go to login i get this: AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request`. I am using the rest API, and my request looks like this function login() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json", 'X-CSRFToken': getCookie('csrftoken') }, credentials: 'include', body: JSON.stringify({ username: username, password: password, }), }; fetch("/users/login/", requestOptions) .then((response) => response.json()) .then((data) => setStatus(data.Message)) } Would anyone know how to create a django request to log the user in? Thanks! -
Django pass request to to_representation method
I want to override the serializer's to_representation. How can I pass the request object in it so I can build url? class FooSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() link = serializers.SerializerMethodField() class Meta: model = Foo fields = ('name', 'link') def to_representation(self, instance): request = self.context.get('request') # Get request here return {'foo': request.build_absolute_uri( '/apps/foo/{}'.format( object.id)) } -
Python unittest.TestCase - Create a code that passes the test below
I am learning about tests and I was wondering if someone could me give an example of how to create a codebase on the test unit. I need to create a code that passes that test. class TestStringMethods(unittest.TestCase): def test_blank_index(self): self.assertEqual(index("/blank_index/", "demo.ed.com", False), { "css": ["/m/corp22/css/toolkit.min.css", "/m/build/student/student.css"], "js": ["/m/build/manifest.js", "/m/build/vendor.js", "/m/build/student.js"], }) Thanks :) -
django reverse to multiple page id
I use the same modal forms in different pages to fill some database entry. My problem is I don't know how to use "reverse" so it bring me back to the right page on success. views.py: class StorageLocationCreateView(LoginRequiredMixin, BSModalCreateView): template_name = 'inventory/storagelocation_create_form.html' form_class = StorageLocationModalForm success_message = 'Success: storage Location was created.' success_url = reverse_lazy("page1") Here my code can only send back to page1 weather i'm calling the modal from page1 or page2. How can reverse to the good page dynamically ? -
How to upload image from Django Rest Framework?
I am new to django-rest-framework. I am using DRF and drf-yasg Swagger. Can any body help to upload image from request body? I am not able to upload image from request body. My current view.py: @swagger_auto_schema(method='post', request_body=openapi.Schema(type=openapi.TYPE_OBJECT, properties={ 'profile_img': openapi.Schema(type=openapi.TYPE_FILE, description='Profile Picture.'), 'cover_img': openapi.Schema(type=openapi.TYPE_FILE, description='Cover Photo.') }) ) @api_view(['POST']) def image(request): profile_img = request.FILES.get('profile_img', '') cover_img = request.FILES.get('cover_img', '') ... pass I tried creating new serializer class but upload image field is not being displayed in swagger form. -
Context not rendering on template
im trying to create a live search using django, AJAX and JQuery, so far i managed to livesearch form my db but when i return the context it doesn't render. However if i use chrome develorper tools, i can see the html in the response with the context properly rendered. I dont know why this is happening, perhaps because im not calling the view correctly my code looks something like this: home.html {% extends 'base.html' %} {% block content %} <input type="text" id="livesearch" placeholder="Ingresar Usuario Aqui"><br> {{list_users}} {% for u in list_users %} <p>{{u}}</p> {% endfor %} {% load static %} <script src="{% static "jquery/jquery.js" %}"></script> <script src="{% static "jquery/plugins/jquery.cookie.js" %}"></script> <script> $(document).ready(function(){ $("#livesearch").on('input', function(e){ search_text = $("#livesearch").val() // console.log(search_text) $.ajax({ method:'post', url:'', data:{text:search_text}, beforeSend: function(xhr, settings){ xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken')); }, }) }) }) </script> {% endblock %} home_view.py def home_view(request): searchtext = request.POST.get('text') searchtext = str(searchtext).upper() print(searchtext) query = '''select NAME from my_base where status not in('Disabled', 'Locked') and upper(domain_login) LIKE ''' + "'%{}%'".format(searchtext) cursor = method_that_gets_the_cursor() cursor.execute(query) users = cursor.fetchall() list_users = pd.DataFrame(users) context = { "list_users": list_users } return render(request, "home.html", context) urls.py from django.contrib import admin from django.urls import path from add_users.views import home_view urlpatterns = [ … -
Django 3.2 aws beanstalk can't load static file
I have website on aws beanstalk with nginx . When i push my code i can't load css and js .I have this erreur MIME (« text/html ») incorrect (X-Content-Type-Options: nosniff) i follow this tuto Deploying a Django application to Elastic Beanstalk on my code i have this STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) else: STATIC_ROOT = os.path.join(BASE_DIR, "static") and i run before push on prod python manage.py collectstatic for my beanstalk conf WSGIPath:mysite.wsgi:application DJANGO_SETTINGS_MODULE:mysite.settings -
Executing Python script on dropdown change in Django?
I have a simple Python script, simple_script.py that simply prints a string with the current datetime: import datetime print(f"Current time is: {datetime.datetime.now()}") The script file is placed in a folder called scripts in the django projet's main folder. On the site, I merely have a dropdown field (<select>) and a button. I want to have this script run every time the user changes the dropdown field, i.e. without the need to press the button (the button won't even be necessary - it's only here for demonstration purposes). I managed to implement the version where running the script depends on pressing the button. My home.html: <form action="/external/" method="post"> {% csrf_token %} <select> <option>---</option> <option>1</option> <option>2</option> <option>3</option> </select><br><br> {{data1}}<br><br> <input type="submit" value="Execute Custom Py Script"> </form> My views.py: import sys from django.shortcuts import render from subprocess import run, PIPE def external(request): out = run([sys.executable, "scripts/simple_script.py"], shell=False, stdout=PIPE) return render(request, 'appName/home.html', {'data1': out.stdout.decode('utf-8')}) And I added the following path declaration to my url.py: path('external/', views.external, name='external'), Right now, upon pressing the button, the {{data1}} tag gets filled up with the string returned from simple_script.py. To get to my goal, I realize I likely need JavaScript, so I added an onChange attribute to the … -
Django test validation isdigit
How to test ValidationError when User inserts Text for my zip code example? This is my validation in my models.py file: def validate_zip_code(value): zip = str(value) if not zip.isdigit(): raise ValidationError('Please enter a valid zip code.') And my test file in test_models.py class TestPLZ(TestCase): def test_zip_code_digit(self): self.assertRaises(ValidationError, validate_zip_code, 'Random Text') Running python.manage.py test I get no Errors, but when I run coverage html I can tell that this function has not been tested properly. -
Django Button to Update 'status' / BooleanField on Database
i have this model in order apps class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='items', on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, related_name='items', on_delete=models.CASCADE) vendor_paid = models.BooleanField(default = False) price = models.DecimalField(max_digits=16, decimal_places=0) quantity = models.IntegerField(default=1) def __str__(self): return '%s' % self.id def get_total_price(self): return self.price * self.quantity i have this button in vendor apps in vendor_admin.html <a href="{% url 'status_update' %}" class="button is-success is-uppercase">Confirm</a> i want to update the vendor_paid = models.BooleanField(default = False) from false to true when i click that button. the problem is i dont know what to write inside def in vendor views.py @login_required def status_update(request): ? return redirect('vendor_admin') -
Using UUID in View_Detail page in Django
I have an app that is working fine, but i just changed the ID to UUIDm and the route no longer work. I have the following route: path("documents/uuid:uuid/",views.document_show, name="document_show"), and the following view: def document_show(request, id): student_list = DocumentAttachment.objects.all() for student in student_list: print("we are printing the list of imaged uploaded :", student.attachment) context = {} try: context["data"] = Document.objects.get(id=id) except Document.DoesNotExist: raise Http404('Book does not exist') return render(request, "documents/show.html", context) With the architecture: template/documents/show.html May I ask what is the right way to setup the routes please? -
Django Q Tasks - putting Q_CLUSTER outside settings file
Hi/I am new in this useful library. What I need to do is using Q_CLUSTER dictionary values outside of (let's say) plain old settings.py (Because of a necessity to change these values in demand in different setting files) . The problem is 'C:\Python38\Lib\site-packages\django_q\conf.py' is being loaded long before the application is being executed and inside this conf.py file there are q_cluster assignments to settings.py such as : class Conf: """ Configuration class """ try: conf = settings.Q_CLUSTER except AttributeError: conf = {} Does anyone have idea how I can manage this task without changing site packages? Thanks in advance for help -
Why is django getting stuck on loading a template that doesn't exist?
I've made some changes to my website's theme and have come across an issue. My previous landing page was called home.html. It worked fine. I have since changed it, retired the old pages (moved them to another folder), and put a new set of pages in my template/app/ folder. The new landing page is index.html. I have changed it in urls.py, and in views.py. I come across this error, Django still wants to access or load main/home.html. I don't understand why, even after changing it to return a HttpResponse, it still wants to render a template? What's going on? Environment: Request Method: GET Request URL: https://website.com Django Version: 3.1.4 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/dist-packages/django/contrib/admin/templates/main/home.html (Source does not exist) * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/dist-packages/django/contrib/auth/templates/main/home.html (Source does not exist) * django.template.loaders.app_directories.Loader: /var/www/app/main/templates/main/home.html (Source does not exist) Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/app/main/views.py", line 103, in homepage return HttpResponse("well?") File "/usr/local/lib/python3.6/dist-packages/django/shortcuts.py", … -
Use FactoryBoy's Maybe declaration without a "decider" model field
Is it possible to use FactoryBoy.Maybe where the "decider" does not map to an actual model field? Consider the following model: class MyModel(models.Model): is_heavy = models.BooleanField() weight = models.PositiveIntegerField() This factory works: class MyModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel is_heavy = factory.Faker("boolean", chance_of_getting_true=50) weight = factory.Maybe( "is_heavy", yes_declaration=factory.Faker("pyint", min_value=0, max_value="10"), no_declaration=factory.Faker("pyint", min_value=10, max_value="20"), ) But what if I don't want the "decider" to map to an actual field of MyModel? Something like: class MyModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel is_heavy = factory.Faker("boolean", chance_of_getting_true=50) weight = factory.Maybe( factory.Faker("boolean", chance_of_getting_true=50), yes_declaration=factory.Faker("pyint", min_value=0, max_value="10"), no_declaration=factory.Faker("pyint", min_value=10, max_value="20"), ) That factory doesn't work. (Note that it used to work prior to this version and this PR.) -
Using BeautifulSoup for web scraping: ValueError obtained
This is my first time asking a question on this platform. I have the following error: ValueError at /scrape/ dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: http://localhost:8000/scrape/ Django Version: 2.2.17 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 1; 2 is required Exception Location: c:\Users\toshiba\Desktop\newsscraper\news\views.py in scrape, line 32 Python Executable: C:\Users\toshiba\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.2 Python Path: ['c:\Users\toshiba\Desktop\newsscraper', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib\site-packages', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib\site-packages\win32', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib\site-packages\win32\lib', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib\site-packages\Pythonwin'] I am trying to scrape news articles from guardian.ng, but it seems to keep giving me an error. This is my views.py file: # import all necessary modules import requests from django.shortcuts import render, redirect from bs4 import BeautifulSoup as BSoup from news.models import Headline requests.packages.urllib3.disable_warnings() # new function news_list() def news_list(request): headlines = Headline.objects.all()[::-1] context = { 'object_list': headlines, } return render(request, "news/home.html", context) # the view function scrape() def scrape(request): session = requests.Session() session.headers = {"User-Agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"} # This HTTP header will tell the server information about the client. We are using Google bots for that purpose. # # When our client requests anything on the server, the server sees our request coming as a Google bot. url … -
How to update model's property value in Django's shell?
I have a such a model: class Territory(models.Model): voivodeship = models.IntegerField(null=True, blank=True) powiat = models.IntegerField(null=True, blank=True) gmina = models.IntegerField(null=True, blank=True) type = models.IntegerField(null=True, blank=True) name = models.CharField(max_length=500) type_name = models.CharField(max_length=100) comparison_group = models.ForeignKey(ComparisonGroup, on_delete=models.SET_NULL, related_name='territories', null=True, blank=True) partnership = models.ForeignKey(Partnership, on_delete=models.SET_NULL, related_name='member_territories', null=True, blank=True) class Meta: unique_together = ('voivodeship', 'powiat', 'gmina', 'type') verbose_name = 'Jednostka terytorialna' verbose_name_plural = 'Jednostki terytorialne' def __str__(self): return f'{self.name} - {self.type_name} ({self.code})' @property def code(self): if self.voivodeship and self.powiat and self.gmina and self.type: return f'{self.voivodeship:02}{self.powiat:02}{self.gmina:02}{self.type}' return '--' And now some of those Territories have code attribute as --, because self.gmina and self.type were NULL in the DB. Then I updated some rows -- added values for self.gmina and self.type for some of the territories units and I want to update their code attributes. I tried: territories = Territory.objects.filter(type_name='some type name') for t in territories: t.code = <some calculated value> but I get an error kind of: Traceback (most recent call last): File "<console>", line 3, in <module> AttributeError: can't set attribute How can I make Django recalculate this code value for all items in Territory model? -
Trying to upload a file via api
I want to programmatically upload a pdf file to an APP via API, from a Python + Django APP. Their documentation says: “In order to upload an invoice you must do a POST as from.data with key type “file” and value fiscal_document that refers to the file you are attaching.” curl -X POST https://api.mercadolibre.com/packs/$PACK_ID/fiscal_documents -H 'Content-Type: multipart/form-data' \ -H 'Authorization: Bearer $ACCESS_TOKEN' \ -F 'fiscal_document=@/home/user/.../Factura_adjunta.pdf' I´m trying to achieve this using requests as follows: response = requests.request("POST", url, headers=headers, files={'fiscal_document': my_file_url}).json() But I get the following response { "message": "File cannot be empty", "error": "bad_request", "status": 400, "cause": [] } Is my request call ok? In the example there is a local path declared, but I need to get the file from an URL. Should I keep the “@” in the -F 'fiscal_document=@/home/user/.../Factura_adjunta.pdf'? Should I upload a byte type? And clues welcome. Thanks in advance.