Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error in django rest api and react in production
i have built rest api with django and deploy it to server , the problem is when i call the api from react in my local machine it works but when i run npm run build and deploy react and django together , i got alot of errors in api like error connection refused and 403 note that i have disabled all security and installed django-cors-headers and i set origin to allow all . so whats the problem now . thank you in advanced -
Refactoring Django model setup advice
As a learning exercise I am creating a way for generate Student Report Cards. I was able to create the desired outcome in the current version by hardcoding each Standard as its own field in the model but there was a lot of repetition and was hoping to improve it. Sample of current models.py with lots of repetition Sample of current forms.py with lots of repetition Current Front-End How can I re-create the formset above with less code? Here's what I'm trying so far but I've come across some issues I can't find a solution to. Any advice would be appreciated. #models.py class ReportCard(models.Model): PROGRESS_INDICATOR = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('NA', 'NA') ] student_perm_number = models.CharField(max_length=51, default='123456789') reporting_year = models.CharField(max_length=10, default='2020-2021') # Grade Received each Trimester standard = models.ForeignKey('reportforms.Standard', on_delete=models.CASCADE, null=True) t1 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) t2 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) t3 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) # Math, Language Arts etc... class Domain(models.Model): name = models.CharField(max_length=100, blank=False) grade = models.ForeignKey(Grade, on_delete=models.CASCADE, blank=True, null=True) # Shapes, Geometry etc... class Standard(models.Model): domain = models.ForeignKey('reportforms.Domain', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100, blank=False, null=True) The form is pretty simple #forms.py class ReportCardForm(ReportCardForm): class Meta: model = … -
How to restrict Endpoint
I am creating a multi-vendor marketplace with django. I have an endpoint for retrieving, updating and deleting a product that belongs to a store like this: localhost:8000/name-of-store/int:product_id. Note: "name-of-code" is the slug of the store. This is the code below: class EditItemAPIView(generics.RetrieveUpdateDestroyAPIView): serializer_class = ItemSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): item = Item.objects.filter(pk=self.kwargs['pk']) print(item) return item With this code, if I append the id of a product that does not belong to a particular store in the url above i.e I do localhost:8000/name-of-store/5, where 5 is the id of a product that belongs to another store, it gets the product. How do I implement some kind of restriction such that if I try append the id of a product not belonging to the shop whose slug is in the url I get a 401 message? Any help will be greatly appreciated. -
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 = [ …