Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I manipulate a static URL using a function?
In my template file I have a classic use of: {% load static %} <img src="{% static 'cat.png' %}"> Which as you'd expect spits out <img src="STATIC_URL/cat.png"> Where the STATIC URL is set in settings.py I want to be able to apply a function to this static URL, for example: def url_change(input_url): output_url = input_url + '/somethingelse/' return output_url So when I use {% static 'cat.png' %} it outputs the following: STATIC_URL/cat.png/somethingelse/ I can't seem to find a way to do this anywhere but I would have thought it was quite easy, given that I already have a function defined. -
How to refresh materialised view in case of multidb in django using manage.py?
I am using Postgresql as database in my django project. I am using materialised views also using django-pgviews which is django module for using materialised views in django. To refreshing materialised views I use command below python manage.py sync_pgviews But now I am using multidb in my django project. Which is easily manageable like python manage.py migrate # This will apply sql to default database python manage.py migrate --database=tableau # This will apply sql to tableau database I was expecting --database=tableau option to work with python manage.py sync_pgviews also. But this does not work. python manage.py sync_pgviews # refresh default db views python manage.py sync_pgviews --database=tableau # This does not work How can I refresh materialised view of other database using django using manage.py? -
Daphne is correctly lauched?
I'm new to channels. I followed the chat tutorial. Everything works with the runserver command also in asyncronous mode. On the other hand when I use daphne: (autoACIlab)$ daphne -b 10.9.6.114 -p 8000 autoACIlab.asgi:application -v 2 2019-02-11 14:06:48,352 INFO Starting server at tcp:port=8000:interface=10.9.6.114 2019-02-11 14:06:48,352 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2019-02-11 14:06:48,352 INFO Configuring endpoint tcp:port=8000:interface=10.9.6.114 2019-02-11 14:06:48,353 INFO HTTPFactory starting on 8000 2019-02-11 14:06:48,353 INFO Starting factory 2019-02-11 14:06:48,354 INFO Listening on TCP address 10.9.6.114:8000 I got this error after the browser request: 2019-02-11 14:08:01,412 ERROR Exception inside application: Cannot import BACKEND 'channels_redis.core.RedisChannelLayer' specified for default File "/usr/lib/python3.6/site-packages/channels/sessions.py", line 179, in call return await self.inner(receive, self.send) File "/usr/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/usr/lib/python3.6/site-packages/channels/consumer.py", line 44, in call self.channel_layer = get_channel_layer(self.channel_layer_alias) File "/usr/lib/python3.6/site-packages/channels/layers.py", line 363, in get_channel_layer return channel_layers[alias] File "/usr/lib/python3.6/site-packages/channels/layers.py", line 80, in getitem self.backends[key] = self.make_backend(key) File "/usr/lib/python3.6/site-packages/channels/layers.py", line 46, in make_backend return self._make_backend(name, config) File "/usr/lib/python3.6/site-packages/channels/layers.py", line 73, in _make_backend % (self.configs[name]["BACKEND"], name) Cannot import BACKEND 'channels_redis.core.RedisChannelLayer' specified for default 2019-02-11 14:08:01,412 INFO failing WebSocket opening handshake ('Internal server error') Can anyone send me a clue on that? Do I have to change something in the … -
Django rest framework, Primary key is string, not integer
have a very stupid problem. All primary keys (id) returned as string, but i need integer. Django==2.1.5 djangorestframework==3.9.1 djangorestframework-jsonapi==2.7.0 Model: class Room(models.Model): id = models.IntegerField(primary_key=True) creator = models.ForeignKey( User, verbose_name='Creator', on_delete=models.CASCADE ) invited = models.ManyToManyField( User, verbose_name='Invited', related_name='invited_user' ) number_1 = models.IntegerField( default=1 ) number_2 = models.IntegerField( default=2 ) number_3 = models.IntegerField( default=3 ) date = models.DateTimeField('Created at', auto_now_add=True) class Meta: verbose_name = 'Chat room' verbose_name_plural = "Chat rooms" db_table = 'room' View: class Rooms(APIView): permission_classes = [permissions.IsAuthenticated] @staticmethod def get(request): # rooms = Room.objects.filter(creator=request.user) rooms = Room.objects.all() serializer = RoomSerializer(rooms, many=True) return Respons Serializer: class RoomSerializer(serializers.ModelSerializer): # id = serializers.IntegerField() creator = UserSerializer(read_only=True) invited = UserSerializer(many=True, read_only=True) class Meta: id = serializers.IntegerField(label='ID', read_only=True) model = Room fields = ['id', 'number_1', 'number_2', 'number_3', 'creator', 'invited', 'date'] Request: { "type": "Rooms", "id": "3", "attributes": { "number_1": 1, "number_2": 2, "number_3": 3, "date": "2019-02-08T12:30:39.095971Z" }, "relationships": { "creator": { "data": { "type": "User", "id": "6" } }, "invited": { "data": [ { "type": "User", "id": "3" } ] } } On request room ID and user ID are strings, but i need integer type. Where another field has types integer (number_1, number_2, number_3), its returned as integer. I have no idea how … -
Django background-task throws an exception but executes correctly
I am trying to start Django background-task automatically when Django starts. import os import subprocess import sys from django.core import management if __name__ == "__main__": from django.core.management import execute_from_command_line os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.prod') # Start background tasks if os.environ.get('RUN_MAIN'): management.call_command('background_task') Problem is that I get this exception: Traceback (most recent call last): File "manage.py", line 13, in <module> management.call_command('background_task') File "/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 104, in call_command raise CommandError("Unknown command: %r" % command_name) django.core.management.base.CommandError: Unknown command: 'background_task' The strange thing is that after exception message I get "waiting for tasks" on console and everything works correctly. Tasks get executed without issues. If I try to catch this exception then tasks wont work. Any suggestions how can I avoid this error? -
DRF: Disable GET request on the base url route path
This is my urlpatterns in base urls.py, urlpatterns = [ path('api/', include((router.urls, 'api'), namespace='api')), ] when I browse to localhost:8000/api/, it exposes all my routes, { "accounts": "http://localhost:8000/api/accounts/", "cases":"http://localhost:8000/api/cases/", "issues": "http://localhost:8000/api/issues/" } Is there any way I can disable this exposing on django application level? -
install tar.gz with pip at requirements.txt
i want to install electrum-ltc into my app like this: pip3 install https://download.electrum.org/3.3.3/Electrum-3.3.3.tar.gz#egg=electrum[fast] but if i include this line in my requirements.txt the role-out fails and i have to install it manually with the same line shown above. if i install it like this at the requirements.txt: -e git+https://github.com/pooler/electrum-ltc.git#egg=electrum-ltc some modules do not get installed in that specific case its the script package. so who can i install/link a tar.gz package at the requirements.txt here? thanks in advance -
Django Session Does Not Destroy After Sometime
Django Session does not destroy after sometimes when no activity is done. Even when i don't logout after closing the browser and again hitting the same url it does not logout. It remains logged in. How can i specify that when no activity is done on website then logout after some time. -
The right way to set up permissions for "workspaces" in Django?
I am trying to create a site where users work together in "workspaces". A workspace is like an account for a group of users. Each workspace will have a number of users. There are two user groups: "superusers" and "regular users". A user may be a member of more than one workspace. The user can never belong to both user groups in the same workspace, but the user can be a "superuser" in one workspace and a "regular user" in another. I am trying to find out whether I can create this type of setup using the out-of-the-box permissions framework in Django, or whether the best solution is to create my own supporting tables? My own solition would be a data model like this: I am trying to create a site where users work together in "workspaces". A workspace is like an account for a group of users. Each workspace will have a number of users. There are two user groups: "superusers" and "regular users". A user may be a member of more than one workspace. The user can never belong to both user groups in the same workspace, but the user can be a "superuser" in one workspace and … -
How to order a django model based on ForeignField referring to model
I've got a django model something like class MyModel(models.Model): precedent = models.ForeignKey('MyModel', null=True, blank=True) I would like to order this model based on precedent, ie a record is included after its precedent in a recordset. I recognise I might need to include another field to save an order value and recalculate the order value on a save but wondered if anyone could recommend an efficient way of achieving this. I have tried the following but immediately hit a RecursionnError: def save(self): categories = self.subsequent.all() for category in categories: category.save() self.save() -
How to run python script in Django having some django models in it
I want to execute a python script where I am accessing some django models in order to fetch and store data ,but when I run python script as (python name_of_file.py) it gives me a ModuleNotFoundError and the execution is terminated. -
Django Rest Framework: Update and delete current user without providing pk
I know a lot of people already asked about handling with current user but I couldn't find solution so I post this. What I want to do is to get, put and delete current user without providing pk. I want to set endpoint like users/my_account My current code is here class MyAccountDetail(generics.RetrieveUpdateDestroyAPIView): queryset = CustomUser.objects.all() serializer_class = UserSerializer def get(self, request): serializer = UserSerializer(request.user) return Response(serializer.data) And now I can get current user's info but when I try to update or delete the current user, AssertionError: Expected view MyAccountDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. How can I solve this? -
Wagtail filter page-childs-elements on base of logged in user-permissions
I am working on a small site using wagtail. This site is all about a "mainpage" and several "subpages". So far it is pretty simple! But, depending on what group the user (not admin) is in, the right subpages should show up! In my mind this shouldn´t be that hard. But after serious investigations i counld find a single way to solve this for myself. See the following setup (minialized), just to get a idea of what i am talking about. So if set permissions on contents of ToolKitPart (like required explizit user-login and group-membership) the following is happening: when going explizit to the page using the full qualified path. The user is request to login and in case of insufitient rights, the user will not see the content! when going to the ToolkitIndex-Page all childs are displayed including the ones the user never should see. Wihtout the need to be loggin or beeing member of a certain group. class ToolkitIndex(Page): def get_context(self, request): # Update context to include only published posts, ordered by reverse-chron context = super().get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['pages'] = blogpages return context class ToolkitPart(Page): body = StreamField([ ('staff', MpStaff()), ('news', MpNews()), ('stuff', MpStuff()), ('teditor', blocks.RichTextBlock()), ('reditor', … -
django.template.base.VariableDoesNotExist: Failed lookup for key [get_cart_total ] in 0
I was getting a VariableDoesNotExist error with the following snippet when get_cart_total is 0. This is the function I performed in my models.py: def get_cart_total(self): return sum([item.product.price for item in self.items.all()]) I have done this on my template: {% with order.get_cart_total as total %} {% if total == 0 %} <td>0.00</td> {% else %} <td>{{ total }}</td> {% endif %} {% endwith %} Can any one tell me what I am doing wrong in my code? Thank you -
How can i choose multiple images from django admin panel
How can I choose two or more images from the Django admin panel? I have two model: class UserMedia(models.Model): user = models.ForeignKey(User) image = models.ImageField(upload_to='user_images/', verbose_name='image') file = models.FileField(upload_to='user_files/', verbose_name='file') class GalleryImage(models.Model): image = models.ImageField(upload_to='gallery_images/', verbose_name='image') file = models.FileField(upload_to='gallery_files/', verbose_name='file') I want to choose multiple images from both of the model ImageFields. -
how to display a cross origin iframe in django tempplate
Can someone please add an example of iframe in a template pointing to yahoo.com or google.com I want to add an iframe in my django template, pointing to an external application or website, and I am having hard time using django-csp , setting all its headers. I've already tried using from django.views.decorators.clickjacking import xframe_options_exempt but it didn't solve my issue(load the iframe). I'm looking forward to your help! -
create user before creating object in django rest frameword
I'm using Django 1.5 and Django REST Framework 2 I have a model MultiUser with two fields user and shared_user referencing User model. I have to create shared_user object first from the email in POST data and then create MultiUser object and assign the new user to shared_user and request.user to user. my view is like class MultiUserCreateListView(generics.ListCreateAPIView): model = MultiUser serializer_class = MultiUserSerializer def get_queryset(self): users = MultiUser.objects.get_shared_users(user=self.request.user) return users def create(self, request, *args, **kwargs): email = request.DATA.get('email', None) access_level = request.DATA.get('access_level', None) name = request.DATA.get('name', None) user = User.objects.filter(email=email) if user: return Response({'message': 'Email address already in use.'}, status=status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(data=request.DATA) new_user = create_active_user(request, self, email, email, password=None, is_shared=True) if new_user: if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response({'message': 'Unable to create user. Try again'}) def pre_save(self, obj): print('pre save called') obj.user = self.request.user This gives error as NOT NULL constraint failed: multiusers_multiuser.user_id -
Can upload to AWS S3 using django-storages & boto3 but can't view (403 Forbidden), can't understand why
I followed the guide on: https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html And I have successfully set up buckets and transferred my static files to Amazon S3. However when I try to load the S3 files, I get a 403 Forbidden message. Here is what is in my settings.py file: # AWS s3 (image storage) AWS_ACCESS_KEY_ID = 'XXX' # XXX replaced with the actual key AWS_SECRET_ACCESS_KEY = 'YYY' # YYY replaced with the actual key # sensitive data will be replaced with environment variables when page is public AWS_STORAGE_BUCKET_NAME = 'diceart-static' AWS_S3_CUSTOM_DOMAIN = 's3.eu-west-2.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = None AWS_BUCKET_ACL = None AWS_QUERYSTRING_AUTH = False STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' So when I ran python manage.py collectstatic Everything worked! And I could see all of my files uploaded to Amazon S3. I can also see the time of the programmatic access of this so I know it all worked. Here is the contents of my html template file where I'm hoping to serve the S3 files: {% extends 'dice/base.html' %} {% load crispy_forms_tags %} {% load static %} {% block content %} <form method="post" … -
How to import a mysql database made with mysql workbench into django?
I created a database with MYSQL Workbench 8.0 and I want to import it into Django, so that I can display the data on the browser. How can I do that? -
Select 2 related fields at one query
For example, I have the following models: class Transport(models.Model): pass class Car(models.Model): type = models.ForeignKey(Transport, related_name='cars') class Train(models.Model): type = models.ForeignKey(Transport, related_name='trains') To fetch cars and trains separately I can do the following: Transport.objects.first().cars.all() Transport.objects.first().trains.all() But how can I do it in one query? -
What is difference between JsonResponse and HttpResponse in django
Lets say result = {'a': 1, 'b': 2, 'c': 3} Is there a difference between these two: return HttpResponse(json.dumps(a)) and return JsonResponse(a) -
Render forms for multiple model objects?
I have a portfolio-template which is supposed to display forms for all existing objects in PortfolioModel, however I need the form-tags to enclose all objects with a common 'category_id' so I can submit these objects simultaneously. The field 'category_id' identifies objects that belong to the same 'category'. A 'category' consists of one or many objects, which I want to be able to submit together. The PortfolioFormset is a model formset. I have achieved this functionality for one 'category' at a time by hard coding the 'category_id' in a filtered queryset, but obviously I want to be able to do this with all objects in the PortfolioModel. I have tried creating a for-loop in views, looping through a range of category_id's in the model, setting the queryset filter to the category_id of each cycle, but this ofcourse doesn't give me an output I can render. views.py def PortfolioView(request): template_name = 'portfolio/portfolio.html' if request.method == "GET": portfolio_object = PortfolioFormset(queryset=PortfolioModel.objects.all()) context = { 'portfolio_object': portfolio_object, } return render(request, template_name, context) portfolio.html template <form method="POST"> {% csrf_token %} <table> {{ portfolio_object.management_form }} {{ portfolio_object }} </table> <button type="submit">Update category</button> </form> This does return all objects in the model as expected, however I need to … -
Is it an efficient method to use a framework to code a single interactive webpage in python?
This is an open source contributor project for Wikidata's Chronic Pain project. I would like to create a webpage that : Have inputboxes where the user select several wikipedia page titles (with suggestions) Get items metadata from Wikidata. Makes a SPARQL request to gather scholarly articles. Render data from Wikidata and Wikipedia, linking to various wiki pages. The webpage will be hosted on Wikimedia fundation server. I have access to a linux container as well as a Jupyter Notebook (not sure this one is suitable for this project). It has to be coded in Python 3 since I will use Pywikibot framework to interact with Wikidata. I'm new to programming so that I don't really know what is the best approach. I heard that it was difficult to code webpages in Python without using a framework like Django. However this page is very simple so that it may not be the most efficient to deploy Django for this ? -
Static files uploaded on s3 won't show locally
I just uploaded my statics on S3 and CloudFront. python manage.py collectstatic succeeded. I know the correct behavior now would be that when i run my app locally, all the statics would be running from S3 as the static url had been changed. But none of this happens. I've tried running python manage.py runserver --nostatic : the server runs but all my assets are gone locally (even when i run this command without --nostatic). Here is my settings.py : import os from django.utils.translation import ugettext_lazy as _ import boto3 ... # AWS CloudFront AWS_S3_REGION_NAME = 'us-east-2' # e.g. us-east-2 AWS_ACCESS_KEY_ID = '*******' AWS_SECRET_ACCESS_KEY = '*******' AWS_S3_HOST = 's3-us-east-2.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=1209600, no-transform' } # static BUCKET_STATIC_NAME = '*******' CLOUDFRONT_STATIC_DOMAIN = '*******.cloudfront.net' # media BUCKET_MEDIA_NAME = '*******' CLOUDFRONT_MEDIA_DOMAIN = '*******.cloudfront.net' # storage DEFAULT_FILE_STORAGE = 'elef.custom_storage.MediaS3BotoStorage' STATICFILES_STORAGE = 'elef.custom_storage.CachedStaticS3BotoStorage' MEDIA_URL = 'https://%s/' % CLOUDFRONT_MEDIA_DOMAIN AWS_DEFAULT_ACL = None I also have a custom_storage.py : from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile import boto3 import os from django.conf import settings from django.contrib.staticfiles.storage import CachedFilesMixin class CachedStaticS3BotoStorage(CachedFilesMixin, S3Boto3Storage): """ S3BotoStorage backend which also saves a hashed copies of the files it saves. """ bucket_name = settings.BUCKET_STATIC_NAME custom_domain = settings.CLOUDFRONT_STATIC_DOMAIN def _save_content(self, obj, content, parameters): content.seek(0, … -
Load data that has models with ImageField in django
Any idea how to load data that has models with ImageField in django? I cannot use fixtures for this as there’s no way to serialize images into the fixtures files. I’m trying to use factory-boy which works very well for tests but I cannot see how to run it as a standalone script because there’s no django management command for it. Is python manage.py shell < myscript.py a good approach to handle this or there’s a better way? Note that I’m using a bucket for file storage with salted filenames, and I have signals that do stuff like indexing into Elasticsearch which I need to keep. and fixtures don’t do this.