Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elasticache & Django - settings configuration for a Redis Cluster
I am setting up my caching to an Elasticache, Redis Cluster with Django-redis 4.10.0. Right now I'm not seeing any cache-hits in my Elasticache console so I'm debugging what is going on. My Cache settings- CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', # 'LOCATION': 'redis://redis:6379/0', 'LOCATION': [ '<node_endpoint_primary>.cache.amazonaws.com:6379/0', '<node_endpoint_replica>.cache.amazonaws.com:6379/0', '<node_endpoint_replica>.cache.amazonaws.com:6379/0', ], 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', # Mimicing memcache behavior. # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior 'IGNORE_EXCEPTIONS': True, 'SOCKET_TIMEOUT': 5, 'SOCKET_CONNECT_TIMEOUT': 5, } } } Things I notice: When I run createcachetable there are no errors. When I deploy with redis://<node_endpoint_primary>.cache.amazonaws.com:6379/0 it does timeout. Having the extra Redis:// seems to cause issues Any ideas? -
Show children inline in Django admin
In Django 1.11, I have 2 models, Foo and Bar: class Foo(models.Model): name = models.CharField() class Bar(models.Model): name = models.CharField() foo = models.ForeignKey(Foo) When I visit the Foo page in the Django admin, I want to be able to see a list of its Bars underneath it. So I do this in admin.py: class BarInline(admin.StackedInline): model = Bar @admin.register(Foo) class FooAdmin(admin.ModelAdmin): list_display = ('name') fields = ('name') inlines = [BarInline] But what I really want is a list of clickable links to a separate page where I can edit each Bar (as well as a Add button to add a new Bar to this Foo). I.e. I don't want the entire inline form. How is this possible in Django? -
how to create a model whenever a user is added to specific group in django
in django User and i have 2 groups, i want whenever i create a user, create a corresponding profile for it (depending on which group it belongs to) how should i manage it? i have used this method: def create_profile(sender, **kwargs): if kwargs['created'] : UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) But it creates userprofile whenever i create a user. How can I have conditions to check which group it belongs too and then have create corresponding profile for it -
Passing FontAwesome (html) as JQuery var/verb
I am learning Django and to create a funtional Like button without need to reload page using Ajax. It is my first contact with JS. It works but I want to pass html (FontAwesome) within this script to show icon together with Likes number. I tried passing it using "verb" argument in function but it just shows plain text). I also tried to grab html code as var (from similar questions on StackOverflow) but it doesn't work for me (it displays [object Object]). I think I am doing something wrong. The code is below: <script> var HtmlHeart = $(this).children("i").attr("class", "fas fa-heart") $(document).ready(function() { function UpdateText(btn, NewCount, HtmlHeart) { btn.attr("data-likes", NewCount) btn.text(HtmlHeart + " " + NewCount) } $(".like-btn").click(function(e) { e.preventDefault() var this_ = $(this) var LikeUrl = this_.attr("data-href") var LikeCount = parseInt(this_.attr("data-likes")) | 0 var AddLike = LikeCount + 1 var RemoveLike = LikeCount - 1 if (LikeUrl) { $.ajax({ url: LikeUrl, method: "get", data: {}, success: function(data) { console.log(data) if (data.liked) { UpdateText(this_, RemoveLike, HtmlHeart) } else { UpdateText(this_, AddLike, HtmlHeart) } }, error: function(error) { console.log(error) console.log("error") } }) } }) }) </script> Could you please help me with understanding how it is possible to pass html as … -
Django joined path for uploaded files
(There are 5 or 6 different SO questions and answers that deal with similar problems – I've tried implementing their solutions without success.) I'm trying to implement a page where a user can drag-and-drop to upload an Excel file that will then subsequently be parsed and information extracted to create various models. The files upload without any problems and are successfully stored on the server and are referenced in a FileField in a model. However, I cannot get my subsequent function, using xlrd, to access the file. Any attempt to reference the file results in a 400 Bad Request, with the error that the joined path is located outside the base path component. urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_ROOT = os.path.join(BASE_DIR,'media') STATIC_URL = '/static/' MEDIA_URL = '/media/' I have also tried the same as above, as suggested in other posts, with a trailing slash for the _ROOTs. The resulting errors (for example, calling the file via File.file.path) are always of the form: django.core.exceptions.SuspiciousFileOperation: The joined path (/media/sheet.xlsx) is located outside of the base path component (/PATH-TO-DJANGO-APP/SchedulePosting/media) -
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)