Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I wanted to get data from my django mobels but it's shown error context must be a dict rather than QuerySet
I tried to pull the data from my models but It's return "{'data': <QuerySet [<WareHousePlan: Part ID : 1 Part No : 71398-KK010-00 PartName : HOLDER RR Depart Time : 2020-09-18 22:27:00 Status : True>]>}" which cause TypeError What should I do ? This is my views.py from django.shortcuts import render from django.http import HttpResponse def Home(request): return render(request,'Warehouse/HomePage.html') from .models import WareHousePlan def ShowSchedule(request): data = WareHousePlan.objects.all() context = {"data": data} return render(request,'Warehouse/Showschedule.html',data) -
I get an error when I try to change my upload image function name Django
Here it is my models.py that works. from __future__ import unicode_literals from django.db import models from django.urls import reverse from django.db.models.signals import pre_save from services.utils import unique_slug_generator from PIL import Image def upload_location(instance, filename): return "%s/%s" %('image/service', filename) # Create your models here. class Services(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=250, null=True, blank=True) content = models.TextField(null=True, blank=True) icon = models.ImageField(upload_to=upload_location, blank=True, null=True) category = models.CharField(max_length=255, default='all') def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 320 or img.width > 560: output_size = (320, 560) img.thumbnail(output_size) img.save(self.image.path) def __unicode__(self): return self.title def __str__(self): return self.title def slug_generator(sender, instance, *args, **kargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Services) The problem is when I want to change def upload_location 's name. I tried to use def upload_location_icon as name and I changed the upload_to to icon = models.ImageField(upload_to=upload_location_icon, blank=True, null=True) This is the terminal error How can I change def upload_location name without errors? -
Decorate an inherited method without changing the method
I have this class, which inherits from another class (in this case django-rest-frameworks mixing.RetrieveModelMixin) and I want to use all of the functionality of the given retrieve() function. However I have to decorate it in order to work with swagger. class TestAPI(mixins.RetrieveModelMixin, viewsets.Viewset): model = TestModel serializer_class = TestSerializerClass @swagger_auto_schema(operation_description="TESTTEST") def retrieve(self, request, *args, **kwargs): pass This states that Expected a 'Response', 'HttpResponse' or 'HttpStreamingResponse' to be returned from the view, but received a '<class 'NoneType'>'. This leads me to believe that the "workflow" is stopped at the pass and not passed on to the parent method, which I need. I tried using the super() method with super(TestAPI, self).__init__() instead of pass but this didn't work either. I don't want to change the behaviour of the retrieve method, I just want to decorate it. When I delete the whole reference to it, it works fine. -
Filter Django queryset by related field (with code-value)
Simplifying my model a lot, I have the following: class Player(models.Model): name = models.CharField(max_length=50) number = models.IntegerField() class Statistic(models.Model): ''' Known codes are: - goals - assists - red_cards ''' # Implicit ID player = models.ForeignKey( 'Player', on_delete=models.CASCADE, related_name='statistics') code = models.CharField(max_length=50) value = models.CharField(max_length=50, null=True) I'm using a code-value strategy to add different statistics in the future, without the need of adding new fields to the model. Now, I want to filter the players based on some statistics, for example, players who scored between 10 and 15 goals. I'm trying something like this: .filter('statistics__code'='goals').filter('statistics__value__range'=[10,15]) but I'm getting duplicated players, I'm guessing because that value__range could refer to any Statistic. How could I properly filter the queryset or avoid those duplicates? -
django-tables2 access request.session
I am using django-tables2 to display some product data which is related to the shop the user is in. I store a request.session["current_shop_id"] variable all the time to select which products the user can see/edit. in the view for example: def get_queryset(self): return Product.objects.filter(shop_id = self.request.session["current_shop_id"]) The table uses a customized column with a button: class ShelfActionColumn(tables2.Column): empty_values = list() def render(self, value, record): view = f"""<a href="/device_all/{record.serial}"> <button class="btn btn-secondary">view</button> </a>""" return mark_safe(view) and in the table: class ShelfTable(tables2.Table): actions = ShelfActionColumn(verbose_name = "",) class Meta: model = ShelfStation sequence = ("name", "serial", "shop", "actions") I would like to disable the view button if request.session["current_shop_id"] != shop.id in the table, So a user can not switch shop by choosing a product of it by mistake. -
In Python(3) using Django, is it faster to break JSON into model fields or query JSON fields
Python 3.8 Django Just as the title describes, I'm wondering which is faster in the long run. I'm receiving a JSON response and saving it to a database, then displaying various fields to views. My two thoughts/options are as follows: Break the JSON response into various native database fields such as # models.py class Data(models.Model) title = models.CharField(max_length=200) body = models.TextField() author = models.CharField(max_length=40) # views.py # yes, I know this is not real code, it is pseudo for the sake of making this easier/faster def incoming_data(request): json_data = json.loads(request.body.decode('utf-8')) Data.objects.create( title = json.dumps(json_data['title']) body = json.dumps(json_data['body']) author = json.dumps(json_data['author']) ) Or, I can save the entire thing into one single row on the database as a JSONFeild # models.py class Data(models.Model) json_data = models.JSONFeild(null=True) # views.py def incoming_data(request): json_data = json.loads(request.body.decode('utf-8')) Data.objects.create( json_data = json_data ) To me, it seems easier, more "pythonic" and more "dry" to save everything as a single JSONField, however as models grow and get much, much larger and JSON responses get longer, I'm beginning to wonder which is faster for two scenarios. Saving data to the database. Obviously, with the first option, I'll have to spend extra time parsing the response and saving each … -
How can I pass user token into template and axios in django rest framework?
I'm learning to use Django rest framework and axios so don't mind me if you find this question ignorant. The whole purpose is I want to get current user information so I'm trying to pass the user token to axios in template but I don't how to pass it. I have been trying to google it but haven't find any solution yet. Login and Register are completely done with regular django form. i have this model class CustomUser(AbstractUser): email = models.EmailField(_('Email Address'), unique=True) # some other fields and i have this form class TeacherRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['email', ..] def save(self, commit=True): user = super().save(commit=False) user.save() token = Token.objects.create(user=user) <- how i create token print(token) viewset class CustomUserViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = serializers.CustomUserSerializer permission_classes = (IsAdminUser,) urls.py router = routers.DefaultRouter() router.register('users', views.CustomUserViewSet) urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('api/', include(router.urls)), ] here is my template {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script> <!-- axios --> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"></div> <script> // Teacher new Vue({ delimiters: ["[[", "]]"], el: "#app", data: { teachers: null, }, mounted: function () { this.getTeacherInfo(); }, methods: { getTeacherInfo: function … -
Running into issues when I create ever lasting publisher in Pika
I have a Django website and I want requests coming from it to be always published to RabbitMQ. For that, I'm using Pika BlockingConnection and I keep the connection always open to publish website requests using basic_publish, but when the connection is stale a bit I get the following exception whenever I publish a new message pika.exceptions.StreamLostError: Stream connection lost: BrokenPipeError(32, 'Broken pipe') This is the code I use to manage my connection class ConnectionManager(): connection = None def get_connection(self): if(self.connection and self.connection.is_open): return self.connection params = pika.URLParameters('amqp://guest:guest@rabbit-server1:5672/%2F') self.connection = pika.BlockingConnection(params) return self.connection def get_channel(self, queue_name): if(channel and channel.is_open and self.connection.is_open): return channel channel = self.get_connection().channel() channel.queue_declare(queue=queue_name, durable = True) return channel And for publishing: publisher = ConnectionManager() def publish_message(request_message): publisher.get_channel("queue").basic_publish(exchange='', routing_key="some_key", body=json.dumps(request_message), properties=pika.BasicProperties( delivery_mode = 2, )) How can I maintain a forever running connection that serves my purpose? -
Return a JSON without keep the data in memory
To give an example, let's assume this situation: I have in the database all the car models released from 1950 to today (so a lot of data). In this case I speculated about cars, but it can be literally anything. I want to create an HTTP API (with Python and Django, but the concept is valid for any framework) that returns the name and brand of all the cars I have saved (a JSON list). Clearly querying the database and keeping all cars in memory, then serializing them to JSON is not an option (it would take too much memory). So what's the best way to generate a JSON, from large amounts of data in the database, and then return it via HTTP? Here is a code example to systematize the concept: def get_cars_view(request): my_cars_json = collect_json_without_keep_in_memory(Car.objects.all()) return HttpResponse(my_cars_json) -
DRF, Nested serializers CRUD with the help of intermediate table
To simplify my problem, I have three models A, B, and AB. models.py class A: title = models.CharField(max_length=120) detail = models.TextField() class B: name = models.CharField(max_length=125) xyz = models.IntegerField() class AB: link_a = models.ForeignKey(A, on_delete=models.CASCADE, related_name="a_ab") link_b = models.ForeignKey(B, on_delete=models.CASCADE, related_name="b_ab") class Meta: unique_together = ['link_a', 'link_b'] I am using BSerializer from below's code snippet as my serializer, which is pointed by the view (I think I don't have to mention the view to minimize the code in a question). serializers.py class ASerializer(DynamicFieldsModelSerializer): class Meta: model = A fields = ['title', 'detail'] class ABSerializer(DynamicFieldsModelSerializer): a = ASerializer(fields=['title', 'detail']) class Meta: model = AB fields = ['a'] Class BSerializer(DynamicFieldsModelSerializer): class Meta: model = B fields = ['name', 'xyz'] I have to use BSerializer to create data on models B and AB. The approach I am trying to needs the access to the fields of model A, and also the validation of serializer ABSerializer. To solve the scenario, at first I update the BSerializer (serializers ASerializer and ABSerializer not updated) as follows: try-BSerializer i Class BSerializer(DynamicFieldsModelSerializer): my_a = serializers.ListField(child=ABSerializer(fields=['a']), source='b_ab.all', required=True, allow_empty=True, allow_null=True ) class Meta: model = B fields = ['name', 'xyz', 'my_a'] By doing this, I need to pass data … -
What causes OSError: Bad file descriptor error in python's selenium package?
I use selenium to run django tests and I've never encountered this error before. Out of nowhere, hundreds of my tests began failing (though strangely enough not all of them, and not consistently - if I run tests one at a time, they run fine.) I have no idea why this started happening as there have been no changes to my environment. From the traceback below, it looks like the error is being thrown while setting up the webdriver. Has anybody ever encountered this selenium error before and does anyone know how to fix it? Traceback (most recent call last): File "/Users/daniellong/Documents/Coding/GrubBase/GrubBase/tests/__init__.py", line 174, in setUp self.selenium = webdriver.Chrome() File "/Users/daniellong/Documents/Coding/GrubBase/venv/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__ self.service.start() File "/Users/daniellong/Documents/Coding/GrubBase/venv/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) OSError: [Errno 9] Bad file descriptor -
Django ImageField: directly using file from disk
I have a file on my disk, say: /home/user/file.png And I have a model with a StdImageField (which is similar to the ImageField, just some additional options), more here. models.py: class MyModel(models.Model): image = StdImageField(upload_to="images", variations={"thumbnail": (600,400), "normal": (1000, 600)}, blank=True, null=True) What I'd like to do is programatically "upload" this image. I do not just want to assign the existing path to the field, as I want the image to be stored in the right folder and properly resized. So let's say I have an instance of my model in the variable obj, then I'm trying to do the following: from django.core.files.images import ImageFile open_file = open("/home/user/file.png", "rb") django_file = ImageFile(open_file) obj.image = django_file obj.save() Now at first sight this works well because a) my image gets moved to the right folder images in my media root, and b) the image gets resized properly. However, after this operation the database field with the path to the file turns absolute, containing the entire path to the media root: /src/media/images/file.png But this is not how it normally works -- this is supposed to be relative and only contain: images/file.png Why does it become an absolute field and how to solve this? -
Django User Database Implementation
quick question. I'm playing with Django and mysql. So say I have different societies, each with a sign up page, and lets say a user is able to join multiple societies, how can I be able to see in my database, how many/which societies the user is signed up to? (I was thinking maybe if I could use a field in the database that has a list/array datatype. That would be so convenient. But no such datatype exists. Or maybe a textfield and append to it every new society id that a user joins. Not sure.) -
Axios PUT Request 403 Forbidden when logged into Django
Whenever I am logged into a django user and I try and send a PUT request to my URL I get a 403 Forbidden Error. However, it works both when I am not logged in and also from the Django Rest API client. Here is my code in my frontend: let parameters = `user/${userID}` return new Promise((resolve, reject) => { axios({ method: 'PUT', url: 'http://127.0.0.1:8000/' + parameters, data: updatedUser, headers: { 'Content-Type': 'application/json', }, }) .then((response) => { resolve(response) }) .catch(error => { console.log(error) // reject(error) }) }); I am very confused as I can't see the difference when I am logged into a django user and when I am not, as nothing changes in the frontend. Thanks -
How to change another field value when Clear in Django?
I am working with Django form Updation, but I am facing a small issue, I have 3 fields in form updating, name, image, status, Now if a user uploads an image in the form then the status is automatically changing to 1 in the database. but now if I clear the form using checkbox of the image then this status should be updated 0 in my database here is my forms.py file... class UpdateForm(forms.ModelForm): ... def save(self, commit=True): instance = super(UpdateForm, self).save(commit=False) # Set status if saving picture if instance.image: instance.status = 1 if commit: instance.save() here is my views.py file... def myview(request, id): datas=Product.objects..get(pk=id) form = UpdateForm(instance=datas) if request.method === 'POST' form = UpdateForm(request.POST or None, request.FILES or None, instance=datas) if form.is_valid(): edit = form.save(commit=False) edit.save() return HttpResponse('Success') else: return HttpResponse('Fail') template_name='test.html' context={'datas':datas} return render(request, template_name, context) here is my site.html file... <a href="/media/{{datas.image}}"/>{{datas.image}}</a> <input type="checkbox" name="image-clear" id="image-clear_id"/> Clear When I update this form then it updates 1 in the status field, but if I clear from form then status should be 0 in my database -
How to use django-logpipe?
I am trying to use django-logpipe package to implement Kafka for one of my projects. I didn't find any reference to implement that. Could you please suggest any demo or sample reference document to start with. Thanks in advance :) -
Django Admin action button per each row in ListView
as in this post from hakibenita https://hakibenita.com/how-to-add-custom-action-buttons-to-django-admin , i would have an action button per each row in admin listview. This button should change the status of the book (simply a char field with choices in models), but i want it to do without opening another page, just a click on the button and the status is changed. The status value is choosen from a select and clicking the action button call a javascript to read the select button, the javascript then call the admin page to change the status. I can't do a form, because each row in listview is already in a form. I don't want to use admin action, because this is an action per single object. Here is the relevant code: admin.py: class BookAdmin(admin.ModelAdmin): #... def get_urls(self): urls = super().get_urls() custom_urls = [ path('changestatus/<str:status>/<int:bookid>', self.admin_site.admin_view(self.change_status), name = 'changestatus'), ] return custom_urls + urls def change_status(self, request, bookid=None, status=None): if bookid: book = Book.objects.get(pk=bookid) if status == 'available': book.status = Book.AVAILABLE elif status == 'unavailable': book.status = Book.UNAVAILABLE book.save() newStatus = book.get_status_display() self.message_user(request, 'Changed status to "{}"'.format(newStatus), messages.SUCCESS) url = reverse( 'admin:library_book_changelist', current_app=self.admin_site.name, ) return HttpResponseRedirect(url) def status_button(self, obj): return format_html('{}<br />' '<select id="selectstatus">' '<option value="available-{}">Status available</option>' … -
Why i am facing IndentationError: unindent does not match any outer indentation level?
i am trying to create a E-commerce website in Django and Following a tutorial.My code as like tutorial video but my code doesn't run .It is showing an IndentationError from . import views in urls.py file in my project folder .here is the code Urls.py : from django.urls import path,include from . import views urlpatterns = [ #Leave as empty string for base url path('', views.store, name="store"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), ] An IndentationError **items = order.orderitem_set.all()**in views.py file in my project folder .here is the code views.py: from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order,created = order.objects.get_or_create(customer=customer,complete=False) items = order.orderitem_set.all() else: items =[] context = {'items':items} return render(request,'store/cart.html', context) def checkout(request): context = {} return render(request, 'store/checkout.html', context) I am sharing my Cart.html file here : Cart.html: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="{% url 'store' %}">&#x2190; Continue Shopping</a> <br> <br> <table class="table"> <tr> <th><h5>Items: <strong>3</strong></h5></th> <th><h5>Total:<strong> $42</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="{% url 'checkout' %}">Checkout</a> </th> </tr> </table> </div> … -
How can I get the object when validated, in the clean function?
I need to get an object by slug field in order to check the difference between the number of items sold and purchased. But I get the error: "'NewDateSell' object has no attribute 'kwargs'". How can I make this check differently? class NewDateSell(forms.ModelForm): def clean(self): sell_now=self.cleaned_data['quantity'] item=Item.objects.get(slug=self.kwargs['slug']) if item.item_remainder-sell_now<0: raise ValidationError('The number of items sold must not exceed the number of items purchased') return sell_now -
How to style each form in modelformset_factory
I've trying to style each form in modelformset_factory. But I couldn't do even if I used a table, its unable to save the last (empty form) Here is my view function from django.shortcuts import render from django.forms import modelformset_factory from .models import Offer def offer_forms(request): OfferFormSet = modelformset_factory(Offer, fields=('name', 'url', 'image', 'active')) formset = OfferFormSet() if request.method == 'POST': formset = OfferFormSet(request.POST, request.FILES) if formset.is_valid(): instances = formset.save(commit=False) for form in instances: form.save() formset = OfferFormSet() context = { 'formset': formset, } return render(request, 'offers.html', context) Here is my Html file: {% extends 'base.html' %} <style media="screen"> *{ box-sizing: border-box; } </style> {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} <table class="table table-stripped"> {% for form in formset %} <tr> <td> {{ form }} </td> </tr> <td> <input type="submit" value="Submit" class="btn btn-sm btn-primary"> </td> {% endfor %} </table> </form> {% endblock content %} -
Django Rest API shows only some urls
I have created a polls app with the Django tutorial and have added a REST API, again with the tutorial. I think I have an error somewhere in my urlpatterns config because I can see only some pages, the rest give me an error. My root url.py: from django.urls import path, include from polls import views, viewsets urlpatterns = [ path('', include('polls.urls')), path('polls/', include('polls.urls', namespace="polls")), path('admin/', admin.site.urls), ] urlpatterns += [ path('api-auth/', include('rest_framework.urls')), ] My app-level url.py: from . import views, viewsets from .viewsets import QuestionViewSet, UserViewSet, ResultsViewSet from rest_framework import renderers from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'questions', viewsets.QuestionViewSet) router.register(r'users', viewsets.UserViewSet) router.register(r'results', viewsets.ResultsViewSet) app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), path('', include(router.urls)), ] viewsets.py: from django.utils import timezone from .models import Choice, Question from .serializers import QuestionSerializer, UserSerializer, ChoiceSerializer from rest_framework import generics from django.contrib.auth.models import User from rest_framework import permissions from .permissions import IsOwnerOrReadOnly from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import viewsets class QuestionViewSet(viewsets.ModelViewSet): queryset = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date') serializer_class = QuestionSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] def perform_create(self, serializer): serializer.save(owner=self.request.user) class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class ResultsViewSet(viewsets.ModelViewSet): … -
Flask-Restful request parsers alternatives in Django/Django Rest framework
It's easy to define request parser/validator for query parameters of a GET request using flask_restful.reqparse as below: search_parser = reqparse.RequestParser() search_parser.add_argument('string_param', type = str, required = True, help = 'string_param must be string') search_parser.add_argument('float_param', type=float, required = True, help='float_param must be float') Is there a way to achieve the same thing, e.g. validate if the query parameters present and have the correct type and return 400 otherwise, in Django/Django Rest Framework. Of course, I can retrieve them directly from request.query_param and validate manually but is there a better/leaner way? -
Trying to import js-search library into django project's js file, 404 not found
I am trying to import the js-search library into myapp.js in my Django app. The directory structure is like this: myproject ├── myproject ├── node_modules\js-search └── myapp ├── static\myapp │ └── myapp.js └── templates\search └── index.html In index.html: <script type="module" defer src="{% static 'myapp/myapp.js' %}"></script> In myapp.js: import * as JsSearch from '../../../node_modules/js-search'; Now in the vscode terminal, I get "GET /node_modules/js-search HTTP/1.1" 404 2169 Similarly in my browser console: GET http://127.0.0.1:8000/node_modules/js-search net::ERR_ABORTED 404 (Not Found) Which make no sense because the directory is there. Now interestingly in vscode, on the import line, there is an error hover message: Could not find a declaration file for module '../../../node_modules/js-search'. 'c:/Users/USER/Documents/myproject/myproject/node_modules/js-search/dist/umd/js-search.js' implicitly has an 'any' type.ts(7016) Which doesn't make sense to me either since there are no typescript files anywhere in the js-search library or in my project.. I've been stuck on this for a whole day and just don't understand how node modules work despite trying to research. Also what would be a better way to reference js-search than saying ../../../ ? Thank you. -
video streaming plate-form with membership
As mentioned in the title I want to implement a e-learning platform like Udemy with payed membership subscription to stream video safety ( DRM, Obfuscation, ... ), but I don't know how to do that and if I can do that with Django and Flutter or I have to chose a another framework like express or any go framework and reactjs or vuesJS. I don't have lot of time so I want use framework that already have stuff build on it packages or something like that ( for stream the video securely ) and have documentation on that. if you have any suggestion or article or tutorial to propose, please refer them to me as a comment. by the way sorry for my bad English 🖐 -
Base template for Node.js and Express similar to Django
In Django there is a really useful tool i.e, using base template for stuff like navbar which makes it really fast for development and also avoids a lot of redundant code since we can neglect including stuff like navbar each time in different pages of a web-app. Also if there is any change to make in navbar, I need not have to change it everywhere but base template. I want to know if there is a similar functionality for Node.js + Express.