Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django failing send email within a view
Hi I am trying the send email within the update view, when I put the view in test.py, and run test.py, it is working import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') from django.core.mail import send_mail send_mail('Notification from covid-tracker application', 'You have a new notifications from the application, please go to dashboard to confirm ', 'covidtracker390@gmail.com', ['zosanivan@gmail.com']) But when I tried to put it in the updateview it doesn't work, how to fix that? class PatientUpdateViewSet(generics.UpdateAPIView): # permission_classes = (permissions.IsAuthenticated,) # queryset = Patient.objects.all() serializer_class = RegisterPatientSerializer def get_object(self): # print("---------------------------------------------------------------") # print(self.request.data) return Patient.objects.get(user_info=self.request.data.get('user_info')) def perform_update(self, serializer): instance = super(PatientUpdateViewSet, self).perform_update(serializer) send_mail('Notification from covid-tracker application', 'You have a new notifications from the application, please go to dashboard to confirm ', 'covidtracker390@gmail.com', ['zosanivan@gmail.com']) return instance I want when I run python manage.py and when I use this view the email is sent, how to fix this problem? -
Issue Defining Functions with python
Am verifying a payment with paystack and I have a model with amount, ref, verify status already. when this view below is passed the staus automatically update as successful. But am having issue defining an action i want immediately this payment is verified. CLARIFICATION I want the amount paid added to the user balance on the website but writting this code seems difficult for me. class PayStack: PAYSTACK_SECRET_KEY = settings.PAYSTACK_SECRET_KEY base_url = 'https://api.paystack.co' def verify_payment(self, ref, amount, *args, **kwargs): path = f'/transaction/verify/{ref}' headers = { "authorization": f"Bearer sk_test_bbvvgfffggg6517d22e20784a85eeeb5f7b4 ", "Content-Type": 'application/json' } url = self.base_url + path response = requests.get(url, headers=headers) user = request.user if response.status_code == 200 : response_data = response.json() with transaction.atomic(): account = Account.objects.select_for_update().get(user=request.user) account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) return response_data['status'], response_data['data'] response_data = response.json() return response_data["status"], response_data["message"] i want this to happen immediately the payment is verified with transaction.atomic(): account = Account.objects.select_for_update().get(user=request.user) account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) -
Is there any way to store list in database in django?
this is the list I have to insert in the database i get this error while inserting in the database -
How does one write Python code that merges 2 files created using wkhtmltopdf into 1 pdf file using pypdf2
I have an application with the back-end written in Python that converts html files to pdf files. To do this it implements wkhtmltopdf (https://wkhtmltopdf.org/). It currently works perfectly for creating a single PDF file from an html file and outputs that to the user. However, I need to be able to create multiple separate PDF files and then merge the files together into a single PDF. I have been trying to do this using Pypdf2 with the PdfFileMerger() function (https://pythonhosted.org/PyPDF2/PdfFileMerger.html) and haven't been able to do it. I keep getting 'bytes' object has no attribute 'seek' Here is my current code: def multi_test_sheet(request, equipment_id): if not request.user.is_authenticated: return render(request, "jobs/login.html", {"message": None}) from io import BytesIO from PyPDF2 import PdfFileReader, PdfFileMerger if not request.user.is_authenticated: return render(request, "jobs/login.html", {"message": None}) equipment = Equipment.objects.filter(pk=equipment_id).first() if not job: raise Http404("test sheet error. Error code: get job failed") pdf_write = PdfFileWriter() user_properties=UserProperties.objects.get(user=request.user) context = { "equipment": equipment, "job": equipment.equipments, "test_sheet": equipment.sheet_eq, "user_properties": user_properties, "now": datetime.now().strftime("%b-%d-%Y %H:%M"), "now_date": datetime.now().date() } html_sheet = render_to_string('jobs/test_sheet_gear1.html', context) html_sheet2 = render_to_string('jobs/test_sheet_gear2.html', context) pdf_content1 = pdfkit.from_string(html_sheet, None) pdf_content2 = pdfkit.from_string(html_sheet2, None) pdfadder = PdfFileMerger(strict=False) pdfadder.append(pdf_content1) pdfadder.append(pdf_content2) pdf_adder.write("combined_sheets.pdf") response = HttpResponse(pdf_adder, content_type="application/pdf") response["Content-Disposition"] = f"filename={equipment.site_id}.pdf" return response -
How do I create a Django / Ajax redirect POST request on click?
I have a search function in my django app using ajax. It displays all results from a model. I want to limit the number of results the search returns on the page though, so when the queryset is so large the user should click on a 'see all results', rather than having heaps of results in the search box. I'm trying to do this by adding a HTML form below, but when I click on the href it is creating a GET request. I'm not totally sure what I need to fix up here to pass the data to the view and render the new page. resultsBox.innerHTML += ` <a href="${url} ${'results'}" class="item"> <form method="POST" class="post-form" input type="submit" {% csrf_token %} <action="${url} ${'results'}"> </form> <div class="row mt-2 mb-2"> <div class="col-2"> img placeholder </div> <div class="col-10"> <h5>See all results for "${quote}"</h5> </div> </div> </a> ` ` -
SMTPSenderRefused Error using Django and Sendgrid
I've been struggling for days trying to get SendGrid to send an email from a contact page on a website I'm building. First, it was SMTPServerDisconnected errors, and I think I fixed that now it's this SMTPSenderRefused Error. settings.py #Load environment variables from .env file SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') #Email for contact form EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY DEFAULT_FROM_EMAIL = 'some-email@hotmail.com' SENDGRID_SANBOX_MODE_IN_DEBUG = False views.py: def contact(request: HttpRequest) -> HttpResponse: if request.method == "GET": form = ContactForm() elif request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): name = bleach.clean(form.cleaned_data["name"]) email = bleach.clean(form.cleaned_data["email"]) subject = f'Message from {name} about {bleach.clean(form.cleaned_data["subject"])}' message = bleach.clean(form.cleaned_data["message"]) recipients = [settings.DEFAULT_FROM_EMAIL] try: send_mail(subject, message, email, recipients, fail_silently=False) except BadHeaderError: return render(request, "contact.html", {"form": form, "success": False}) form = ContactForm() return render(request, "contact.html", {"form": form, "success": True}) else: raise NotImplementedError return render(request, "contact.html", {"form": form}) I've switched between fail_silently=False and fail_silently=True, but when it's true the email doesn't send through anyways so I've just left it false for now. Lastly, here is the traceback I got: Environment: Request Method: POST Request URL: http://localhost:8000/contact/ Django Version: 4.0 Python Version: 3.9.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
How do you insert a record in an empty Django migration?
I'm using Django 3.2 with a PostGres 14 db. I have the following model ... class Vendor(models.Model): class VendorNames(models.TextChoices): MYCO = 'MyCo', _('MyCo') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, null=False, choices=VendorNames.choices) objects = VendorManager() I have created an empty migration with python manage.py makemigrations --name insert_binance_vendor_record cbapp --empty and now I would like to populate it with an operation to insert a record into my Vendor table. How do I do that? -
Sending data from template to Django views via button
I'm trying to create a delete button in my template: <button type="submit" class="btn btn-danger" value={{ instance.name }}> Delete </button> And I want this button to submit that data in my views.py : instance_client = compute_v1.InstancesClient() if request.method == "POST": instance = request.POST['data'] instance_client.delete(project='xxx', zone='xxx', instance=HERE_I_WANT_THE_DATA) It's a script that will delete an instance from gcloud. But I don't know exactly how to deliver the data from the template to views.py. I'm using Bootstrap 5. -
Generic ManyToMany for multiple inherited models
First of all, the following code is not an example of best practices in DB modelling and I know it, unfortunately, this is already made and it's what it is. Remodelling everything is just not an option. I have the following models: models.py class OtherModel(models.Model): ... class AbstractSite(models.Model): class Meta: abstract = True class Site(AbstractSite): ... class Banner(Site): data = models.ManyToManyField(OtherModel, blank=True) The issue is, this many-to-many is supposed to be present both in the Site and the Banner models. I've tried to specify it in the Abstract Model, and it created a site_data table, but data saved in the Banner model was also populating this table, instead of populating a banner_data as I was expecting. The easiest way is to create a new field in the Site model, named differently from the data field in the Banner model, but this doesn't seem to be correct, since any new child model would need a new table being declared. I was expecting to find a way to dynamically allocate this in the DB. Is there a way to create a dynamic through parameter that follows the class child class name? -
Getting error not found url while making post request to specific url with htmx in Django
I am making like function to my blog without page refreshing. But getting error [06/Apr/2022 20:48:26] "POST /like/post/4/ HTTP/1.1" 404 3945 Here what I do base.html with htmx settings <!-- Load from unpkg --> <script src="https://unpkg.com/htmx.org@1.7.0"></script> <script> document.body.addEventListener('htmx:configRequest', (e) => { e.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) </script> views.py def add_like_post(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return HttpResponseRedirect(post.get_absolute_url()) urls.py urlpatterns += [ path('like/post/<int:pk>/', add_like_post, name='like-post'), ] post-detail.html {#<form method="post" action="{% url 'like-post post.id %}">{% csrf_token %}#} <button hx-post="{% url 'like-post' post.id %}" hx-target="#likes" id="likes" hx-swap="outerHTML" class="btn btn-block btn-outline-secondary btn-lg mb-2 mx-auto" name="post_id" value="{{ post.id }}"><i class="fa fa-thumbs-up"> L i k e - {{ post.number_of_likes }}</i></button> {# </form>#} It works fine when I remove htmx settings from button and adding type='submit' and also uncommenting form. Is there are anything which I did wrong -
How to get all field details in a django LogEntry()
I have a LogEntry items I'dlike to call one by one to make a table. So far I have managed to get it working partially with this. <table class="layout"> <thead> <th>User</th> <th>Date</th> <th>Log</th> <th>Item Affected</th> <th>Item ID</th> </thead> {% for log in logs %} <tr> <td>{{ log.user}} - {{ log.user_id }}</td> <td>{{ log.action_time|date:"d/m/Y - g:ia" }}</td> <td>{{ log }}</td> <td>{{ log.object_repr }}</td> <td>{{ log.object_id }}</td> <td>{{ log.change_message }}</td> </tr> {% endfor %} </table> <td>{{ log.change_message }}</td> Gives me data in this format. [{"changed": {"fields": ["Borrower id"]}}] When I try {% for log in logs %} {{ log }} {% endfor %} I get data in this format. Changed “Smart Maths:-MAT/1663/21” — Changed Borrower id. What would I call in my template in order to get this last part only???? Changed Borrower id -
Django/Python - overwrite initial loaded values
I'm quiet new to Django, and I've been struggling with the following: I have a view that initially has set1=0(False) and set2=1(True). A user can swap this,so to set set1=1(True) and set2=0(False). The user can do this by pushing the 'Update' button. My problem is, that it does change in the backend, but the frontend/view/html is not updated. And I have no idea why.. I created a small example, which, if this works, I'll also get my Django case working.. I have the following: views.py So first this view is used, and the initial values for set1 and set2 are set: class MainSettingsView(generic.TemplateView): extra_context = {"main_page": "active"} context_object_name = 'main' template_name = 'index.html' set1 = int(model.set1 == True) set2 = int(model.set2 == True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) model = Setting12.objects.get(pk=1) context['set1'] = int(model.set1 == True) context['set2'] = int(model.set2 == True) return context And then, based on the chosen option in the radio buttons, it changes the model/db and therefore also the set1 and set2: class UpdateButton(generic.TemplateView): extra_context = {"main_page": "active"} context_object_name = 'setting12' template_name = 'index.html' def post(self, request, queryset=None, *args, **kwargs): if update_type == "set1": model = Setting12.objects.get(pk=1) model.set1 = True model.set2 = False return redirect(reverse("main")) elif … -
Can there be two celery instances in a django application?
I have a use case of using two celery instances in a same django application. One celery instance is used for incoming events to the app and the other is to publish an event to an external django application. Doing this is making connections to the celery workers timeout and blocking both the instances. -
Problem with adding objects to manytomany fields
I have a User model: class User(AbstractUser): followers_num = models.IntegerField(default=0) followings_num = models.IntegerField(default=0) followers = models.ManyToManyField('self', null=True, blank=True) followings = models.ManyToManyField('self', null=True, blank=True) And there's a view for adding/removing user objects from followers/followings: def follow(request, follow, user): if (request.method == 'PUT'): following_user = User.objects.get(username=user) follower_user = User.objects.get(username=request.user.username) if follow: # Follow following_user.followers.add(follower_user) following_user.followers_num += 1 follower_user.followings.add(following_user) follower_user.followings_num += 1 else: # Unfollow following_user.followers.remove(follower_user) following_user.followers_num -= 1 follower_user.followings.remove(following_user) follower_user.followings_num -= 1 following_user.save() follower_user.save() return HttpResponse(status=204) I want it to add follower_user to the followers of following_user and add following_user to the followings of follower_user. However, instead of doing so, it adds follower_user not only to the followers of following_user, but it also adds it to the followings of following_user. Why does it happen? -
psycopg2.OperationalError after makemigrations
I am trying to python manage.py makemigrations for a django app in postgres, but I am getting the follow error: psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "backend_db" does not exist Before this, I am doing docker compose up with the following docker-compose and .env file: version: '3.2' services: postgres: image: postgres:13.4 environment: POSTGRES_DB: backend_db POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - database-data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - postgres volumes: database-data: driver: local networks: postgres: driver: bridge DB_NAME='backend_db' DB_USER='postgres' DB_PASSWORD='postgres' # DB_HOST is localhost or the IP of the machine running postgres DB_HOST='localhost' DB_PORT='5432' The part of the settings.py that I define the postgres is the following: DATABASES = { 'default': get_config( 'DATABASE_URL', 'sqlite:///' + BASE_DIR.child('db.sqlite3'), cast=db_url ), 'postgres': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_config('DB_NAME', 'backend_db'), 'USER': get_config('DB_USER', 'postgres'), 'PASSWORD': get_config('DB_PASSWORD', 'postgres'), 'HOST': get_config('DB_HOST', 'postgres-service'), 'PORT': get_config('DB_PORT', '5432') } } Any idea of what causes the error? -
How to use pillow library to make image from letters in django?
When I try to draw images from the pillow library in django website hosted from pythonanywhere server it shows me an error with : OSError at /confession cannot open resource Request Method: POST Request URL: https://luckyklyist.pythonanywhere.com/confession Django Version: 4.0.3 Exception Type: OSError Exception Value: cannot open resource Exception Location: /home/Luckyklyist/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/PIL/ImageFont.py, line 193, in __init__ Python Executable: /usr/local/bin/uwsgi Python Version: 3.9.5 Python Path: ['/home/Luckyklyist/Confess/Confessout', '/var/www', '.', '', '/var/www', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/Luckyklyist/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages'] Server time: Wed, 06 Apr 2022 14:58:13 +0000 My code to work : def confession(request): if request.method=="POST": message=request.POST.get('confession-msg') ide=random() # Drawing image img = Image.new('RGB', (1080, 1080), color=(0, 0, 0)) d1 = ImageDraw.Draw(img) myFont = ImageFont.truetype("arial.ttf", size=40) words = message lines = textwrap.wrap(words, width=60) a = 0 for word in lines: d1.text((0, a), word, fill=(255, 255, 255), font=myFont) a += 40 img.save(f'{ide}.jpeg') imgge='{ide}.jpeg' confess=Confession(message=message,image=imgge) confess.save() disctionary={"message":message,"activehome":"active"} return render(request,"confession.html",disctionary) But when i remove this part from the code it dosent show me error(OSError at /confession): # Drawing image img = Image.new('RGB', (1080, 1080), color=(0, 0, 0)) d1 = ImageDraw.Draw(img) myFont = ImageFont.truetype("arial.ttf", size=40) words = message lines = textwrap.wrap(words, width=60) a = 0 for word in lines: d1.text((0, a), word, fill=(255, 255, 255), font=myFont) a += 40 img.save(f'{ide}.jpeg') Models.py files … -
Convert String to datetime.timedelta
I have an input string as hundreds or thousand of hours, such as: 1000:50 (One thousand hours and 50 minutes) I need to convert it into a timedelta object, in order to insert it as a DurationField in a Django Model. So far, what I tried is to use datetime.strptime but, the error is giving me is: time data '1000:50' does not match format '%H:%M' I tried to google any kind of solution but so far I didn't find a solution that could help me. Even though the DurationField will convert the timedelta in number of days, I just need to have the input to be as thousand or hundreds of hours, after that, the calculation will be handled in the backend. -
Give a single user permission to view another user's account Django
I would like to give user A revokable permission to enter and view user B's account without the need for using the Admin console, but I am not sure how to do this. I already have custom Users setup, which is working well, as follows: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=False, null=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def save(self, *args, **kwargs): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() return super(User, self).save(*args, **kwargs) def __str__(self): return self.email -
You don't have permission for this user error when trying to update profile
Getting the error message "authorize": "You don't have permission for this user." when trying to update a user profile. I can update information from my default user class (ie.username, first_name, last_name etc), but only if I remove all reference to city, country and bio (anything related to information stored in my extended model and keep my update method nested under class Meta:. Here is my serializer: #updating user profile class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city') country = serializers.CharField(source='profile.country') class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False} } def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): #re-writing updated profile info from request user = self.context['request'].user profile = instance.profile if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] instance.save() … -
Django 3.2.9 Url Path İmportError
I have created a django project called "blogprojesi". I want to import the urls.py file inside the application I created with the name "inf" to the urls.py file inside this project, but I am getting the following error ImportError: cannot import name 'inf' from 'blogprojesi' (.....\blogprojesi\blogprojesi_init_.py) I guess somehow it doesn't see the inf app. I tried the Re_path thing but it didn't work. How can I solve this? **urls.py file inside the "blogprojesi"** from django.contrib import admin from django.urls import path,include from blogprojesi import inf from blogprojesi.inf import urls urlpatterns = [ path('admin/', admin.site.urls), path('',inf,include('inf.urls')), ] **Contents of urls.py file inside inf application** from django.urls import path from . import views urlpatterns = [ path("",views.index), path("index",views.index), path("blogs",views.blogs), path("blogs/<int:id>",views.blog_details), ] **Contents of views.py file inside inf application** from http.client import HTTPResponse from django.http.response import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("Home Page") def blogs(request): return HttpResponse("blogs") def blog_details(request,id): return HttpResponse("blog detail: "+id) -
Disable pagination inspector on drf_yasg
Hi guys im using drf_yasg to create my swagger documentation but I have an issue with a PaginationInspector. In one of my views I declare a paginator and, in swagger, is shown as the default pagination for swagger. Something like this count* integer #This info is generated automatically by swagger next string($uri) #This info is generated automatically by swagger x-nullable: true #This info is generated automatically by swagger previous: string($uri) #This info is generated automatically by swagger x-nullable: trueç results: (THE BODY I ACTUALLY WANT TO SHOW) I would like that the swagger ignore that pagination but haven’t found any info related to it. i try using the decorator, initially I though it could be something like @swagger_auto_schema(paginator_inspectors=False) but it doesn't work and I can't find anything usefull on the docs. Thanks in advance oh and just in case this is my view: class CharacterView(ListChView): class OutputSerializer(serializers.Serializer): id = serializers.CharField(source="external_id") created_at = serializers.DateTimeField() pagination_class = CustomPagination -
How to complete the 19.3 from the book Python-Crash-Course.-Eric-Mattes
Trying to complete the 19.3 from the book Python-Crash-Course.-Eric-Mattes. The task is: 19-3. Refactoring: There are two places in views.py where we make sure the user associated with a topic matches the currently logged-in user. Put the code for this check in a function called check_topic_owner(), and call this function where appropriate. views.py ''' from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') @login_required def topics(request): """Show all topics.""" topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): """Show a single topic, and all its entries.""" topic = Topic.objects.get(id=topic_id) # Make sure the topic belongs to the current user. if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): """Add a new topic.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} … -
how to set loader in django app using python and javascript
I'm building a big project using django, and I want the best way to put the loader during operations for Example: code now this function need almost 2 min to finsh the function when this function run the page only loading how i can set a loader while the function run ? for frontend i use (html , css, js) backend ( django - python ) i want simple method In short, I want to set loader while the run functions in django :) -
Two ways to create timezone aware datetime objects (Django). Seven minutes difference?
Up to now I thought both ways to create a timezone aware datetime are equal. But they are not: import datetime from django.utils.timezone import make_aware, get_current_timezone make_aware(datetime.datetime(1999, 1, 1, 0, 0, 0), get_current_timezone()) datetime.datetime(1999, 1, 1, 0, 0, 0, tzinfo=get_current_timezone()) datetime.datetime(1999, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>) datetime.datetime(1999, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>) In the Django Admin GUI second way creates this (German date format dd.mm.YYYY): 01.01.1999 00:07:00 Why are there 7 minutes difference if I use this: datetime.datetime(1999, 1, 1, 0, 0, 0, tzinfo=get_current_timezone()) -
Manifest.json not found Django React
I'm unable to get rid of manifest.json error. I don't want to remove it's link from HTML file. Also I tried every single answer out there on stackoverflow and other sites but nothing worked. Error Image Directory Structure Following are my settings for static files and html files - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'frontend/build'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'frontend' / 'build' / 'static'] Can you please tell me what's wrong here ?