Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Please enter a valid date/time django error
i suddenly got an error. Please enter a valid date/time. It used to work just fine but I don't know what's going on now LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = False USE_TZ = False DATE_INPUT_FORMATS = ['%d-%m-%Y %H:%M'] class JobForm(forms.ModelForm): class Meta: model = ShiftPlace fields = ['add','medewerker','job_type','firmaName','date','dateTo','adress','postcode','HouseNumber','city','comment'] widgets = { 'date': DateTimePickerInput(), 'dateTo': DateTimePickerInput(), 'comment':forms.Textarea, class DateTimePickerInput(forms.DateTimeInput): input_type = 'datetime-local' date_format=['%d-%m-%Y %H:%M'] -
Django localization - translating models cross apps
I'm translating model choices in a django APP but the local APPs do not use the localized string. I have an APP named base_app with the following model: class User(AbstractUser): LIVING_AREA_CHOICES = ( ('urban', _('Urban')), ('rural', _('Rural')), ) name = models.CharField( _('Option Name'), null=True, max_length=255, blank=True ) def __str__(self): return self.name or '' living_area = models.CharField( _('Living Area'), choices=LIVING_AREA_CHOICES, max_length=255, null=True, blank=True ) ... other stuff... This model is used in a modelform of forms.py from courses_app (added as external app through requirements.txt of base_app): model = get_user_model() fields = ('username', 'email', 'name', 'first_name', 'last_name', 'image', 'occupation', 'city', 'site', 'biography', 'phone_number','social_facebook', 'social_twitter', 'social_instagram', 'preferred_language', 'neighborhood', 'living_area', 'race', 'birth_date','city', 'gender') and rendered in profile-edit.html, template of a third app (client_app configured in .env): {% with errors=form.living_area.errors %} <div class="form-group{{ errors|yesno:" has-error,"}}"> <label class="col-xs-12 col-sm-3 col-lg-2 control-label" translate>Living area </label> <div class="col-xs-12 col-sm-9 col-lg-10"> {{ form.living_area }} {% for error in errors %}<small class="warning-mark">{{error}}</small>{% endfor %} </div> </div> {% endwith %} I've already tried to use localized_fields = ('living_area',) in forms.py with no success. The only way I've got it working is adding the strings of LIVING_AREA_CHOICES inside client_app's po/mo files. Is there a way for the client_app template to retrieve the … -
How do I create a unique number for Django model objects?
I am working on a project where a user can create a card under their company. Unfortunately, the databases indexes all the cards, regardless of the company. I would like to create a unique number for all the cards but serialised according to the company, e.g like creating an invoice number that will always be unique. The two models are here: class Company(Organization): name = models.Charfield(max_length=256, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) email = models.EmailField(null=True) date_created = models.DateField(default=timezone.now, null=True) class Card (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='card_user', null=True) thecompany = models.ForeignKey(Company, related_name = "company_card", on_delete=models.CASCADE, null=True) date_created = models.DateField(default=timezone.now) card_number = models.PositiveIntegerField(default=1, null=True, editable=False) def save(self, *args, **kwargs): if self.card_number == 1: try: last = Card.objects.filter(thecompany=self.thecompany).latest('card_number') self.card_number = last.card_number + 1 except: self.card_number = 1 super(Card, self).save(*args, **kwargs) I can sequence the objects created according to the company, using the card_number field on Card. Below is the model: The save method works well and maintains Card_Number sequence even when you delete cards, up until you delete the card object with the largest number. Then if you create a card object after you have deleted the card with the largest card_number, it repeats. I thought of creating a list with … -
How to hit a json database index in Django query?
I created an index on a models.JSONField in my postgres db. class Meta: indexes=[ models.Index(KeyTextTransform('id', 'my_json_field'), name='my_json_id_idx') ] i wrote some sql on pg_indexes to verify and it is there CREATE INDEX my_json_id_idx on my_model USING btree (((my_json_field ->> 'id'::text))) One thing to note is it uses ->> which means it casts to text im pretty sure. So then if i try to query like this my_query = MyModel.objects.filter(my_json_field__id=1234) If i analyze with my_query.explain(analyze=True) it shows a sequential Scan. It does NOT hit my index at all. When i look at the SQL of the query i think im noticing the difference is it uses Filter: (my_model.my_json_field -> 'id'::text) = '1234'::jsonb Or if i just look at the SQL of the query it basically is: select * from my_model where (my_json_field -> id) = 1234 I think the -> in the query vs --> in the index is what makes the discrepancy. What is the proper way to write the query so it hits the index, or should i rewrite the index so it uses -> ? Does anyone know how to rewrite the statement in the indexes so that it creates it with -> ? P.S I can write … -
How to use sync_to_async() in Django template?
I am trying to make the Django tutorial codes polls into async with uvicorn async view. ORM query works with async view by wrapping in sync_to_async() as such. question = await sync_to_async(Question.objects.get, thread_sensitive=True)(pk=question_id) But I have no idea how to apply sync_to_async or thread inside Django templates. This code fails saying 'You cannot call this from an async context - use a thread or sync_to_async.' Or any other way to work around this? {% for choice in question.choice_set.all %} I use Python 3.10, Django 4.0.4 and uvicorn 0.17.6 -
Django runserver not worked after login
I used this command: python manage.py runserver 0:8080 After I logined the system I can reach rest API pages, but can't reach other pages. Although I send a request, the command output does not log. Quit the server with CONTROL-C. -
Django and Celery: unable to pickle task kombu.exceptions.EncodeError
I have this async Celery task recalculate_emissions_task.delay(assessment, answers,reseller, user) where the parameters supplied are all Django objects, my task function is defined like this @app.task @transaction.atomic def recalculate_emissions_task(assessment, answers, reseller, requesting_user=None): for ans in answers: approver = None if ans.is_approved: approver = ans.approver auto_approved = ans.auto_approved auto_approval_notes = ans.auto_approval_notes ans.unapprove() ans.report_upstream_emissions = ans.scope in assessment.scopes_for_upstream ans.report_transmission_and_distribution = assessment.report_transmission_and_distribution ans.for_mbi_assessment = assessment.uses_mbi if approver: ans.approve( approver, auto_approved=auto_approved, auto_approval_notes=auto_approval_notes ) else: ans.save() and the error I am receiving is : Traceback (most recent call last): File "dir/bin/django-python.py", line 18, in <module> runpy.run_path(path, run_name='__main__') File "/usr/lib/python3.8/runpy.py", line 265, in run_path return _run_module_code(code, init_globals, run_name, File "/usr/lib/python3.8/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "test.py", line 15, in <module> recalculate_emissions_task.delay(assessment, answers,reseller, user) File "dir/lib/python3.8/site-packages/celery/app/task.py", line 427, in delay return self.apply_async(args, kwargs) File "dir/lib/python3.8/site-packages/celery/app/task.py", line 566, in apply_async return app.send_task( File "dir/lib/python3.8/site-packages/celery/app/base.py", line 756, in send_task amqp.send_task_message(P, name, message, **options) File "dir/lib/python3.8/site-packages/celery/app/amqp.py", line 543, in send_task_message ret = producer.publish( File "dir/lib/python3.8/site-packages/kombu/messaging.py", line 167, in publish body, content_type, content_encoding = self._prepare( File "dir/lib/python3.8/site-packages/kombu/messaging.py", line 252, in _prepare body) = dumps(body, serializer=serializer) File "dir/lib/python3.8/site-packages/kombu/serialization.py", line 221, in dumps payload = encoder(data) File "/usr/lib/python3.8/contextlib.py", line 131, in __exit__ self.gen.throw(type, …