Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django | HTMLField not being saved using TinyMCE
I'm using django-tinymce to save HTML data into a field. Nontheless, the HTML content is not being saved meanwhile the rest of the form is. Also, there are no error messages on the console (python and browser). There is a similar issue and another one which take care of this, however, the solution doesn't work for me. models.py from tinymce.models import HTMLField class Thing(models.Model): field = HTMLField(null=True, blank=True) forms.py from tinymce.widgets import TinyMCE class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class ThingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for form in self.visible_fields(): form.field.widget.attrs['class'] = 'form-control' def save(self, commit=True): data = {} form = super() try: if form.is_valid(): form.save() else: data['error'] = form.errors except Exception as e: data['error'] = str(e) return data class Meta: model = Thing fields = '__all__' widgets = { 'field': TinyMCEWidget(attrs={'required': False,}) } views.py class ThingCreateView(LoginRequiredMixin, CreateView): [model, form, template, ...] def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'add': form = self.get_form() data = form.save() else: data['error'] = "Error" except Exception as e: data['error'] = str(e) return JsonResponse(data) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context The package IS in … -
how to get values from django views to django template script tag
this is my views.py file def xyz(request): year="Dec 24, 2021 10:40:44" return render(request,"abc.html",{"year":year}) this is my HTML file <script> (function () { let birthday = {{year}}, countDown = new Date(birthday).getTime(), x = setInterval(function() { ..... ..... ..... </script> i am not able to accept the value of year in let birthday variable I actually want to make a countdown timer and the problem is the value which I am sending from my python file is not working -
Creating a favourites list in Django, what would be the best option a new model or an array of dictionaries?
So i am just messing around and trying to practise building django apps and trying improve my coding and basically came to think about apps in scale and ease of use and efficiency etc. I was hoping to get advise / answers from the community about what would be best and why that would work best. I hope this is actually the right place to post such a question, if not please let me know where it would be more appropriately posted? So my question is for agruments sake i create a app where users can share quotes and you can save your favourite quotes, just something super basic. But in terms of creating a new model called "Favourites" with fields of; user - fk , quotes - fk or having an array field on the user model, that stores a dict with key value pairs; { quote : "yabadabadoo", url_of_quote : "www.quote-app.com/flintstones" } what would actually be a better option? In terms of scale, say this is so popular and has millions of users, would creating a new model not slow things down or make it the app less efficient as it would have to look for the data, … -
drf-yasg: Image field not displaying in swagger ui
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=MySerializer) @api_view(['POST']) def image(request): profile_img = request.FILES.get('profile_img', '') cover_img = request.FILES.get('cover_img', '') ... pass my_serializer.py: class MySerializer(serializers.Serializer): profile_img = serializers.ImageField() profile_img = serializers.ImageField() Can any one explain the problem? -
Connecting to a Postgres database with Django and sqlalchemy
I'm having trouble with connecting to a Postgres database in a Django Python app. It seems to be using the sqlalchemy library and trying to connect to postgresql+pg8000://username:password@46.195.0.100:5432/dbname?ssl=True. The error I get from Django is the following: TypeError: connect() got an unexpected keyword argument 'ssl' When I tried removing the ssl=True from the database URL, I got the following error message: sqlalchemy.exc.InterfaceError: (pg8000.exceptions.InterfaceError) {'S': 'FATAL', 'V': 'FATAL', 'C': '28000', 'M': 'no pg_hba.conf entry for host "51.2.345.678", user "upeducation", database "upeducationnetwork", SSL off', 'F': 'auth.c', 'L': '489', 'R': 'ClientAuthentication'} (Background on this error at: http://sqlalche.me/e/14/rvf5) I'm doubly confused because I have no idea what that host is in the message: 'no pg_hba.conf entry for host "51.2.345.678" Even though it seems like Django is routing through something else while trying this locally, I'm able to connect to the database with and without SSL on my local machine with a SQL client. -
Django: How to put issue check condition
I am working on a Cylinder management system in which I want to put a check condition that if the cylinder is available then only it can be issued and similarly a cylinder can be returned if it is issued. But was unable to write logic, Please help me out to write the logic for this functionality. here is my models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','available'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) issue_Date=models.DateTimeField(null=True) issue_user=models.CharField(max_length=70,null=True) return_Date=models.DateTimeField(null=True) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return str(self.cylinderId) class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_Date=self.issueDate) CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_user=self.userName) super().save(*args,**kwargs) def __str__(self): return str(self.userName) class ReturnCylinder(models.Model): fill=[ ('Fill','fill'), ('Empty','empty'), ('refill','Refill') ] ava=[ ('yes','YES'), ('no','NO') ] cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) availability=models.CharField(max_length=20,choices=ava) status=models.CharField(max_length=10,choices=fill) returnDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Issued': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(return_Date=self.returnDate) if self.availability=='YES' or self.availability=='yes': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Available') else: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability='Unavailable') if self.status=='refill' or self.status=='Refill': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Status='Refill') super().save(*args,**kwargs) def __str__(self): return str(self.cylinder) -
Centering text in Django Admin list view
In the Django Admin list view, is there an easy way of centering the boolean icons below their headings? Please see the attached image. Thanks not-centered example -
jquery-3.5.1.js:10099 POST http://localhost:8000/pmu_dash/filter/ 403 (Forbidden)
3.5.1.js:10099 POST http://localhost:8000/home/filter/ 403 (Forbidden)". i am trying to post data via js to view.py // myclick function function myClick(){ var table = document.getElementById("meastable"); var rows = table.getElementsByTagName("tr"); console.log("got here"); for (i = 0; i < rows.length; i++) { var currentRow = table.rows[i]; var createClickHandler = function(row) { return function() { var cell = row.getElementsByTagName("td")[0]; var id = cell.innerHTML; alert("id:" + id); var URL="{% url 'home:filter' %}" var data = {'count': id, 'X-csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()}; $.post(URL, data); }; }; currentRow.onclick = createClickHandler(currentRow); } } -
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.