Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to store Business Availability (Weekday and Time) with possible varing timezones
I am currently developing a work availability calendar for users. And I'm looking for a way to store weekly availability so it can be transformed depending on the timezone. For example: If I store Monday with availability from 4 p.m. to 10 p.m. (GMT -5), it should transform the availability from 9 p.m. Monday to 3 a.m when being saved on UTC. Tuesday. However, as it is currently set, it is available. To summarize, is there any way to store this availability in UTC and then transform it to the desired timezone, taking into account the changes in days from one day to another? Initially, I was thinking of storing the availability with two TimeFields for the start_time and end_time and a CharField storing the day of the week. However, when converting the times to UTC, they may change from one day to another. And like that I will not be aware if the days change. Note: Sorry about my grammar. -
How Can I perform Django Multiple Filter on a Model
I am current working on a Django project where I want user to perform property search using different criterial like Property type, State, Minimum bedrooms, Bathroom type, minimum and max price. I want the search to be flexible such that the user chooses which field to search for and not forcing him to input every form field during search. I have tried my best but no error and no positive result, rather even when the user search matches the Model record, it still does not display it. Here is my Model Code: class Property(models.Model): PROPERTY_TYPE_CHOICES = [ ('Complete House', 'Complete House'), ('Apartment', 'Apartment'), ('Self-Contained', 'Self-Contained'), ] BEDROOM_CHOICES = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5+'), ] BATHROOM_CHOICES = [ ('Self-contained', 'Self-contained'), ('General', 'General'), ('Private Detached', 'Private Detached'), ] COUNTRY_CHOICES = [ ('Nigeria', 'Nigeria'), ] STATE_CHOICES = [ ('Abia', 'Abia'), ('Adamawa', 'Adamawa'), ('Akwa Ibom', 'Akwa Ibom'), ('Anambra ', 'Anambra '), ('Bauchi', 'Bauchi'), ('Bayelsa', 'Bayelsa'), ('Benue ', 'Benue '), ('Borno', 'Borno'), ('Cross River', 'Cross River'), ('Delta', 'Delta'), ('Ebonyi', 'Ebonyi'), ('Edo', 'Edo'), ('Ekiti', 'Ekiti'), ('Enugu', 'Enugu'), ('Gombe', 'Gombe'), ('Imo', 'Imo'), ('Jigawa', 'Jigawa'), ('Kaduna', 'Kaduna'), ('Kano', 'Kano'), ('Katsina', 'Katsina'), ('Kebbi', 'Kebbi'), ('Kogi', 'Kogi'), ('Kwara', 'Kwara'), ('Lagos', 'Lagos'), ] agent = … -
My django models keep accepting values that they shouldn't
Ok so here's my model: from django.db import models class PetSex(models.TextChoices): MALE = 'Male', 'Male' FEMALE = 'Female', 'Female' NOT_INFORMED = 'Not Informed', 'Not Informed' class Pet(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() weight = models.FloatField() sex = models.CharField(max_length=20, choices=PetSex.choices, default=PetSex.NOT_INFORMED) def __str__(self): return self.name Every time I try to add an invalid sex it should return an error but it keeep accepting it. >>> from pets.models import Pet >>> petinfos_2 = {"name": "xamaria", "age": 1, "weight": 30, "sex": "Malasdasdde"} >>> test123 = Pet(**petinfos_2) >>> test123.save() >>> test123.name 'xamaria' >>> test123.sex 'Malasdasdde' >>> -
Jenkins - Create an agent with a python script
as the title suggests, I am willing to automate the creation of a jenkins agent using python! I don't have any idea about jenkins or what is it even used for, I just got a task to do in my internship and I can't skip it, so I just installed Jenkins and didn't anything yet! I'm sorry for not giving a code sample because I'm literally stuck in that task! All I have is this django view function: @login_required def create(request): if request.method == 'POST': name = request.POST.get('form-submit') description = request.POST.get('employe-description') employee = Employee(user=request.user, name=name, description=description) employee.save() return redirect('create') return render(request, 'create.html') And all I want is when the form is submitted, a jenkins agent will be created using the same name as the employee's from the request. Thanks in advance. -
How do I separate URLs for different groups in Django?
I am developing a login screen using Django-allauth. I would like to change the design of the login screen for Group A and Group B. To do this, we would like to change the URL settings of the login screen for each. Also, pages other than the login, I want Group A to transition to https://xxxx/groupa/account/login/ https://xxxx/groupa/toppage/ https://xxxx/groupa/editpage/ I want group B to transition to https://xxxx/groupb/account/login/ https://xxxx/groupb/toppage/ https://xxxx/groupb/editpage/ Perhaps it would be better to separate the application for Group A and Group B, but I want to keep the source code common except for the login screen. Below is the code I tried. settings.py LOGIN_URL = 'account/login/' LOGIN_REDIRECT_URL = '/' ACCOUNT_LOGOUT_REDIRECT_URL = '/' urls.py path('<str:group>/account/', include('allauth.urls'), name="account_info"), path('<str:group>/', include('member.urls')), I get an error when accessing https://xxxx/groupa/account/login/ NoReverseMatch at /groupa/account/login/ Reverse for 'account_signup' with no arguments not found. 1 pattern(s) tried: ['(?P<group>[^/]+)/account/signup/\\Z'] Is there some middleware or something that forces the URL to change? I am a beginner and very confused. Please give me some advice. -
How can I upgrade Django along with compatible dependencies listed in the requirements.txt file?
I am trying to install the latest version of django-debug-toolbar but it requires a version of Django >=3.2, and the project I am working on was written in Django 2.2.10. Is this going to pose a problem for me if I go ahead and install it? How can I fix this? -
Django with postgresql is getting slower and slower to create and save objects
With Django 4.2.2 and Posgresql 15.3, I have to migrate data from another database. Basically, I am doing something like that for each of the 1,500,000 rows I have to migrate: asset = Asset() asset.creation_date = a date from old database asset.modification_date = a date from old database asset.flag = a boolean from old database asset.serial = a string from old database asset.quantity = an integer from old database asset.save() Note that I do not want to use bulk_create() because I plan to get the generated primary key at once for other processing. The database I read (it is on a separate server) can give me 500 rows per second, this is stable over the time. At Django side, with a NVMe disk, the first 10,000 rows are copied at the speed of 500 inserts/seconds, after 100,000 copies the speed is 100 inserts/s and I stopped migration when it gradually went to 20 inserts/s. I tried : Wait a little and restart my batch at the point it was stopped (I still got 20 inserts/s) Restart postgresql Run without transactions Run without indexes Fully recreate the database But I have still the problem. I checked postgresql log file, but I … -
trying to update the cart icon status using javascript and django
So i am doing this small webpage project in Django and when its time to update the cart icon in the navbar, it doesn't do anything. I had tried some alternatives but no change. Here is some part of my code. If any body can tell me what I'm missing that would be awesome. I'm pretty much a noob to this. añadir_al_carrito.html {% extends 'paginaV3_app/base.html' %} {% load static %} {% block title %}Carrito{% endblock title %} {% block main-content %} <div class="container my-5"> <div class="row"> <h1 class="text-center mb-5">Carrito de compras de {{ request.user }}</h1> <div class="col-sm-8"> <div class="card"> <div class="card-body"> {% for item in items_carrito %} <div class="row"> <div class="col-sm-3 text-center align-self-center"><img src="{{ item.producto.prod_imagen.url }}" alt="" class="img-fluid img-thumbnail shadow-sm" height="150" width="150"></div> <div class="col-sm-9"> <div> <h3>{{ item.producto.titulo }}</h3> <p class="mb-2 text-muted small">{{ item.producto.descripcion }}</p> <div class="my-3"> <label for="cantidad">Cantidad</label> <a class="minus-cart btn" href="{% url 'disminuir_cantidad' item.id %}"><i class="fas fa-minus-square fa-lg"></i></a> <span id="cantidad">{{ item.cantidad }}</span> <a class="plus-cart btn" href="{% url 'aumentar_cantidad' item.id %}"><i class="fas fa-plus-square fa-lg"></i></a> </div> <div class="d-flex justify-content-between"> <a href="{% url 'remover_del_carrito' item.id %}" class="remove-cart btn btn-sm btn-secondary ,r-3">Quitar Item</a> <p class="mb-0"><span><strong>${{ item.producto.precio }}</strong></span></p> </div> </div> </div> </div> <hr class="text-muted"> {% empty %} <h1 class="text-center mb-5">Carrito Vacío</h1> {% endfor %} … -
Django Rest Framework: All POST APIs only respond with "Forbidden" after logging in a user
After enabling authentication in my Django backend and logging in a user all POST Requests stop to work and only respond with "403 Forbidden". I setup a Django App as my backend and I use ReactJS as my Frontend. All the basics work fine so far. But now I want to add authentication to my project. For this I have installed django-cors-headers. I have also included corsheaders in my INSTALLED_APPS. CORS_ALLOWED_ORIGINS allows http://localhost:3000 (the port my Frontend is running under). CORS_ALLOW_CREDENTIALS is also set to TRUE. The corresponding middleware corsheaders.middleware.CorsMiddleware has also been added to the MIDDLEWARE section. I created three APIs. One each for registering a new user, for logging in an existing user and for logging out a user. All three of them work perfectly fine as long as no user is logged in. The cookies csrftoken and sessionid are set just as they should. Now for my problem: As soon as a user is logged in all POST APIs - including the three mentioned above - stop to work. I get a simple "403 Forbidden" response. GET APIs seem to work just fine. My research suggest that this is a common error that has something todo with … -
Django DB Constraint with grandfathered data / Ignore UniqueConstraint for a test?
Recently added a UniqueConstraint to a model (Project) to enforce uniqueness with no problems. class Meta: constraints = [ models.UniqueConstraint( name="%(app_label)s_%(class)s_unique_name_in_organization", fields=['organization', 'name'] ) ] As I understand database constraints, they do not work retroactively. This creates a blindspot as I am uncertain how the grandfathered entities will behave on future database interactions (e.g. will an IntegrityError be raised when saving even if the only change is for an unrelated field?). To remedy this, I've tried creating a test that populates the test database with a few entities that have the known conflict (e.g. a shared name and organization), but as expected Django raises IntegrityError. How can I circumvent this and create purposely bad data that conflicts with my database constraint? I've tried: with connection.constraint_checks_disabled() Project.objects.create( ... with mock.patch.object(Project._meta, 'constraints', return_value=[]): Project.objects.create( ... with mock.patch.object(Project._meta, 'constraints', new_callable=mock.PropertyMock) as cmock: cmock.return_value = [] Project.objects.create( ... However, an IntegrityError is still raised for each attempt. I've tried deleting the constraint with some sql, but that raises django.db.utils.OperationalError: cannot ALTER TABLE "app_project" because it has pending trigger events with connection.cursor() as cursor: table = Project._meta.db_table sql_ = sql.SQL("ALTER TABLE {table} DISABLE TRIGGER ALL").format(table=sql.Identifier(table)) cursor.execute(sql_) cursor.commit() sql_ = sql.SQL( "ALTER TABLE {table} DROP CONSTRAINT … -
Django framework test features not working
I have been stuck on this feature getting this error that I can't seem to solve, I'm still new to coding. It's giving me errors about things that I feel like I have already done. I have a lot of files but Ill share the ones I just changed most recently and that I think must be the issue. This is my accounts/views.py: from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.urls import reverse from .forms import LoginForm def login_view(request): if request.method == "GET": form = LoginForm() return render(request, "accounts/login.html", {"form": form}) elif request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect(reverse("projects:list_projects")) return redirect(reverse("accounts:login")) This is my accounts/urls.py: from django.urls import path from . import views app_name = "accounts" urlpatterns = [ path("login/", views.login_view, name="login"), ] This is my accounts/templates/accounts/login.html: <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <main> <div> <h1>Login</h1> </div> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Login</button> </form> </main> </body> </html> I've read the rules of what I need to accomplish and it feels like I've met that criteria but it gives me an … -
Looping in window.location
I am getting lat and lng from sessionStorage and I want to send it to browser with window.location but i get to a infinity loop. var lat = sessionStorage.getItem('lat'); var lng = sessionStorage.getItem('lng'); window.location = '?lat='+lat+'&lng='+lng; I saw other questions about this but they did not work. I tryed to use window.location.hash / href etc... but the result is not what I expect Does someone knows how to build that function to work properly? Thank you very much -
Data from Django form doesn't get saved to MySQL table
I am trying to save data, collected via a Django form, to the DB. The page is designed to first ask user for an input, based on which a list is generated. I am trying to save values corresponding to these generated items. But this data, while I see it in the POST request, just doesn't get saved. I am assuming the error is in my Save logic, but I just cannot find it out. I have the views defined to save this, and also the relevant URLs. The Django logs show no error, and there are none when I look into the DB error log. Here's how my code looks like: Model class MonthlySheet(models.Model): month = models.IntegerField() year = models.IntegerField() org_name = models.ForeignKey(Establishment, on_delete=models.DO_NOTHING) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, default=None) wages = models.IntegerField() gross = models.IntegerField() total_work_days = models.IntegerField() present_days = models.IntegerField() calc_twelve = models.DecimalField(max_digits=10, decimal_places=2) calc_eight_three_three = models.DecimalField(max_digits=10, decimal_places=2) calc_diff = models.DecimalField(max_digits=10, decimal_places=2) calc_point_seven_five = models.DecimalField(max_digits=10, decimal_places=2) def get_absolute_url(self): return reverse('monthly_sheet_detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): self.pk = f"{self.month}.{self.year}" super().save(*args, **kwargs) View: class AddMonthlySheetView(FormView): template_name = 'add_monthlysheet.html' form_class = CustomMonthlySheetForm model = MonthlySheet def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) last_month, year, total_work_days = set_previous_month() context['last_month'] = last_month … -
HTTP 404 error for css and javascript files in Django and Gunicorn
The actual error is Refused to apply style from 'http://127.0.0.1:8000/static/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET http://127.0.0.1:8000/static/js/home.js net::ERR_ABORTED 404 (Not Found) This error started happening when I started using Gunicorn as app server. The first error for css is a misdirection. The file was not found to begin with. Chrome developer tools shows Request URL:http://127.0.0.1:8000/static/css/home.css Request Method:GET Status Code:404 Not Found Referrer Policy:same-origin Connection:close Content-Length:8559 Content-Type:text/html Date:Wed, 07 Jun 2023 19:32:29 GMT Referrer-Policy:same-origin Server:gunicorn status code. I see the same status code for all the css and javascript files. Here are my relevant settings settings.py INSTALLED_APPS = [ . . 'django.contrib.staticfiles', 'bootstrap4', . . ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "kubera/static"), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") import mimetypes mimetypes.add_type("text/css", ".css", True) manage.py collectstatic command copied the files correctly ~/workspace/djangoapp/src$ python3 manage.py collectstatic 161 static files copied to '/home/<myhomedir>/workspace/djangoapp/src/static'. index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% bootstrap_messages %} <link href="{% static 'css/home.css' %}" type="text/css" rel="stylesheet"> <title>{% block title %}Parier Config Central {% endblock %}</title> </head> … -
How to find out where Django is querying from?
I am relatively new to Django and web development in general. I am working on a project with my company (small company, three developers here currently who all have little to no experience) which has very little documentation, and the person who used to work on it is gone. I am getting errors when building the project, and part of the problem I think is that I may have incorrect data for building the project. My specific question is, when you call something like Model.objects.get(), how can you tell where the program is "getting" this information from? My project has a ton of moving parts - an sqlite db, a csv spreadsheet, a whole directory of audio recording sessions, and is making use of all of them. I am not sure whether this get() is looking at any of these, or possibly an API that no one currently in my company even knows exists. Is there a standard file in most Django projects where I could see what Model.objects.get() looks at when fetching the data? -
How to cache beautified / prettified outputted HTML rendered by Django?
I've implemented a Middleware after researching how to beautify / prettify (format nicely), the outputted HTML rendered in the browser for my Django project. I came across this method here. settings.py # local Memcached CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ... 'django.middleware.gzip.GZipMiddleware', 'myproject.middleware.HTMLBeautifyMiddleware', # needs to come after gzip ] myproject/middleware.py from bs4 import BeautifulSoup class HTMLBeautifyMiddleware(object): TAGS = ["p", "script", "span", "i", "h1", "h2", "h3", "h4", "h5", "h6"] def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if response.status_code == 200: if response["content-type"].startswith("text/html"): html = BeautifulSoup(response.content, "lxml", preserve_whitespace_tags=self.TAGS) response.content = html.prettify() return response In the discussion on the blog, a comment mentions: I’d advise to cache the output before using this plugin on a production site. My questions are: How would one go about caching the outputted HTML? Does Django or the browser handle caching the outputted HTML for me, or do I need to do something explicitly to make it happen? If I used AWS Cloudfront, would that be a solution? -
Unable to send email using celery in DRF
I'm unable to send email via smtp using celery task and DRF. I have the following constants in settings.py # Celery settings CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # Email settings EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = MY_EMAIL EMAIL_HOST_PASSWORD = MY_PASSWORD EMAIL_USE_TLS = True EMAIL_USE_SSL = False tasks.py from django.core.mail import send_mail from celery import shared_task @shared_task def send_verification_email(user_email): send_mail( subject="test email", message="testing", from_email=settings.EMAIL_HOST_USER, recipient_list=[user_email], fail_silently=False ) views.py class RegisterUserAPIView(generics.GenericAPIView): ... user_email = ... send_verification_email.delay(user_email = user_email) ... The error I'm getting is raised unexpected: SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)') Also, if i'm using console instead of smtp in below EMAIL_BACKEND, i'm able to send emails to the console without any problem.. EMAIL_BACKEND ='django.core.mail.backends.console.EmailBackend' I have EMAIL_USE_SSL = False but still asking for SSL certificate ? Not understanding how to fix this issue. -
pyQt5 ui connected a Django services
I want to create a program for organizations. that has a simple interface and is linked to the Django project for the large parent organization, Where you receive the order from one of the branches by to the interface ui ,, Django sends the results,, can I use puQt5 for ui interface and Django for server? Can I make a ui interface with pyQt5 for multy entreprises Connected to the django project with a mother entreprise? -
How can I create a user login/registration model using Django Rest Framework without getting a response code 403 when trying to create user?
So I am working on a project using Django and Django rest framework. I'm trying to create an api for my website which allows users to register/log in/log out. I'm following [this tutorial] (https://iheanyi.com/journal/user-registration-authentication-with-django-django-rest-framework-react-and-redux) for the initial set up. My issue is that when I try to run my test code to create a user, I get a response code 403 which I guess means I'm trying to do something I don't have permission to do? How can I get rid of this issue so I can create users? Here is my tests.py: from django.test import TestCase from django.urls import reverse from rest_framework.test import APITestCase from django.contrib.auth.models import User from rest_framework import status class TestUserApi(APITestCase): def setUp(self): self.test_user = User.objects.create_user('testuser', 'test@example.com', 'testpassword') self.create_url = reverse('user-create') def test_create_user(self): data = { 'username': 'foobar', 'email': 'foobar@example.com', 'password': 'somepassword' } response = self.client.post(self.create_url , data, format='json') # We want to make sure we have two users in the database.. self.assertEqual(User.objects.count(), 2) # And that we're returning a 201 created code. self.assertEqual(response.status_code, status.HTTP_201_CREATED) # Additionally, we want to return the username and email upon successful creation. self.assertEqual(response.data['username'], data['username']) self.assertEqual(response.data['email'], data['email']) self.assertFalse('password' in response.data) def test_create_user_with_short_password(self): data = { 'username': 'foobar', 'email': 'foobarbaz@example.com', 'password': 'foo' … -
How to access Product name and all details from sub Category using Django?
I want to get product name and all its details from sub category, I tried a lot to find how to do it but it didn't work When clicking on the sub category the related products should appear ,If anyone knows the query please tell me I have made four models First Main category Second category Third SubCategory Category contains the foregion key of the main category Also In sub category the foregion key of category is given And in the product model, the foreign key of the above three models is given I try this query Product.objects.all().select_related('main_category').select_related('category').select_related('sub_category') Please tell me and its html part too -
How to order the results by two columns using admin.display decorator
Please consider the following example: # models.py class Case(models.Model): number = models.SmallIntegerField(null=False, blank=False) year = models.SmallIntegerField(null=False, blank=False) ... #admin.py @admin.register(Case) class CaseAdmin(admin.ModelAdmin): list_display = ['case_number', ...] ordering = ['-year', '-number'] @admin.display(ordering=['-year', '-number']) def case_number(self, case): return f'{case.number} / {case.year}' Now how can I specify the order to be by '-year' and '-number' using the admin.display() decorator? If it can not be done with the admin.display() decorator, is there another way to achieve that? Thanks -
`django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured` when I try to start the daphne
I have a django project. When I start runserver - everything is fine. But if I try to start the daphne asynchronous server (daphne -p 8001 config.asgi:application), I get an error django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Settings in wsgi and asgi are the same os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') Maybe someone came across and can me help? Here ais full traceback File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/dima/PycharmProjects/TyuMeb/Back_reload/config/asgi.py", line 16, in <module> from chat import routing File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/routing.py", line 3, in <module> from . import consumers File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/consumers.py", line 9, in <module> from chat.models import Conversation, Message File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/models.py", line 3, in … -
Static url is not working whenever I am trying to use slug to show a blog details
My other pages static url is working great but when ever I am trying to show a blog details, my static url is changing its showing http://127.0.0.1:8000/blog/this-is-testing-number-1/media/assets/css/bootstrap.min.css instead of http://127.0.0.1:8000/media/assets/css/bootstrap.min.css my blog app views.py from django.shortcuts import render from .models import Blog # Create your views here. def details(request, slug): blog = Blog.objects.get(slug=slug) context = { 'blog':blog } return render(request, 'blog/blog_details.html', context) my blog app urls.py from django.urls import path, include from froala_editor import views from .views import * urlpatterns = [ path('froala_editor/',include('froala_editor.urls')), path('<slug>/', details, name='details') ] my blog details.html <!-- CSS ================================================== --> <link rel="stylesheet" href="media/assets/css/bootstrap.min.css" /> <link rel="stylesheet" href="media/assets/css/magnific-popup.css" /> <link rel="stylesheet" href="media/assets/css/owl.carousel.min.css" /> <link rel="stylesheet" href="media/assets/css/simple-scrollbar.css" /> <link rel="stylesheet" href="media/assets/css/fontawesome.all.min.css" /> <link rel="stylesheet" href="media/assets/css/style.css" /> <script src="media/assets/js/modernizr.min.js"></script> </head> my static settings STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIR = { os.path.join(BASE_DIR , "public/static") } MEDIA_ROOT = os.path.join(BASE_DIR, 'public/static') MEDIA_URL = '/media/ my main urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('blog/', include('blog.urls')), path('account/', include('account.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() how to fix this. I … -
issue sending uploaded image file from reactJS frontend to django python backend (file sending as undefined)
I am trying to send various data types from user input on the reactJS frontend to the Django python backend and getting an error where the text string sends but the image file does not. here is where I am sending the image and caption handleSubmit = async () => { try { const formData = new FormData(); console.log('Image: ', this.props.fileInput); console.log('Image type: ', typeof this.props.fileInput); console.log('Image is a File: ', this.props.fileInput instanceof File); formData.append('file', this.props.fileInput); // formData.append('file', this.props.file); formData.append('caption', this.state.caption); for (let pair of formData.entries()) { console.log(pair[0] + ', ' + pair[1]); } const response = await axios.post(API_URL, formData, { headers: { 'Content-Type': 'multipart/form-data' } }); if (response.status === 200) { console.log('Image uploaded successfully'); } } catch (error) { console.error(error); } } on the caption component and for the image component I did updateImage = async (imageId, caption) => { try { const formData = new FormData(); console.log('File:', this.state.file); console.log('Caption:', caption); formData.append('file', this.state.file); formData.append('caption', caption); for (let pair of formData.entries()) { console.log(pair[0] + ', ' + pair[1]); } const response = await axios.post(API_URL, formData, { headers: { 'Content-Type': 'multipart/form-data' } }); if (response.status === 200) { console.log('Image processed successfully'); const currentState = this.state; const newState = {...currentState}; newState.elements[imageId].URL = … -
Django formatting DecimalField to money
In my Django project I'm saving a money amount in a decimalField. The problem is the format of the number when I print it. I need it in the german money format 10.000,00 € so first a point as seperator and a comma for the cents. In Django I've only managed it to seperate everything with commas like 10,000,00 Has anyone an idea how I can implement it as I want?