Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
invoke data from view after database operation in django
I have a model named "Routing_Dest_Area", i need to get the destinationId from that table and using that value I need to write another query in the same view function itself.I have written the query but don't know how to pass this value to the next query as argument.Pleaae help me to solve . ...models.py....... class Routing_Dest_Area(models.Model): areaDigit = models.IntegerField(primary_key=True) destinationId = models.IntegerField() destinationName=models.CharField(max_length=30) def __str__(self): return '%d' % (self.destinationId) class Routing_Point(models.Model): destinationId = models.IntegerField() productId=models.CharField(max_length=30) routingPointId= models.IntegerField() routingPointName=models.CharField(max_length=30) ...view.py..... def get_route_list(request): data={} if request.method == "POST": areaDigit = request.POST['areaDigit'] destination_id=Routing_Dest_Area.objects.get(areaDigit=areaDigit) data={'test1':Routing_Point.objects.get(destinationId=destination_id)} else: data = '' return render(request, 'routing/test.html',{'data':data}) -
Add custom fields to Django Rest
I am subclassing Django's rest framework APIException class to create my custom API exceptions. For example, one of my exceptions look like this: class Unauthorized(APIException): status_code = 401 default_detail = 'You have to login first.' default_code = 'ERR_UNAUTHORIZED' And I've written a custom exception handler to modify key names. This is the part in my exception handler that deals with these kinds of exceptions: def custom_exception_handler(exc, context): response.data['code'] = response.data['detail'].code response.data['message'] = response.data['detail'] print(response.data) del response.data['detail'] return response As a result, the output for my exceptions looks like this : { "code": "ERR_UNAUTHORIZED", "message": "You have to login first." } What I want to do now is that I want to add a new field to my exceptions so that my exception output looks like this: { "code": "ERR_UNAUTHORIZED", "message": "You have to login first.", "another field" : "extra data" } I'm quite new to Django and I've searched about this and also tried to add the "another field" to my custom exception class fields but that couldn't solve my problem. Are there any ways to do something like this? -
Using the Django authentication system within a React SPA
I'm currently developing an application based on React and Django. I'm using Django rest Framework to create REST APIs that are consumed in the React frontend. This works pretty well. I'm now willing to implement authentication using Django session authentication system for the application. I could create authentication APIs. However I would prefer using Django authentication system. How can I use Django authentication views and forms in a React SPA? A code snippet describing the overall architecture would be much appreciated. I can't figure out how to have the React app "calling Django code" (apart from DRF APIs)! My question is about authentication, but I could reuse the same mechanism for other Django views. -
Django channels consumer freezes
I'm trying to create a Django Channels consumer which receives some data in real time from a RabbitMQ queue and then sends this data to a frontend. Here is my consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='Test') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume( queue='Test', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') await self.send({ "type": "websocket.accept" }) await channel.start_consuming() async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) And here is my Javascript code: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ wsStart = 'wss://' } socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("message", e) } socket.onerror = function(e){ console.log("message", e) } socket.onclose = function(e){ console.log("message", e) } </script> The problem with this code is that, altough in my console i will see the queue waiting for data, on my HTML page i won't see any message appear when the connection is opened; even more, … -
In Django, how do I aggregate one annotation result by another?
Here's a tricky operation that I've been working on. I have the following: users.values('first_name').annotate(demo=F('demo_responses__demographic__display'), response=F('demo_responses__option__display')) When I run this, I get something like the following for results: [ {'first_name': 'Bob', 'demo': 'Business Category', 'response': 'Engineering'}, {'first_name': 'Bob', 'demo': 'Job Function', 'response': 'Training'} {'first_name': 'Joe', 'demo': 'Business Category', 'response': 'Restaurant'}, {'first_name': 'Joe', 'demo': 'Job Function', 'response': 'Server'} ] What I would like to do is compress these into the following: [ {'first_name': 'Bob', 'Business Category': 'Engineering', 'Job Function': 'Training'}, {'first_name': 'Joe', 'Business Category': 'Restaurant', 'Job Function': 'Server'}, ] Having it in this format would be helpful for some of the reports I'm generating. I know that I can do this programmatically, but I didn't know if there was some Django query magic that I could use to get there faster. Any ideas? -
Django - Filtering Related Sets in Templates
I have two models; class Customer(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() class WorkOrder(models.Model): date_created = models.DateField('Date', default=datetime.now) due_date = models.DateField('Due Date') customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='Customer') STATUS_CHOICES = [ ('pending', 'Pending'), ('approved', 'Approved'), ('completed', 'Completed'), ('cancelled', 'Cancelled'), ] status = models.CharField('Status of the work order', max_length=10, choices=STATUS_CHOICES, default='pending') description = models.TextField('Description of the work') I wrote a class based list view to make a customer list: class ReportCustomerListView(ListView): model = CustomUser template_name = 'reports/customer_report.html' def get_queryset(self): return CustomUser.objects.filter(is_staff=False).filter(is_superuser=False) I would like to prepare a report for the user about its customers so I wanted to show how many pending, approved and completed work orders a customer have. My list template is; <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Company</th> <th scope="col">Pending Work Orders</th> <th scope="col">Active Work Orders</th> <th scope="col">Completed Work Orders</th> <th scope="col">Draft Bills</th> </tr> </thead> <tbody> {% for customer in object_list %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ customer.first_name }}</td> <td>{{ customer.last_name }}</td> <td>{{ customer.company.company_name }}</td> ... ... ... // the part where I am stuck But I am lost after that after 4 hours of reading I am more confused. I know I can access work orders … -
OSError: [Errno 30] Read-only file system: '/[Path to project]' on mac
I am trying to set up django-silk in my django project and I keep running into this issue when I run python manage.py collectstatic. I have tried creating a new virtual environment and trying again but I get the same error. But if I were to create a new django project with only Dango Rest Framework and Silk everything works fine. I have been stuck on this issue for several days. Can anyone help? -
Count CheckBox in Django-tables2 table and Rendering
I want display the actual sum of checked box with a table by django-tables2. Table Structure class GeneralTable(tables.Table): """ GeneralTable Class """ id = "" s = tables.CheckBoxColumn(accessor="id", attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False) column_default_show = ['s'] export_formats = ['csv', 'xls'] class Meta: """ Meta Class """ attrs = {'class': 'table table-sm table-hover table-bordered table-striped table-condensed'} Table Generate table = GeneralTable(data) print(table.as_html(request)) Table html <table class="table table-sm table-hover table-bordered table-striped table-condensed"> <thead > <tr> <th class="s"> <input type="checkbox" onclick="toggle(this)"/> </th> </tr> </thead> <tbody > <tr class="even"> <td class="s"><input type="checkbox" name="s" value="386"/></td> </tr> </tbody> </table> HTML code I try to build a javascript function but the function render the count of the checked box (as excepted) but when i count all the checkboxs with the checkbox in the header columns, it's not working like in the image below. <p id="result"><p> {% block table%} <div class="row" style=" white-space: nowrap;"> {% load django_tables2 %} {% render_table table %} <br/> </div> <script> showChecked(); function showChecked(){ document.getElementById("result").textContent = "Total Number Selected = " + document.querySelectorAll("input:checked").length; } document.querySelectorAll("input[name=s]").forEach(i=>{ i.onclick = function(){ showChecked(); } }); </script> -
ModelBackend authenticate doesn't receive credentials when using Admin Panel
I've setup a custom backend with the following configuration: Settings.py; REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'users.backends.CustomUserBackend', 'django.contrib.auth.backends.ModelBackend', ), } AUTHENTICATION_BACKENDS = ('users.backends.CustomUserBackend',) backends.py class CustomUserBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = request.data.get("username") if password is None: password = request.data.get("password") .... return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None When submitting a request via my API this works as expected and authenticates the user correctly etc. My problem comes when I try and log into the admin panel. The stack trace I'm getting when trying to login is caused by an exception when trying to access request.data which is because it's not the correct type to look at, which is correct to how my logic works. The problem is the authenticate method in here; def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): print(backend) try: inspect.getcallargs(backend.authenticate, request, **credentials) except TypeError: # This backend doesn't accept these credentials as arguments. Try the next one. continue try: user = backend.authenticate(request, ) except PermissionDenied: # This backend says to stop in our tracks - this user should not be allowed in at … -
How do you pass model data to a template using Django?
I am trying to pass data from a Django model into an HTML template using a class based view. urls.py from django.urls import path from app import views urlpatterns = [ path('review/', views.ReviewRecord.as_view(template_name='review.html'), name='review') ] models.py from django.db import models class MyModel(models.model): RegNumber = models.TextField(primary_key=True) Description = models.TextField(null=True) views.py from app.models import MyModel from django.views.generic import TemplateView class ReviewRecord(TemplateView) template_name = 'review.html' model = myModel def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['description'] = self.model.description return context html <textarea readonly>{{ description }}</textarea> The above code inserts the following into the html textarea: <django.db.models.query_utils.DeferredAttribute object at 0x0000024C449B9F88> I need to display the stored field data from the model, not the object data as stated above. I am trying to create a queryset based on a field in the model, for example, for a particular RegNumber. Eventually I would like to retrieve several records and be able to increment through them, however I am currently just trying to get one to work. I have also tried using a DetailView using the primary key in the url, however I keep getting errors, therefore the provided example code is from what appears to be my closest attempt to my goal. -
Problem regarding Installation of Pillow and zlib for PyCharm
When I am trying to install pillow it is saying "The headers or library files could not be found for zlib, a required dependency when compiling Pillow from source." And while I am trying to install 'zlib' its saying "Could not find a version that satisfies the requirement zlib (from versions: ) No matching distribution found for zlib" What to do. can anyone suggest please. I am using python3.8.2 in windown 10 Please help Its urgent -
Django Postgres memory leak
I have a custom Django command to start background job executers in a multi-threaded fashion which seems to give me memory leak issues. The command can be started like so: ./manage.py start_job_executer --thread=1 Each thread has a while True loop that picks up jobs from a PostgreSQL table. In order to pick up the job and change the status atomically I used transactions: # atomic transaction to temporary lock the db access and to # get the most recent job from db with column status = pending with transaction.atomic(): job = Job.objects.select_for_update() \ .filter(status=Job.STATUS['pending']) \ .order_by('created_at').first() if job: job.status = Job.STATUS['executing'] job.save() Il looks like the allocated memory by this Django custom command keeps growing. Using tracemalloc I tried to find what is causing the memory leak by creating a background thread that checks the memory allocation: def check_memory(self): while True: s1 = tracemalloc.take_snapshot() sleep(10) s2 = tracemalloc.take_snapshot() for alog in s2.compare_to(s1, 'lineno')[:10]: log.info(alog) Finding out the following log: 01.04.20 13:50:06 operations.py:222: size=23.7 KiB (+23.7 KiB), count=66 (+66), average=367 B 01.04.20 13:50:36 operations.py:222: size=127 KiB (+43.7 KiB), count=353 (+122), average=367 B 01.04.20 13:51:04 operations.py:222: size=251 KiB (+66.7 KiB), count=699 (+186), average=367 B 01.04.20 13:51:31 operations.py:222: size=379 KiB (+68.9 KiB), count=1056 … -
Opening browser in server from hosted Flask application in IIS not working
I am working on a flask application which needs to open a browser inside server and do some operations based on the user input. My application is working in visual studio and spyder. But when hosted it is not opening browser. I tried: webbrowser : Work in local but hosted code is not working pyppeteer : Work in local but hosted code is not working subprocess : Work in local but hosted code is not working I tried running a batch file from the hosted code to write into a file , this is working in local but the hosted code is not even running the subprocess. Can someone help on this? Thanks in advance! -
Fetch entire data from Celery task
I am currently using celery in my Django project. Below are my views.py and tasks.py files. views.py def status_codes(request): try: url = request.GET.get('url') urls = linksextraction(url) url_codes.objects.all().delete() for each_url in urls: res = url_status_codes.delay(each_url[1]) while (res.status == 'PENDING'):# waiting till all tasks are completed pass # Do manipulations from db data tasks.py @app.task def url_status_codes(url): r = requests.head(url) status_code = r.status_code spell_words = spellcheck(url, 'English--en') if (not spell_words): spell_words = 'NA' data = url_codes(status_code=status_code, url=url, spell_words=spell_words) data.save() # Saving in Database From above code snippets, I am saving results achevied in tasks.py in database and when all tasks are completed, i am fetching the results from db and doing manipulations. Is there any way to get all results in tasks.py to views.py without having saved to db. -
allauth is redirecting me to /accounts/profile when i am trying to go to /accounts/login
I have done all the necessary settings in settings.py, and i have set the urls too i the urls.py file. Each time i am trying to access /accconts/login, it will say the url did not match any pattern, and it redirects me to /accounts/profile. This are the code INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'core' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) SITE_ID = 1 urlpatterns = [ path('accounts/', include('allauth.urls')) ] -
django tutorial, not loading my static files properly
It's my fault I'm following different tutorials, but the first one worked well enough and figured I'd follow a more detailed one. Anyway, the first one had me move the templates folder outside the blog app and move it to the route, so I have the following on the settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] problem with that tutorial, it did not include any static setups for css and whatever static files I would need. That said, I'm following another tutorial that has me placed the css like so |- blog |---static |-----blog |-------main.css |- django_app |---all the settings found here |- templates |---blog |-----all my templates are here and had this on the base.html of the templates to <style rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"></style> but my template does not find it. I was able to trace my css through the following url http://127.0.0.1:8000/static/blog/main.css Idk what the best practice is with django and it's folder structure but any advice is appreciated. Thanks -
How to make jQuery script correctly run in google chrome?
I have django project and I can't make jquery script to run in google chrome. Simple code for checking if scroll is at bottom: <script language="JavaScript" type="text/JavaScript"> window.onload = function () { $('#scrolling').on('scroll', chk_scroll); }; function chk_scroll(e) { var elem = $(e.currentTarget); if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) { alert("bottom") } } </script> It works in Opera, Explorer, Firefox, Chrome (As single html file, not part of project), jsfiddle. P.s jquery loads correctly and other scripts works. -
Huey not calling tasks in Django
I have a Django rest framework app that calls 2 huey tasks in succession in a serializer create method like so: ... def create(self, validated_data): user = self.context['request'].user player_ids = validated_data.get('players', []) game = Game.objects.create() tasks.make_players_friends_task(player_ids) tasks.send_notification_task(user.id, game.id) return game # tasks.py @db_task() def make_players_friends_task(ids): players = User.objects.filter(id__in=ids) # process players @db_task() def send_notification_task(user_id, game_id): user = User.objects.get(id=user_id) game = Game.objects.get(id=game_id) # send notifications When running the huey process in the terminal, when I hit this endpoint, I can see that only one or the other of the tasks is ever called, but never both. I am running huey with the default settings (redis with 1 thread worker.) If I alter the code so that I am passing in the objects themselves as parameters, rather than the ids, and remove the django queries in the @db_task methods, things seem to work alright. The reason I initially used the ids as parameters is because I assumed (or read somewhere) that huey uses json serialization as default, but after looking into it, pickle is actually the default serializer. One theory is that since I am only running one worker, and also have a @db_periodic_task method in the app, the process can only … -
how to pass my_dict to redirect, like redirect('home',my_dict)
I want to pass this error into the template, but it is not working, def addcomment(request): name = request.POST['name'] comment = request.POST['comment'] if name=="" and comment=="": my_dict = {'error':'blank fields not allowed'} return redirect('home',my_dict) Comment(name = request.POST['name'],comment = request.POST['comment']).save() return HttpResponseRedirect('/') -
How to print value of a "changing field" in Django template
I am trying to display a list of fields (and their values) in a template. The problem is that the fieldnames are changing and I dont have control over them. e,g the fields can be: field_name1 field_object1 field_input1 The only thing constant here is the prefix "field_" This makes a challenge to get the value of that field in the template. I followed the advice here: Django: Cannot reference a fieldname in template which contains a dot and was able to print the field names. But i still dont know how to print the values of these fields. model.py rowObj = { 'id': id, 'inputList': {'Input_' + k: v for k, v in objList} } # Example of the outputs (The outputs can be one of the following): # rowObj = { # 'id': 1, # 'inputList': {'Input_Image' : 'http://test', # 'Input_Image2' : 'http://test2' } # } #another time the output can be: # rowObj = { # 'id': 1, # 'inputList': {'Input_Text' : 'Random text', # 'Input_Text2' : 'Random text 2' } # } My template is: {% for row in row_list %} <tr> <td>{{ row.id }}</td> {% for obj in row.inputList %} <td>{{ obj.value }}</td> {% endfor %} … -
Can Django run with failing database connection
Is it possible to handle a failed database connection but still have frontend run smoothly with Django? I wouldn't want my page break while the database stops. I'm using MySQL 5.7 and Django 1.8. -
Image ids apparently not being created
I have created a template for displaying a photo gallery and giving users the ability to add photos to that gallery. The idea is that there is an image associated with each comment - there is a for loop of {% for p in pictures %} at the start of the page, and I use variations of p. (e.g. p.image_id) to associate particular pictures with particular comments. In addition, the urls.py contains the following: path('add_comment/<int:p.image_id>', views.add_comment, name='add_comment') However, when I run the code, I get an error message that suggests that image ids aren't being created (even though image is a field in he Pictures model I created): Reverse for 'add_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['add_comment/$'] What do you suggest, please? -
Django's dbshell and sqlmigrations
The output of the initial default sqlmigrate from Django works when running it with manage.py but applying the output of sqlmigrate does not work with sqlplus [the default for manage.py dbshell]. When creating triggers (e.g) select count from user_sequences loop is terminated by a /; could this be the issue? I've searched through the source code but cannot understand how Django is applying these differently than using its shell and sqlmigrate. -
How to slove a MultiValueDictKeyError in Djangos Rest API upload?
I am currently setting up a file upload with React for the frontend and Django for the backend. I want to upload a file and some jason data. When submitting the data to my django backend i get the following error message: raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'data' The error message refers to 'data' in the utils.py file, wehere I define my multipart parser. models.py (Django) class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) audio = models.FileField(default='SOME STRING', upload_to='audio_stories/',null=True, validators=[validate_file_extension_audio]) def __str__(self): return self.title def get_absolute_url(self): return reverse('story-detail', kwargs={'pk': self.pk}) serializers.py (Django) class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = '__all__' A MultiPartParser is used to pass file + data. api.py (Django) class StoryViewSet(viewsets.ModelViewSet) (Django): serializer_class = StorySerializer parser_classes = (MultipartJsonParser, parsers.JSONParser) queryset = Story.objects.all() permission_classes = [ permissions.IsAuthenticated ] def perform_create(self, serializer): serializer.save(author=self.request.user) utils.py (Django) class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # find the data field and parse it data = json.loads(result.data["data"]) qdict = QueryDict('', mutable=True) qdict.update(data) return parsers.DataAndFiles(qdict, result.files) In actions story.js (React) import axios from "axios"; import { tokenConfig } from './auth'; import { createMessage, returnErrors } from "./messages"; import {ADD_STORY} … -
set django setting django-graphql-jwt samesite options
I'm trying to make an authentication system for my react front-end i want to use cookie authentication for it but i cant set cookies SameSite attribute i couldn't find anything on package's site isn't there any setting for it ? https://django-graphql-jwt.domake.io/en/latest/settings.html like that ? """JWT_COOKIE_SECURE = True""" Can anyone help me ?