Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Ignore spaces for specific query in queryset
Input: OFG 5T4 WR4 2-3 Does not give any results for ofg5t4wr42-3. However, that's how ticket_reference is saved in my database, while I show it on tickets as seen in the input, to make it easier to read. Can I replace ticket_reference__icontains with any other "filter" to "ignore" spaces for ticket_reference queries. def queryset(self, queryset): cleaned_data = self.cleaned_data # Search search = cleaned_data.get('search') if search: queryset = queryset.filter( Q(company_name__icontains=search) | Q(first_name__icontains=search) | Q(last_name__icontains=search) | Q(email__icontains=search) | Q(ticket_reference__icontains=search) ) -
How to get response of an image in django api, after encoded it in base64?
I am trying to make an django api, which accepts image from post method. After that, I change it to grayscale and then, I tried sending back that image as HttprResponse after encoded it into base64. (Actually, I don't know how to send base64 encoded string as reponse. I am new to python). Here's my code: # import the necessary packages from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse import numpy as np import urllib.request import json import cv2 import os import base64 @csrf_exempt def combine(request): # check to see if this is a post request if request.method == "POST": # check to see if an image was uploaded if request.FILES.get("image1", None) is not None: # grab the uploaded image image1 = _grab_image1(stream=request.FILES["image1"]) # image2 = _grab_image2(stream=request.FILES["image2"]) gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) final = base64.b64encode(gray) # return a response return HttpResponse(final) def _grab_image1(stream=None): if stream is not None: data = stream.read() image1 = np.asarray(bytearray(data), dtype="uint8") image1 = cv2.imdecode(image1, cv2.IMREAD_COLOR) # return the image1 return image1 I am using postman to test. And from HttpResponse I am getting a lot of strings as you can see in above image. I copied those strings and tried to decode it online to get … -
What is the recommended practice in django to execute external scripts?
I'm planning to build a WebApp that will need to execute scripts based on the argument that an user will provide in a text-field or in the Url. possible solutions that I have found: create a lib directory in the root directory of the project, and put the scripts there, and import it from views. using subprocess module to directly run the scripts in the following way: subprocess.call(['python', 'somescript.py', argument_1,...]) argument_1: should be what an end user provides. -
Is there a way to make dropdown checkbox with django-filter and location foreignkey for City from cities-light
I create a dropdown list checkbox with django-filter that I managed to create for some fields with a choice option, but I can not retrieve the database information for city-light cities . When put city for choice value, I get this error : * TypeError at / 'City' object is not iterable this section work fine: CITY_CHOICES = ( ('city1','city1'), ('city2','city2'), ) class PostFilter(filters.FilterSet): location = filters.MultipleChoiceFilter(field_name='location', choices=CITY_CHOICES, widget=forms.CheckboxSelectMultiple()) class Meta: model = Post fields = ['location'] this problem section: from cities_light.models import City class PostFilter(filters.FilterSet): location = filters.MultipleChoiceFilter(field_name='location', choices=City, widget=forms.CheckboxSelectMultiple()) class Meta: model = Post fields = ['location'] I expect the same results for my city choices. How can i proceed on doing that -
django static files loading error in aws-s3 buscket
here is my aws conf file: import datetime AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = 'monetimes.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'monetimes.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'monetimes-static-bucket' S3DIRECT_REGION = 'ap-south-1' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ), } AWS_QUERYSTRING_AUTH = True I am putting my static files to aws-s3 buket by making it full access and in public mode. static files are coming and copying to my aws-s3 bucket but showing some errors. please check the above screen-shot for the error. I am adding key and secret key properly also by default in my s3 bucket it is coming asia-mumbai location. and i am procedding with the same -
django 'python manage.py runserver' does not open port in Ubuntu
Starting up with Django. On Ubuntu 16.04, using python3.6. On a venv started a project and running the command to start webserver. Here is the output $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). January 03, 2019 - 14:06:57 Django version 2.1.4, using settings 'tictactoe.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. when I try to access the localhost. I get a connection refused error $ curl -v http://127.0.0.1:8000/ * Trying 127.0.0.1... * connect to 127.0.0.1 port 8000 failed: Connection refused * Failed to connect to 127.0.0.1 port 8000: Connection refused * Closing connection 0 curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused Found that the server isn't listening on port 8000 . Verified with netstat -an Tried with different ports also with python manage.py runserver 0:8000 Didn't help. -
how to encrypt password so that it matches with the algorithm in admin panel?
The account i am registering is saved in the database but it is not logged in. I think the issue is for password encryption This is my view page This is my model page -
What does the test directories implies in a source code on github?
When you go through some source code in github like source codes for pinax-notification, elasticsearch-dsl, and many more, you normally see a folder called 'Test'. What is the function of this folder? Is it an example of how to use the source code and its functionality in your own code or what? For example, I saw a 'test' folder in pinax-notification repository does this give an example on how to use this in my code? Also if not, please someone share an example with me on how to use pinax-notification to send email notification and display a notification to users through django template? -
How to add lookup to Count inside an annotate
I want to get the count of all lectures with status=1. Currently I can only get the count of all lectures using the following line of code: topic = Topic.objects.annotate(lectures_count=Count('lectures')).get(id=topic_id) Here are my models class Lecture(models.Model): id = HashidAutoField(primary_key=True) topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='lectures') status = models.BooleanField(default=1) class Topic(models.Model): id = HashidAutoField(primary_key=True) name = models.CharField(max_length=100, null=False) status = models.BooleanField(default=1) -
Google Cloud SQL w/ Django - Extremely Slow Connection
I've recently noticed my Django application is incredibly slow to connect to my Google Cloud SQL database when using the Cloud SQL Proxy in my local development environment. The initial connection takes 2-3 minutes, then 60 seconds per request thereafter. This applies when performing migrations or running the development server. Eventually the request completes. I've tried scaling up the database but to no effect (it's relatively small anyway). Database version is MySQL 5.7 with machine type db-n1-standard-1. Previously I've used django-channels but have since removed all references to this. The Middleware and settings.py are relatively standard and identical to another Django app that connects in an instant. The live site also connects very fast without any issues. Python version is 3.6 w/ Django 2.1.4 and mysqlclient 1.3.14. My database settings are defined as: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'PORT': '3306', } } DATABASES['default']['HOST'] = os.getenv('DB_HOST') if os.getenv('GAE_INSTANCE'): pass else: DATABASES['default']['HOST'] = '127.0.0.1' Using environment variables or not doesn't seem to make a difference. I'm starting the Cloud SQL Proxy via ./cloud_sql_proxy -instances="my-project:europe-west1:my-project-instance"=tcp:3306. After invoking the proxy via the command line I see Ready for new connections. Running python manage.py runserver shows New … -
Django lockdown logout
Im trying to logout of my lockdown session. In the docs it says LOCKDOWN_LOGOUT_KEY A key which, if provided in the query string of a locked URL, will log out the user from the preview. I'm not sure if I understand it rightly. I tried to implement this like this: I have the lockdown middleware in the middleware list. I have these lockdown options in settings.py: LOCKDOWN_FORM = 'lockdown.forms.AuthForm' LOCKDOWN_AUTHFORM_STAFF_ONLY = False LOCKDOWN_LOGOUT_KEY = 'logout' I have a button which links to "/logout/" <form action="/logout/"> <input type="submit" value="Logout"/> </form> This just links to a HttpResponseRedirect() back to my main page: urls.py: path('logout/', views.logout, name='logout') views.py: def logout(request): return HttpResponseRedirect("/") The link works and takes me back to my main page. But the logout doesn't occure. Does anyone know how to do this? -
"Cannot interpret feed_dict key as Tensor" error when submitting form
I am creating a django web application. The application holds a form for uploading an image and input fields for filling the description about the image. I am using keras classifiers that try to classify the image and fill some of the description automatically. While the classification part works fine, I get a type error while submitting the form. 'Cannot interpret feed_dict key as Tensor: ' + e.args[0]) TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 32), dtype=float32) is not an element of this graph. this is my code so far models.py class Item(models.Model): title = models.CharField(max_length=100) pattern = models.CharField(max_length=100) color = models.CharField(max_length=100) user = models.CharField(max_length=100) img = models.ImageField(upload_to='item/img/', null=False, blank=False) def __str__(self): return self.title def delete(self, *args, **kwargs): self.img.delete() super().delete(*args, **kwargs) forms.py from .models import Item class ItemForm(forms.ModelForm): class Meta: model = Item fields = ('title', 'pattern', 'color', 'user', 'img') views.py def handle_uploaded_file(file, filename): if not os.path.exists('media/classification/'): os.mkdir('media/classification/') with open('media/classification/' + filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) def image_classification(request): form_des = ItemForm(initial={'user': request.user}) category_classifier = load_model("./cat_classifier.h5") pattern_classifier = load_model("pat_classifier.h5") if request.method == 'POST': handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) img = np.expand_dims(cv2.resize(cv2.imread(os.path.join('./media/classification/', str(request.FILES['file']))), (170, 100)), axis=0) category_prediction = category_classifier.predict_classes(img)[0] pattern_prediction = pattern_classifier.predict_classes(img)[0] form_des.fields['title'].widget.attrs['value'] = category_prediction form_des.fields['pattern'].widget.attrs['value'] … -
Loop over Django objects and Bootstrap cards
I would like to use Bootstrap cards in order to create one card by object and add some sub_objects in each one. For example : I have an object Publication which could contain one or many sub_objects Document. Publication object has some attributes : category, title, picture, description and Document object has some attributes like title, format, language, ... I would like to get something like this : For a same category, I create a card by publication and I list all documents for each publication. This is what I get with my code : As you can see, I should have document n°1 and document°2 in the same card and not two different cards. This is my code : {% for category in research_categories|dictsort:'name' %} <div class="row"> <fieldset> <legend id="category_{{ category.id }}"><span class="name">{{ category }}</span></legend> </fieldset> </div> <div class="row"> <div class="col-sm-4"> {% for element in test_research %} {% if element.publication.category|stringformat:"s" == category|stringformat:"s" %} {% ifchanged %} <div class="card" style="width:250px"> <img class="card-img-top" src="{{ element.publication.cover.url }}" alt="Card image"> <div class="card-body"> <h4 class="card-title">{{ element.publication }}</h4> <table class="table table-condensed"> <tbody> <tr> <td> {{ element.title }}</td> </tr> </tbody> </table> </div> </div> {% endifchanged %} {% endif %} {% endfor %} </div> </div> {% endfor … -
Different SESSION_COOKIE_AGE setting for different users
Im executing session timeout in django with these settings: SESSION_SAVE_EVERY_REQUEST = True SESSION_COOKIE_AGE = 600 is very easy, i'm looking for a way to differ the session cookie age for user group. In example, i want to timeout a regular user much faster then a staff member or even admin. Is there any easy way to modify session cookie age on the fly, via middleware or in view? Is there a way to avoid writing new session menagement? -
how to include different js and css files when using block content using jinja
I am creating a web app using Django. I have a html template as follows: <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% block content %} {% endblock %} </body> </html> I am using this template to create other html files using {% extends 'document.html' %} {% block content %} {% endblock %} for the moment I am referring to all css and js files in the original document.html. how can I refer to different js and css files in the new templates only when necessary? thanks -
django channels invalid state error after disconnnect
Im using django-channels to implement chat message box and connecting to websocket via ajax since the chat box doesn't take up a full screen . Im connecting to a particular socket when one user is selected and the messages are sending through the first time and its getting saved.When i close the chatbox im calling websocket close and disconnnect is executing,but when i close and reopen again im getting error reconnecting-websocket.js:293 Uncaught INVALID_STATE_ERR : Pausing to reconnect websocket And also the messages can be seen in other channels as well when i open the chatbox.Is there any chance the websocket are remaining connected and channels aren't being discarded after disconnect is called? My code: class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] thread_obj = await self.get_thread(me, other_user) self.thread_obj = thread_obj chat_room = "thread_{}".format(thread_obj.id) self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("MEssage received",event) front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get('message') me = self.scope['user'] myResponse ={ 'message': msg, 'username': me.username } if msg is not "": await self.create_chat_messages(me,msg) await self.channel_layer.group_send( self.chat_room, { "type": "chat_message", "text": json.dumps(myResponse) } ) … -
Extends Django Admin View for concrete Model
I would like to extends django admin view, it's if posible?. I want to do more things in admin view like extending class based view for example from django.views.generic import TemplateView My idea is something like that: file.py: class CustomClass(object): atributes... methods... views.py: class ConcreteModelList("admin_view"): doTask(self): instance = CustomClass() result = method() return result How could do that? Thanks in advance. -
Django Rest Framework - How to implement different schemas based on request action in function-based views?
I am trying to display a function-based view in a Swagger UI page. The view is part of a legacy code (the real one, not the one shown below) and it supports both GET and POST operations. @schema(foo_schema) def foo(request): if request.method == 'GET': param1 = request.query_params.get('param1') # do something elif request.method == 'POST': param1 = request.data.get('param1') # do something ... The parameter param1 is required for both GET and POST operations, so my initial attempt was to specify it twice in the schema, with different arguments for the location: foo_schema = AutoSchema( manual_fields=[ coreapi.Field( name='param1', location='query', required=True, schema=coreschema.Integer(), ), coreapi.Field( name='param1', location='formData', required=True, schema=coreschema.Integer(), ), ... ] ) The problem is, the swagger UI would only display the field once, as a form data. So even if I tried to access the endpoint via swagger with a GET request, the parameter would be included to the request.data variable and not to request.query_params, as if the inputed data were always part of a POST request. Likewise, if I removed the second field specification in the schema, the parameter would always be in request.query_parames, as if the requests were always GET. How do I specify both fields in the swagger? Or … -
Get Queryset by removing White spaces in the middle of the string - Django
I am having table which has column "name". I want to get record by providing name, which contains extra white spaces in middle. my table looks like as follows. id name 1 Raj Kumar 2 praveen kumar 3 Sandya My Table contain records in which row contain only one spaces at the middle. I want to make a query as follows. input_name = 'Raj Kumar'(Which contain two spaces) a = A.objects.get(name=input_name) The above will return "None". Kindly help me out to solve the problem. -
Can I use part of the implementation to build test expectation?
Let's suppose that I use build_help_message many times throughout my application and it returns a big dictionary which contains text and attachments which I need to send using Client library. Is it okay to use build_help_message to build expected result in the test? How can I avoid doing that, if it's not a good practice? def help_handler(payload): team_id = payload['team_id'] user_id = payload['user_id'] message = build_help_message(team_id, user_id) Client(team_id).send_message(user_id, **message) Tests class TestHandler(TestCase): def setUp(self): team = Team.objects.create(team_id='TEAMID') User.objects.create(team=team, user_id='USERID') def tearDown(self): ... @mock.patch('client.Client.send_message') def test_correct_text(self, send_message_mock): payload = {'team_id': 'TEAMID', 'user_id': 'USERID'} handle_message(payload) expected_message = build_help_message('TEAMID', 'USERID') send_message_mock.assert_called_with('USERID', **expected_message) -
Own Middleware for Restricting Users Django
i am going to write a model which contains following fields example. user_id, role_id, company_id, functionality_id, has_access. I want to write middleware where user will be raised NOT ACCESS where field has_access is false. Please help how should i do it and i can't use in-built permission due to my dependencies. I have created middleware.py and followed official document. This is just my start for writing middleware class ACLMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response i have found some reference to this code but i don't know if it is right way to do because i'm using django 2.1 version from django.core.urlresolvers import reverse from django.http import Http404 class RestrictStaffToAdminMiddleware(object): """ A middleware that restricts staff members access to administration panels. """ def process_request(self, request): if request.path.startswith(reverse('admin:index')): if request.user.is_authenticated(): if not request.user.is_staff: raise Http404 else: raise Http404 -
How to asynchronously generate Google Text-To-Speech audio files in Django view to use in webpage?
One of my webpages takes about 3 seconds to load locally, and 15 seconds to load when it's live on Heroku. I believe the problem is how many synchronous Google TTS (Text-To-Speech) API calls and synchronous database / Amazon S3 writes I make. I think asynchronous coding would help, but I'm not entirely sure how to implement it. Here's an oversimplified example of what's happening in the view: def slow_loading_view(request): for i in range(100): audio_str = str(i) google_audio = synthesize_text(audio_str) # returns audio file # WAIT for google's response to come back save_string_and_audio_to_database(audio_str, google_audio) # WAIT to complete writing the audio string to my database and # storing the audio file in my Amazon S3 bucket for future use # Now I would like to query the database to obtain these audio strings and files I just saved # And then pass them in my context to use in the webpage return render(request, 'my_page.html', context) As you can see, there's a lot of waiting (idle time) going on in the view, so ideally i'd be able to 1) asynchronously send all the google API requests to generate the audio files, and then after I have all those audio files returned … -
Django QuerySet filtering not working with views, showing blank view even though there are entries
I am attempting to view a particular set of objects with a certain attribute by using QuerySet filtering, however when I use the filter, the view returns blank. Not sure if I'm using this particular filter wrong, or if I'm calling on the attribute wrong, however I accessed other attributes (as seen below, the attribute "status") and found that it worked fine. views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import * from .forms import * @login_required def vendorView(request): return render(request, 'inv/vendorInventory.html') @login_required def consumerView(request): return render(request, 'inv/consumerInventory.html') def unauthenticatedView(request): return render(request, 'inv/unauthenticatedInventory.html') ################ need to edit other views to render consumer/vendor/unauth def display_drinks(request): items = Drinks.objects.all() context = { 'items': items, 'header': 'Drinks', } if not request.user.is_authenticated: items = Drinks.objects.filter(status='AVAILABLE') context = { 'items': items, 'header': 'Drinks', } return render(request, 'inv/unauthenticatedInventory.html', context) elif request.user.profile.vendor: items = Drinks.objects.filter(donatorID=request.user.username) context = { 'items': items, 'header': 'Drinks', } return render(request, 'inv/vendorInventory.html', context) elif not request.user.profile.vendor: items = Drinks.objects.filter(status='AVAILABLE') context = { 'items': items, 'header': 'Drinks', } return render(request, 'inv/consumerInventory.html', context) inventory/models.py: from django.db import models from django.contrib.auth.models import User from users.models import * # Create your models here. class Donation(models.Model): description = models.CharField(max_length=200, … -
Modal positioning on mobile - bootstrap
Hopefully you can advise, I have a script that loops through DB records and creates a row & modal for each. It's great, but when I get to the middle of the page on mobile & click on the button, opening the modal, it shows right at the top of the page, so I have to scroll up and use it. Is there any way to make a modal appear at the right point on the screen? {% for todo in todo_list %} {% if todo.complete is False %} <div class="col-sm-3"> <div class="card"> <h5 class="card-header">{{ todo.id }} :{{ todo.text }}</h5> <div class="card-body"> <p class="card-text"> <table class="table table-hover"> <tr> <td>Created By</td> <td>{{ todo.creator }}</td> </tr> <tr> <td>Assigned To</td> <td>{{ todo.assignee }}</td> </tr> <tr> {% if todo.priority == "High" %} <td>Priority</td> <td class="table-danger">{{ todo.priority }}</td> {% elif todo.priority == "Medium" %} <td>Priority</td> <td class="table-warning">{{ todo.priority }}</td> {% else %} <td>Priority</td> <td class="table-info">{{ todo.priority }}</td> {% endif %} </tr> </table> <table class="table table-hover"> <tbody> <tr class="table"> <th scope="col"><form action="/complete/" name="form2", id="form2" method="post"> {% csrf_token %} <button name="donebutton" type="submit" value={{ todo.id }} data-toggle="tooltip" data-placement="top" title="Complete Task" class="btn btn-success"><i class="fas fa-check"></i></button></th> </form> <td> <!-- Button trigger modal --> <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#EditModal{{ todo.id … -
Form field calculations online with Ajax
I have a current django application with a form, and as user selects options, it updates the total price at the bottom of the form. The form is extense, and field combinations large. I have all this calculations implemented in my view, so when the user posts the form, I have the total and correct amount calculated. I also have the calculations in a javascript file, so the user can see the total amount on the fly. Now I want to get rid of the javascript file, and have calculations only on my view (hate double implementation). I thought on having an ajax call on some field changes so the view can be called, the values updated and return a full form back (or something like that). My question is: is out there some django package that does that? (So I don't have to do it from scratch) -- couldnt find from my research.