Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python deploying django with django channels on heroku
I have been trying to deploy my application on heroku with django channels and I always get the following error 2022-05-26T20:09:58.137436+00:00 app[web.1]: ModuleNotFoundError: No module named 'core' I have seen previous questions such as Deploying asgi and wsgi on Heroku but even when following these steps I can't get the deployment to work. My channel layers in settings.py: ASGI_APPLICATION = "server.asgi.application" CHANNEL_LAYERS = { 'default': { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')] }, 'ROUTING': 'server.routing.channel_routing', } } My asgi.py: import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = get_asgi_application() My wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') application = get_wsgi_application() My Procfile web: daphne server.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 chatworker: python manage.py runworker --settings=server.settings -v2 My file structure server | |_ _ chat | | | |_ __init__.py | | | |_ admin.py | | | |_ consumers.py | | | |_ models.py | | | |_ routing.py | | | |_ urls.py | | | |_ views.py |_ _ server | | | |_ __init__.py | | | |_ asgi.py.py | | | |_ routing.py | | | |_ settings.py | | | |_ urls.py | | | |_ wsgi.py | |_ _ … -
Localize dependency model name
I want to localize the DJANGO OAUTH TOOLKIT app and models names. But as it's a dependency, it's not included in my project as a custom app and I cannot change the verbose name from verbose_name = "Django OAuth Toolkit" to verbose_name = _("Django OAuth Toolkit") I could just include oauth2_provider as a entire app inside my project, but in case we need to update that dependency with a new version published in github, we should replace the entire folder. Can I just override the oauth2_provider models verbose names without creating a new Class that inherits from the original oauth2_provider class that exists as a project dependency? -
HighlightJS not highlighting certain code fragments
I'm using HighlightJS to format code that's being stored in a model's TextField of my Django application. Here is the template HTML: <pre> <code class="{{ compiler.highlight_js_alias }}">{{ compiler.unit_test_boilerplate_code }}</code> </pre> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/default.min.css" <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script> <script>hljs.highlightAll();</script> Example output: <pre> <code class="ruby hljs language-ruby"> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Person</span> : <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span> ( <span class="hljs-params"> <span class="hljs-variable language_">self</span>, name, age</span> ): <span class="hljs-variable language_">self</span> .name = name <span class="hljs-variable language_">self</span> .age = age me = Person( <span class="hljs-string">"Nathan"</span> <span class="hljs-number">32</span> ) print(me.name) </code> </pre> Why are certain fragments not highlighted? Thank you for any advice. -
Do I need to have AWS CLI to use Boto3?
I have a Django application that needs to use Boto3 to create and manage EC2 instances. When I host the Django application, do I need to install AWS CLI in the server to use Boto3 in the Django application? -
Django Rest Framework Nested Serializers with multiple types of Query Filters
Sorry for the not so descriptive title, hard to put into words what I am trying to do. My Models have various Many to Many relationships. I am trying to make my Serializers act in a very similar way to the queries I listed out below. Essentially, I am looking to get my TeamStats Model Serialized in various ways. If I need the whole leagues stats, I filter by season, if just a single team, I filter by team etc. These queries will also be read only, they won't be written to, they are just for viewing purposes on the front end. In addition, I need the serializer to be nested in such a way that whatever is filtering the query, is top data in JSON. For example, if I was doing TeamStats by Season, I would have Division Nested inside of Season, Team nested inside of Division. If I was just calling TeamStats by Division, I would have just Team nested inside of Division. Models class BaseModel(LifecycleModelMixin, models.Model): date_modified = models.DateTimeField(auto_now=True) date_created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: abstract = True class SeasonTest(BaseModel): name = models.CharField(max_length=50) class DivisionTest(BaseModel): name = models.CharField(max_length=50) seasons = models.ManyToManyField(SeasonTest, through='SeasonDivision') … -
Change webpage logo for every user in django
How can I change website logo for every other user login into django platform? For example: User-A when login, will see different logo on website, while User-B will see different and so on. -
Django exclude only works with get_context_data
Can I use exclude() without having to use get_context_data with generic class based views? I want to exclude the is_removed for the soft delete. I have seen examples where it's not used. It only works with a form variable school_district_model_form with an SchoolApplicationModelForm in get_context_data and using it in the template. Below works. I was expecting the default form variable in the template to exclude the fields and it still includes all fields. models.py class SchoolDistrictModelForm(forms.ModelForm): class Meta: model = SchoolDistrict exclude = ("is_removed",) view.py class SchoolDistrictCreateView(SchoolDistrictBaseView, CreateView): """View to create a new school district""" def get_context_data(self, **kwargs): context = { "school_application_model_form": SchoolApplicationModelForm(), } return context schooldistrict_form.html <div class="container d-flex justify-content-center mt-5" style="width: 25%;"> <div class="col mt-5"> <form action="" method="post"> {% csrf_token %} <table class="table"> {{school_district_model_form.as_table}} </table> </form </div> </div> -
django add likes user blog post
am quite new to django and am trying to make a blog in django but cant figure out how to add a few key features. How can i make my code so other ppl also can make blog posts ? how can i add a like/dislike button with counter on all blogposts created? How can i add so you can add pictures to the posts so they show on the front page so you dont have to click in to the post to see them? Would be very appreciated if someone could help me with this since am not quite sure how to do it. code is below: This is my code: APP Folder views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from .models import Post from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to … -
How to display the total number of votes in a Poll?
I have a simple voting application. models: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text results.html: {% extends 'base.html' %} {% block content %} <h1 class="mb-5 text-center">{{ question.question_text }}</h1> <ul class="list-group mb-5"> {% for choice in question.choice_set.all %} <li class="list-group-item"> {{ choice.choice_text }} <span class="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span> </li> {% endfor %} </ul> <a class="btn btn-secondary" href="{% url 'polls:index' %}">Back To Polls</a> <a class="btn btn-dark" href="{% url 'polls:detail' question.id %}">Vote again?</a> {% endblock %} How to make the total number of votes for each question so that you can display total: and the total number of votes for this poll at the bottom. -
Refused to apply css styles in my Django App, because its MIME type its not supported
I have a serious problem with my Django application and is that I do not load the styles in my app, the error I get in console is as follows: "It has been rejected to apply the style of 'http://127.0.0.1:8000/static/static/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled". "ailed to load resource: the server responded with a status of 404 (Not Found)" Settings.py: """ Django settings for DjanPro project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from email.mime import application from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # IMPORT MODULES import os # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-5%wdpom7_!0w5wx&qfv2_e@riio6&dqv$h!h_8ly_nk^2=w!pz' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'clase', 'index', 'accounts', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
How to avoid the magnifying zoom my cropbox has in Cropper js?
Im using Cropper JS by fengyuanchen. When my cropper loads everything looks ok. But when I resize the window the cropbox zooms in the image. This is how it loads: And this is how it ends after the window resizing: The is a zoom effect in the cropbox that I don't want. I'd like to be able to resize the window and avoid the zoom effect in the cropbox. Below are my cropper and container specifications: Cropper: croper() { const image = document.getElementById('image'); const cropper = new Cropper(image, { responsive:false, autoCropArea:1, zoomable:false, movable: false, aspectRatio: NaN, viewMode: 2, crop(event) { console.log("***********************************"); console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); this.data = this.cropper.getData(); document.getElementById("demo").innerHTML = JSON.stringify(this.data); var contData = cropper.getContainerData(); //Get container data }, }); cropper.setCropBoxData({ height: contData.height, width: contData.width }) //set data } Container: <div class="col-md-8 col-sm-6 grid-margin stretch-card" id="image_box" align="center"> <div class="card text-center" style=" overflow: hidden; height: 100vh;"> <!-- <div class="card-body"> --> <!-- <label id="file-drag"> --> <img id="image" style="max-width: 100%; display: block; " src="static/template/{{img}}.png" alt="Preview"> <span id="preview">La vista previa de la imagen de la plantilla irá aquí</span> <!-- </label> --> <!-- </div> --> </div> </div> Thanks! -
Django + Gunicorn + Nginx + Python -> Link to download file from webserver
On my webpage served by a Debian web server hosted by amazon-lightsail behind nginx and gunicorn, a user can send a request to start a Django view function. This function add some work to a background process and check every 5s if the background process created a file. If the file exists, the view sends a response and the user can download the file. Sometimes this process can take a long time and the user get a 502 bad gateway message. If the process takes too long, I like to send the user an email with a link where he can download the file from the web server. I know how to send the email after the process is finished, but I don't know how to serve the file to the user by a download link. This is the end of my view function: print('######### Serve Downloadable File #########') while not os.path.exists(f'/srv/data/ship_notice/{user_token}'): print('wait on file is servable') time.sleep(5) # Open the file for reading content path = open(filepath, 'r') # Set the mime type mime_type, _ = mimetypes.guess_type(filepath) # Set the return value of the HttpResponse response = HttpResponse(path, content_type=mime_type) # Set the HTTP header for sending to browser response['Content-Disposition'] … -
How can I send email using python with google workspace
I just signed up for the Google workspace business starter because of lots of recommendations from people, I would like to know how possible is it to send email via my backend API using Django, I've searched for it online but nothing comprehensive or direct, try to contact their support but not available. Thanks in advance -
ValueError: I/O operation on closed file in Django and DRF when saving data to model
I am trying to save a file to the Django instance the following way: class SomeName(ListCreateAPIView): queryset = fileUpload.objects.all() serializer_class = fileUploadSerializer def create(self, request, *args, **kwargs): file = serializer.validated_data["file"] object = fileUpload.objects.create( file_local_storage=file, file=file, ) ..... The models is class fileUpload(models.Model): fileName = models.CharField(max_length=200, unique=True, blank=True) file = models.FileField(storage=PrivateMediaStorage()) file_local_storage = models.FileField(upload_to="uploads/", blank=True) The error I get is ValueError: I/O operation on closed file in Django and DRF when wrting data -
How Can Update Python Version to be the same with the version on Cpanel Hosting Python App
I have fully developed my Django App using Python Version 3.9.1 and after purchasing Cpanel Python Hosting I realized that there was no version 3.9.1 rather the closer version on their Python App Installation was Version 3.9.12. I am confused on which version to choose that can work perfectly without errors. I have opened a Ticket to their support but no response till now so I need your professional advise. -
How to get out of nested for? In Django Template
I have a nested loop to display content and apply terms in my template. {% for class in class %} {% if saveclass %} {% for saveclass in saveclass %} {% if class.colecl in saveclass.saveclass_tag %} save class exists! {{ class.levelclass_name }}<br> {% else %} save class not exists! {{ class.levelclass_name }}<br> {% endif %} {% endfor %} {% else %} there is nothing save class {{ class.levelclass_name }}<br> {% endif %} {% endfor %} The first loop gives me the list of classes. Then it is checked whether the saveclass variable exists or not, if there is, the second loop is executed. In the second loop it gives me saveclass and I check if the class tag is in the saveclass table and I display the output. The problem is that the inner circle has to end to get to the next class. And for this reason, both the first if and its else are executed. Python and other languages use breaks for this, but Django does not have a break template. What is your solution? Thank -
Django - how to save user uploaded data both locally and in the cloud?
When the user uploads some data to Django, I would like to create both a local copy and a cloud copy. The following succesfully creates a cloud copy, how can I modify it so it creates a local copy too? class fileUpload(models.Model): fileName = models.CharField(max_length=200, unique=True, blank=True) file = models.FileField(storage=PrivateMediaStorage()) class PrivateMediaStorage(S3Boto3Storage): location = "rawFiles" file_overwrite = False default_acl = "private" -
Function reserved for each user in Django
I have my function/python code which is used to clean data from my database according to user request, Now for every user's request python code is executed, if 1000 user ask for different - different parameters then python code/function has to be executed for 1000 times by which user have to wait for very long becz it's single function which will be running for single user at each time. Is their any way to duplicate or make a executable copy of python function which will be reserved for each user.? -
Django | Serializer for Foreign Key
I got two models Book and Author implemented like this: class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey(Author, on_delete=models.CASCADE) In addition to this I got the following Serializers: class AuthorSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=50) class BookSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=50) author = AuthorSerializer() Serializing objects works without any problems. Now I got the following situation: Author's: id name 1 Josh Robert 2 J. R. R. Tolkien 3 Mike Towers I get a POST request to an API endpoint on my server http://127.0..0.1:8000/api/book looking like this: payload = { 'name': 'Lord of the rings', 'author': 2 } How can I use my Serializers to create a new Book with the given name and link it with the author no. 2? -
Get parents by filtering two date range in childs table with Django ORM
I have two tables with this informations: Room id room name 1 room 1 2 room 2 and a child table with this information: Reservation id room id (reserved_rooms) from date to date 1 1 2022-05-20 2022-05-22 2 1 2022-05-23 2022-05-25 I want to get available rooms for a certain amount of time: Witch doesn't have any reservation rooms where no reservation has been made at a specific time such as 2022-05-24 I tried the following code, but the problem is that the booked room is returned with id=1, while it has a reservation on the desired date. Room.objects.filter(Q(reserved_rooms__isnull=True) | Q(reserved_rooms__from_date__gt=date) | Q(reserved_rooms__to_date__lt=date)) This query ignored reservation with id=2, because 2022-05-23 < 2022-05-24 < 2022-05-25, but reservation with id=1 causes that room with id=1 is returned. because 2022-05-24 not in range 2022-05-20 and 2022-05-22. so I expected that the only room with id=2 would be returned, but both 1 and 2 were returned. What is your suggestion to solve this challenge? -
Upload data to the cloud and Django instance storage
I have set my Django application to upload files to AWS and it works fine. When I upload a file, I see it in the cloud storage and the django admin has a downloadable URL. Here is the code anyways. In the settings.py MEDIAFILES_LOCATION = env("AWS_S3_ENDPOINT_URL") + "media" In the models class fileUpload(models.Model): fileName = models.CharField(max_length=200) file = models.FileField(storage=PrivateMediaStorage()) In the FileField class PrivateMediaStorage(S3Boto3Storage): location = "rawFiles" file_overwrite = False default_acl = "private" And in the views def create(self, request, *args, **kwargs): .... file = serializer.validated_data["file"] object = fileUpload.objects.create(file=file, fileName=name) .... When I check the Admin panel, I am able to download the file from the file url from model into my computer. I want to retrieve this file that I have uploaded into AWS and run some calculation on it using Django. How can I modify the fileUpload upload class to also store the data locally in the Django? (I am also open to alternative approaches). -
How to create postgres db index for a jsonfield in Django using the ORM?
I made a migration and added this exact sql: migrations.RunSQL("CREATE INDEX my_json_idx on my_table((my_json_data->'id'));") It works. All i'm trying to do is, get this exact equivalent but using the Django ORM so that I can put something in my models.py file in the class Meta: indexes=[...] That way it can all be managed at the "code" level and have django take care of the rest. I tried this: models.Index(KeyTextTransform('id', 'my_json_data'), name='my_json_idx') This creates an index fine, but it uses ->> something like CREATE INDEX my_json_idx on my_table((my_json_data->>'id'));") Which is a problem because queries from the django orm such as my_table.objects.filter(my_json_data__id=123) get translated into -> by the ORM. And the index ends up getting skipped. It does a full scan. -
Django Ratelimit custom method
I try to limit the pages of one of my site with django-ratelimits. But how can I limit with custom methods. For example if the rate is 3/m then if you fill out a form and press enter then this will count as a visit for the limiter. Something like flask-limiter cost methods. -
How to access a postgres container through its name? Could not translate host name error
I have a django and postgres containers. When it's time for django to apply migrations, it doesn't see a postgres container that I named pgdb and I get this error: django.db.utils.OperationalError: could not translate host name "pgdb" to address: Temporary failure in name resolution It appears that there is no docker container with name "pgdb". If I run "docker-compose run pgdb" it creates a postgres container with a name of "app_pgdb_run_23423423" under the "app" group. The cute thing is that I made it work previously with this settings.py setup and "pgdb" postgres container name. What could be the underlying issue? You can clone the full code from https://github.com/UberStreuner/mailing-service My settings.py setup, the environment variables definitely aren't at fault. DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE', 'django.db.backends.postgresql_psycopg2'), 'NAME': os.environ.get('POSTGRES_DB'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': os.environ.get('POSTGRES_HOST', 'pgdb'), 'PORT': os.environ.get('POSTGRES_PORT', '5432') } } docker-compose.yml version: "3.8" services: django: build: . container_name: django command: ./docker-entrypoint.sh volumes: - .:/usr/src/app/ ports: - "8000:8000" env_file: - ./.dev.env depends_on: - pgdb - redis celery: build: . command: celery -A mailing worker -l INFO volumes: - .:/usr/src/app/ env_file: - ./.dev.env depends_on: - django - redis - pgdb celery-beat: build: . command: celery -A mailing beat -l INFO volumes: - … -
Django Checkbox Multiple Select to SQLite [closed]
I will be specific I have a problem! There is a modal with a list of data that I get from a table in a database in sqlite, I have implemented a checkbox in each row, I want to achieve that when selecting each row with the checkbox, that selection when clicking on the button " adjust" I save it in another table of the database. HOW DO I ACHIEVE THIS? I need your help Imagen de Referencia