Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Get objects from a squared many-to-many relation
I'm starting a Django project with models like: Vendor <- many to many -> Product <- many to many -> Category Is there an efficient way to get all the categories linked to the products of a vendor ? Current inefficient way: Get all the products of a specific vendor For all products get their specific categories Remove duplicates of the categories list If possible I would like to avoid creating a fake many-to-many relation between Category and Vendor. Thanks in advance, -
Cannot access FileResponse.streaming_content and return FileRespone
The situation: I can return an HTTP response containing a file. I can return an HTTP response containing the hash of the file. I cannot return both the file and the hash at the same time. When trying to access the streaming_content property of a Django FileResponse object, the HTTP request times out and fails to return. This code correctly returns the requested file. class DownloadFile(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: user = request.user most_recent_report = Reports.objects.filter(user_id=user).latest("created_date") most_recent_report_filepath = settings.BASE_DIR + most_recent_report.filepath filename = 'report.pbf' response = FileResponse(request, open(most_recent_report_filepath, 'rb'), content_type='application/json') response['content-disposition'] = 'attachment; filename="%s"' % filename return response except Exception as e: return Response({'status': str(e)}, content_type="application/json") This code correctly returns the SHA256 hash of the requested file. class DownloadFile(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: user = request.user most_recent_report = Reports.objects.filter(user_id=user).latest("created_date") most_recent_report_filepath = settings.BASE_DIR + most_recent_report.filepath filename = 'report.pbf' response = FileResponse(request, open(most_recent_report_filepath, 'rb'), content_type='application/json') response['content-disposition'] = 'attachment; filename="%s"' % filename h = hashlib.sha256() partial_data = b''.join(response.streaming_content) h.update(partial_data) partial_hash = h.hexdigest() return Response({'status': str(partial_hash)}) except Exception as e: return Response({'status': str(e)}, content_type="application/json") This code fails to return anything and times out. class DownloadFile(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: user = request.user most_recent_report = Reports.objects.filter(user_id=user).latest("created_date") … -
Polymorphic model fixtures fail when loading from Django tests
I'm running a few test using fixtures to create initial data I need. The fixtures dump/load correctly to populate the actual db, but when loading the fixtures during tests I get the error: polymorphic.models.PolymorphicTypeInvalid: ContentType 9 for <class 'attributes.models.Attribute'> #5 does not point to a subclass! Here is that fixture: - model: items.item pk: 1 fields: polymorphic_ctype: 12 name: White T-Shirt plural_name: White T-Shirts - model: items.item pk: 2 fields: polymorphic_ctype: 12 name: Black Jeans plural_name: Black Jeans - model: items.item pk: 3 fields: polymorphic_ctype: 11 name: Firebomb plural_name: Firebombs - model: items.item pk: 4 fields: polymorphic_ctype: 10 name: Gold plural_name: Gold - model: items.item pk: 5 fields: polymorphic_ctype: 9 name: Fork plural_name: Forks - model: items.weaponitem pk: 5 fields: {} - model: items.apparelitem pk: 1 fields: {} - model: items.apparelitem pk: 2 fields: {} - model: items.combatitem pk: 3 fields: {} - model: items.materialitem pk: 4 fields: {} Here is the actual line where the test fails: fixtures = ['characters/fixtures/tests', 'items/fixtures/tests', 'skills/fixtures/tests'] user_character = None def setUp(self): human_class = CharacterClass.objects.get(name='Human') self.user_character = UserCharacter.objects.create(name="Ratboi", character_class=human_class) def test_inventory_methods(self): user = self.user_character fork = WeaponItem.objects.get(name='Fork')``` Fails here at last line, getting "fork". The other fixtures load appropriately, but items are the only … -
How do I write a queryset to display all products linked to a category?
I am new to Django and am trying to display my products on a page that are linked to a certain category. I have tried codes such as queryset = Product.objects.filter(category__exact='Badges') Here are my models. class ProductCategory(models.Model): title = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.PROTECT) class Product(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(ProductCategory, null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) image = models.ImageField(upload_to='products/', null=True, blank=True) I am expecting to get the objects in products that are linked to a certain category to print. -
Django python: 'init_command' is an invalid keyword argument for this function
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'bookingsystem'), 'USER': 'root', 'PASSWORD': '', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } When I enter: python manage.py migrate It returns the error: TypeError: 'init_command' is an invalid keyword argument for this function I'm looking to create new tables on my database, but when I reload phpmyadmin through XAMPP nothing changes. I can't seem to figure out the error, so any help is greatly appreciated. I was trying to follow the guide: https://data-flair.training/blogs/django-database/ -
Establish connection to (another) server on server startup
I currently have a requirement where I'll need my Django server to establish a connection to a 3rd party provider (via sockets) and listen for events. The 3rd party uses TCP to send/receive messages and requires me to do some socket programming to integrate their services. What I think is supposed to happen: Django server acts as client socket, 3rd party server will send messages to my Django server and I'll have to appropriately decrypt each message and have respective functions to handle those messages. Things I'm confused about: The correctness of this setup / architecture. Where to place code in Django so that when I run python manage.py runserver my python socket code will execute (the socket.connect($HOSTNAME, $PORT) step) -
Django get Visitor's Location
I am trying to build a Django web application that will store internal tracking metrics (along with doing it's own work). I have so far created models to get API hit counters. I want to check from which location user accessed my application. For that purpose I have to store data in GeoDjango Model. from django.contrib.gis.db import models class AccessLocation(models.Model): location = g_models.PointField() user = models.ForeignKey(User,on_delete=models.PROTECT) class Meta: abstract = True db_table = "location_info" Now I want to capture User's location when they access my views and store in data-base. Is there any django/pythonic way to do it? For eg: hidden form fields that captures user location (latitude and longitude)? -
TypeError at post/4/remove : 'str' object is not callable
I am trying to delete a post(confirm delete) using DeleteView. I run into the below error: TypeError at /post/4/remove/ 'str' object is not callable New to Django-working on a blog application. Other functionalities are working fine but when I attempt to delete a post(confirm delete). I run into the below error: urls.py: http://codepad.org/SP55psyf urlpatterns = [ ... url(r'^post/(?P\d+)/remove/$',views.PostDeleteView.as_view(),name ='post_remove'), ... ] views.py: http://codepad.org/BVsApXhB(complete file) class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') Models.py : http://codepad.org/TLUo4NJG post_confirm_delete.html : http://codepad.org/795iD3RB -
static files not serving in django
I'm trying to deploy my django app since last tuesday using this tutorial , https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 .I redeployed my droplet five times still no avail.Whenever i run collecstatic, it's not showing static files but correctly showing admin styles files. The droplet is live at, https://157.245.108.160:8000 . I'm disapointed from digitalocean . It's a way more easier to deploy at pythonanywhere. Please help me. I also checked twice that files are at correct location -
Django 2.2.6: Reading JSON data returns "None" as output
Trying to send a basic POST request, read the data, and send it back as a response. The JSON data sent looks like this { "user": "user1" } The python code: class User(View): def post(self, request): data = request.POST.get("user") return HttpResponse(data) Expected response: user1 Actual response: None (It prints the word 'None') -
When calling super().save() in overriden save method, model is not updating ManyToManyField
If I have a model with a field that is a ManyToManyField, calling super().save() inside of the overidden save method, the model object is not getting updated if referenced inside of the save method. models.py class AddOn(models.Model): name = models.CharField(max_length=100) class Invoice(models.Model): additional_options = models.ManyToManyField(AddOn) def save(self, *args, **kwargs): super().save() # this prints the objects that were selected prior to the save. # this isn't helpful if the selected objects have changed. print(self.additional_options.all()) -
How to restrict access for staff users to see only their information in Django admin page?
I have created a custom Django admin page. I have two types of users who can access admin page (staff user and superuser). Superuser can see all the users and can change their settings. He can also add or delete users. The staff user can only see their settings and can change some of them. I currently have a problem that staff users can see all users of the web application and can add or delete them. I restricted staff users to see certain settings but could not change it. I do not know how to restrict staff users to see only their settings. Here is my code: Admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserAdminChangeForm, UserAdminCreationForm from .models import UpLoadFile User = get_user_model() admin.site.site_header = 'SRC Orkestracija' admin.site.index_title = 'Administration' admin.site.register(UpLoadFile) class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserAdminChangeForm add_form = UserAdminCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('username', 'superuser', 'active', 'staff') list_filter = ('superuser', 'active', 'staff') readonly_fields = … -
django-simple-history track User from python shell
We are using django-simple-history to track changes in our models. All models have a history = HistoricalRecords() field. When making changes to a model from the python shell, the changes are tracked, however the changed_by field is saved as None. When changes are made in admin, the simple_history middleware grabs the User instance from whoever is logged in. Obviously in shell we don't have that. Is there any way to manually inject the User instance based on an existing Account object? Unfortunately I'm not able to change any of these models, so I can't add any of the history user getters and setters to our models (project manager is very strict about refactoring and we also have a lot of models) -
Role based access control in django
i have a table called stores and for each stores listed inside i need to give access to specific user . How can i achieve this feature in django admin page? admin.site.register(models.StoresDetails, StoresDetailsAdmin) admin.site.register(models.StoreServices, StoreServicesAdmin) admin.site.register(models.StoreImages) -
Unable to display the content of {% block content %}{% endblock %} in Django
I can't display the content of {% block content %}{% endblock %} on my web page. Here is the tree structure: toolbox/ toolbox/ lisa/ templates/ lisa/ lisa.html templates/ base.html Here is the code of base.html : {% load static %} <!DOCTYPE html> <html lang="fr"> <head> </head> <body> <section id="main-content"> {% block content %}{% endblock %} </section> </body> </html> And here is the code of lisa.html: {% extends 'templates/base.html' %} {% block content %} <h2>Bienvenue !</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rhoncus massa non tortor. Vestibulum diam diam, posuere in viverra in, ullamcorper et libero. Donec eget libero quis risus congue imperdiet ac id lectus. Nam euismod cursus arcu, et consequat libero ullamcorper sit amet. </p> {% endblock %} Do you know where it could have come from? Thank you in advance -
How to send signals to consumer in django?
I'm developing websocket programs in Django. I want to receive the request from client(ReactJS) and send signals to websocket consumer, and then websocket consumer send messages to client. How to solve such a problem? I tried as following. urls.py urlpatterns = [ url(r'^updatesignal/$',updatesignal), url(r'^stopsignal/$',stopsignal), ] views.py @api_view(['POST']) def updatesignal(request): print("update") consumers.isconnected = 1 return Response("update signal") @api_view(['POST']) def stopsignal(request): print("stop signal") consumers.isconnected = 0 return Response("stop signal") consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json import asyncio isconnected = 0 class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): print("connect") await self.accept() while isconnected == 1: await asyncio.sleep(2) print("true") # obj = # do_something (Ex: constantly query DB...) await self.send(text_data=json.dumps({ 'message': "aaa" })) async def disconnect(self, close_code): # Leave room group pass async def receive(self, text_data): # Receive message from WebSocket ..... But websocket consumer is fired after 10 seconds after receiving update siganl request. How to solve this problem? -
UWSGI no module named uwsgi
I hope you are doing well. I have problem with import uwsgi Thanks for helping, my rabbitmq is working behind scene dont worry about it I already installed uwsgi which version 2.0.15 and 2.0.18 and i tried still it does not work my purpose is import uwsgi and uwsgi.websocket_handshake( env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '') ) If i can not import uwsgi so i can not use uwsgi.websocker_handshake """Receive messages over from RabbitMQ and send them over the websocket.""" import sys import pika import uwsgi def application(env, start_response): """Setup the Websocket Server and read messages off the queue.""" connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost') ) channel = connection.channel() exchange = env['PATH_INFO'].replace('/', '') channel.exchange_declare( exchange=exchange, exchange_type='fanout' ) # exclusive means the queue should be deleted once the connection is closed result = channel.queue_declare(exclusive=True) queue_name = result.method.queue # random queue name generated by RabbitMQ channel.queue_bind(exchange=exchange, queue=queue_name) uwsgi.websocket_handshake( env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '') ) def keepalive(): """Keep the websocket connection alive (called every 30 seconds).""" print('PING/PONG...') try: uwsgi.websocket_recv_nb() connection.add_timeout(30, keepalive) except OSError as error: connection.close() print(error) sys.exit(1) # Kill process and force uWSGI to Respawn keepalive() while True: for method_frame, _, body in channel.consume(queue_name): try: uwsgi.websocket_send(body) except OSError as error: print(error) sys.exit(1) # Force uWSGI to Respawn else: # acknowledge … -
Django register.tag take a dynamic variable as kwarg
I notice register.simple_tag can easily achieve this but I unfortunately can't make the switch right now to use that and would like to use register.tag to implement this have a tag: register.tag(name='foo') def foo(parser, token): bits = token.split_contents() # rest of code.. template, i have an object that we call bar that needs to be passed into foo. Unfortunately i can't seem to get the dynamic value - the below 1. will just be a string 2. will be a string 1. {% foo arg='bar' %} {{ foo_* }} {% endfoo %} 2. {% foo arg=bar %} {{ foo_* }} {% endfoo %} It looks like I can do {% with b=bar %} {% foo arg=b %} {{ foo_* }} {% endfoo %} {% endwith %} I'm hoping to not have to use a with statement here and have the "token" come over with the bar object rather than just taking the literal of it. -
Why i receive error in automcomplete django admin?
I am trying to use openpyxl library to export django admin files, the export is working 90%, however the values are getting below each other and not filling the whole line This my action def export_as_xls(self, request, queryset): if not request.user.is_staff: raise PermissionDenied opts = self.model._meta field_names = self.list_display file_name = f'{opts.verbose_name}' blank_line = [] wb = Workbook() ws = wb.active ws.append(ExportExcelAction.generate_header(self, self.model, field_names)) for obj in queryset: row = [] for field in field_names: is_admin_field = hasattr(self, field) if is_admin_field: value = getattr(self, field)(obj) else: value = getattr(obj, field) if isinstance(value, datetime): value = convert_data_date(value) elif isinstance(value, bool): value = convert_boolean_field(value) ws.append([value]) # import pdb; pdb.set_trace() response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename={file_name}.xlsx' wb.save(response) return response This my output, the values are a single record -
Update credit card details of user for all subscriptions in Stripe using API
I've created one user using the Stripe API and that customer is subscribed to 5 lessons. Now the user is wanted to change the credit card information. How can I update credit card details in all the subscriptions so that amount will be deducted from the new card using the API? You can give answers in any programming language. -
How to display number of rows and columns of a csv file in a django web app
I want to get a csv file from the user and then simply want to display the number of rows and columns in that file to the user testapp.html: <form method="POST" action="rowcol"> {% csrf_token %} <input type="file" name="file" accept=".csv"> <button type="submit">Upload text</button> </form> views.py: from django.shortcuts import render from django.shortcuts import HttpResponse import numpy as np import pandas as pd def testapp(request): return render(request, 'testapp.html', {}) def rowcol(request): if request.method == 'POST': file = request.POST["file"] dataset=pd.read_csv('file') count_row = dataset.shape[0] count_col = dataset.shape[1] ans=("<H1>%d,%d</H1>",count_row,count_col) return HttpResponse(ans) urls.py: from django.urls import path from testapp import views urlpatterns = [ path('', views.testapp, name='testapp'), path('', views.rowcol, name='rowcol'), ] urls.py in outer folder: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('testapp.urls')), ] -
Logout in Django Rest Framework
Fails to implement the user logout. Here is the code. I'm trying to run from the command line curl -d "" POST http://127.0.0.1:8001/api/v1/users/settings/logout/ But in response I get a 401 error - {"detail": "Authentication credentials were not provided."}. Although the user is logged in. @action(detail=False, methods=['post']) def logout(self, request): print(999) #Nothing try: print(request.user.auth_token) request.user.auth_token.delete() except (AttributeError): pass from django.contrib.auth import logout logout(request) return Response({"success": _("Successfully logged out.")}, status=status.HTTP_200_OK) It seems that the function does not even work ... -
AJAX not working in django production mode?
I've a django app deployed on heroku. In one of the section I asks for feedback and email of the person. If the email is valid email then I just reply Thank you. This is all being done using AJAX from getting values of form to returning thank you. It works fine in developement mode but not in prouction mode. Here's my 'index.js' function valid(email) { var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; return emailReg.test(email); } $(document).on('submit','.Myform',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'', data:{ message:$('#id_message').val(), email:$('#id_email').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function() { let validate = valid($('#id_email').val()); if(validate){ $('.Myform').fadeOut(); $('.thank_you').fadeIn(); } else{ $('.Myform').show(); alert('Please enter valid email address.'); } } }); }); I've only one view in my app. So transferring data of AJAX to that view. Here's my views.py def index(request): if request.method == 'POST': form = FeedbackForm(request.POST) if form.is_valid(): message = request.POST['message'] email = request.POST['email'] print(message) print(email) return HttpResponse('') else: form = ThoughtForm() return render(request,'my_webapp/index.html',{'form':form}) My urls.py file- urlpatterns = [ path('',views.index,name='index') ] In developement mode- It all works well. In production mode as soon as I hit submit button it shows me the loading gif but then it dissappears with no thank you message, no wrong email alert nothing happens and form vanishes The … -
django password change completion fails
I have almost implemented the password reset process, but when I validate the password change I don't end up on the reset complete template and get the template says: The password reset link was invalid... However, the password change has been made and can log in with the new password. It looks the redirection is wrong but I can't figure out why. Here is my urls.py: path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( template_name='news/user/password_reset_confirm.html', success_url='../password-change/done'), name='password_reset_confirm'), path('password-change/done', auth_views.PasswordResetCompleteView.as_view(template_name='news/user/password_reset_complete.html'), name='password_change_done'), Here is my template: {% block content %} {% if validlink %} <p>Please enter your new password twice so we can verify you typed it in correctly.</p> <form method="post">{% csrf_token %} <fieldset class="module aligned"> <div class="form-row field-password1"> {{ form.new_password1.errors }} <label for="id_new_password1">New password:</label> {{ form.new_password1 }} </div> <div class="form-row field-password2"> {{ form.new_password2.errors }} <label for="id_new_password2">Confirm password:</label> {{ form.new_password2 }} </div> <input type="submit" value="Change my password"> </fieldset> </form> {% else %} <p>The password reset link was invalid, possibly because it has already been used. Please request a new password reset.</p> {% endif %} {% endblock %} -
Load multiple images with Javascript from Django backend
I'm working on a d3 based visualization tool that allows users to click paths on images. That works all fine until I tried to let the user change the background image by a simple dropdown. The problem was that javascript can not load files from the disk since to Cross-Origin permissions. So the solution I picked was to set up a backend. I choose Django. This is the javascript code which manipulates the image: window.LOADED_FILE = "PUT PATH HERE"; I have a working dropdown where the user can pick an image and I get then the path to the file. After this, I tried to load the image like the following. window.SVG.append("image") .attr("width", window.WIDTH + "px") .attr("height", window.HEIGHT + "px") .attr("xlink:href", window.LOADED_FILE); This doesn't work at all and I only get a placeholder image for the 404 Request. So tried to following two things: First of all, this is a solution that I found here. This works fine, but I don't want and I cant hardcode every possible image into an HTML file just to pick the correct variable when the user wants to select another image them later when the user wants. So I need a more dynamic solution. …