Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
makemigrations is not identifying changes. Is there any solution to resolve this without touching my database migration logs?
I encounter this problem in every Django project whenever I do some complex work. I tried deleting all the migrations folders from each app and then changed the database. It worked, but I'm looking for a solution that doesn't involve touching migration files or the database. whenever i tried python manage.py makemigrations it always displays no changes dected. -
Django ignores static configuration for uploading to S3
I had the same problem with media files before, I did all the configuration but django kept saving the media files locally and not in S3, I think it was solved by implementing a custom class inheriting from S3Boto3Storage. Now I want to save my static files in the same S3 but I have the same problem, django completely ignores my configuration and keeps saving the files locally in the staticfiles directory. These are my installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'app', 'crispy_forms', 'crispy_bootstrap5', ] Media file setup currently working: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_ENDPOINT_URL = config('AWS_S3_ENDPOINT_URL') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_MEDIA_LOCATION = 'media' AWS_S3_REGION_NAME = config('AWS_S3_REGION_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False AWS_S3_CONNECTION_TIMEOUT = 60 MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com/{AWS_MEDIA_LOCATION}/" PUBLIC_MEDIA_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'cms.storage_backends.PublicMediaStorage' DEFAULT_PROFILE_PHOTO=config('DEFAULT_PROFILE_PHOTO') Static file configuration, the idea is to read CMS_STATIC_LOCAL_STORAGE from the environment variables, but for testing purposes the value is set constantly: CMS_STATIC_LOCAL_STORAGE = False print('Static Local Storage: ', CMS_STATIC_LOCAL_STORAGE) AWS_STATIC_LOCATION = 'static' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if CMS_STATIC_LOCAL_STORAGE: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] else: STATIC_URL = f"https://{AWS_S3_REGION_NAME}.digitaloceanspaces.com/{AWS_STORAGE_BUCKET_NAME}/{AWS_STATIC_LOCATION}/" STATICFILES_STORAGE = 'cms.storage_backends.StaticStorage' Please note that I have also … -
Next JS doesn't send cookies to Django backend
I'm using NextJS on the front end and Django for the backend. I have authentication and authorization working by storing the tokens in local storage. I'm attempting to implement a more secure approach by using httonly cookies for authorization. The issue I'm stuck on is sending the httponly cookie back to Django on subsequent requests. Here is what I'm trying to do with some additional combinations I've attempted commented out. async function getData(url, errorMessage) { const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', // 'Access-Control-Allow-Credentials': true, // credentials: 'same-origin', credentials: 'include', // "Authorization": "Bearer " + localStorage.getItem(ACCESS_TOKEN_KEY) } }) if (!response.ok) { throw new Error(errorMessage); } return await response.json() } Here is what I have in my settings.py file in Django CORS_ALLOW_CREDENTIALS = True from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ( "credentials", 'access-control-allow-credentials', ) REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ] } REST_AUTH = { "USE_JWT": True, "JWT_AUTH_HTTPONLY": True, 'JWT_AUTH_COOKIE': 'my-app-auth', } MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware', ] from datetime import timedelta SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(days=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=30), "ROTATE_REFRESH_TOKENS": False, "UPDATE_LAST_LOGIN": True, "SIGNING_KEY": "complexsigningkey", # generate a key and replace me "ALGORITHM": "HS512", } When … -
Django Templates doesn't update
I have an application with Django 2.2. and IIS 8. It suddenly doesn't work when I made new changes. It changes appear in the Database but doesn't show on the webpage (templates or admin forms). I had tried start/stop the IIS server, I had modified the DEBUG option but still not working. The server Thanks. -
Preserve image metadata with Wagtail rendered images
I would like to find a way to preserve some or all of the image metadata when Wagtail generates renditions from the original. I have found the following reference in the Wagtail documentation about the function <generate_rendition_file>: NOTE: The responsibility of generating the new image from the original falls to the supplied filter object. If you want to do anything custom with rendition images (for example, to preserve metadata from the original image), you might want to consider swapping out filter for an instance of a custom Filter subclass of your design. It mentions the use of a filter, but as I am new to Django and Wagtail, I have not been able to determine how or where this would be used. This is an example of my code creating the renditions: {% image picture max-800x600 format-webp preserve-svg as picture_image %} {% image picture max-1600x1600 format-webp preserve-svg as original_image %} I would appreciate any help or guidance to figure this out. -
Django - call Form item by item with AJAX call
I'm new to Django and I'm trying to upload Form's items in my template with AJAX call to avoid refresh. Thanks to many Questions/answers here I have the following code which is working fine and renders the form as a table. I would like to do the same thing BUT instead of rendering it as a table, I would like to be able to choose which item to display and use it like this {{ form.item_name }} so I can organise my template like I want. What should I change ? view.py def test_company(request): if request.user.is_authenticated: company_num = request.GET.get('company_num') current_record8 = models_companies.objects.get(id_company=company_num) ser_template = forms_companies(instance=current_record8) return HttpResponse(ser_template.as_table()) else: messages.success(request, "You Must Be Logged In...") return redirect('home') template.html function load_company_test() { $.ajaxSetup({ data: { company_num: $('#id_id_company').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ type: "GET", url: "../test_company/", success: function (data) { $("#div_company").empty(); $("#div_company").html(data); }, }); } // I want to populate the div like this <div id="div_company">{{ data.item_name }}</div> -
Dockerised Django project not serving files after trying to adjust static configuration
I'm running a dockerised web application using Django. I have had issues with getting static files to work (I couldn't get the application to find them), I thought I had this figured out that the files had the wrong permissions and added my current usergroup to it. After this the application won't run. What do I mean by won't run? I now get OOM messages from Gunicorn which I never got before. It's not a very intense application so far. My feeling is that changing permissions has caused some issues. This is the current permission setup: -rw-rw-r-- 1 ash ash 757 Aug 30 20:17 docker-compose.yml -rw-rw-r-- 1 ash ash 965 Aug 26 18:02 Dockerfile drwxrwxr-x 7 ash ash 4096 Aug 26 18:32 gs-python drwxr-xr-x 3 ash ash 4096 Aug 16 20:12 nginx -rw-rw-r-- 1 ash ash 6 Aug 15 17:16 README.md -rw-rw-r-- 1 ash ash 31 Aug 15 19:06 requirements.txt drwxrwxrwx 2 ash ash 4096 Aug 30 19:50 static docker-compose.yml version: '3.8' services: web: build: . command: gunicorn app-name.wsgi:application --bind 0.0.0.0:8000 volumes: - ./gs-python:/app - ./gs-python/static:/app/static # Directly mount local static folder expose: - "8000" depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: POSTGRES_USER: POSTGRES_PASSWORD: nginx: image: … -
make USERNAME_FIELD dynamic between phone and email
I have a Django rest framework app and I modified its User model with AbstractBaseUser. I deployed the project on a VPS and now the customer wants to make changes on authentication. I have to set BOTH phone and email as USERNAME_FIELD to let users send phone or their email and I have to make it dynamic. Here's my first approach : from django.db import models from django.core.validators import RegexValidator, MinValueValidator from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin class AllUser(BaseUserManager): def create_user(self, username, phone, email=None, password=None, first_name=None, last_name=None): if not email: raise ValueError('need Email') if not username: raise ValueError('need Email') if not phone: raise ValueError('need Phone Number') if not first_name: raise ValueError('First Name') if not last_name: raise ValueError('Last Name') user = self.model( email=self.normalize_email(email), phone=phone, username=username, first_name=first_name, last_name=last_name, ) user.is_active = True user.set_password(password) user.save(using=self._db) return user def create_staff(self, username, phone, email, password, first_name, last_name): user = self.create_user( email=email, phone=phone, username=username, password=password, first_name=first_name, last_name=last_name, ) user.is_active = True user.is_staff = True user.is_superuser = False user.save(using=self._db) return user def create_superuser(self, username, phone, email, password, first_name, last_name): user = self.create_user( email=email, phone=phone, username=username, password=password, first_name=first_name, last_name=last_name, ) user.is_staff = True user.is_active = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', … -
Issue uploading files to S3 in Django on Azure App Services
Our application has been hosted on Heroku for several years without any issues uploading to S3. We are working on migrating to Azure App Services. We are now encountering an issue where the the file uploads are failing. They appear to be timing out and cause the gunicorn worker to abort and close. The server log and stack trace hasn't been helpful, but I'm hoping someone else may see something here that can be useful. None of the storage configuration or settings have been modified from Heroku to Azure. packages being used: Django==3.2.25 boto3==1.35.9 botocore==1.35.9 s3transfer==0.10.2 django-storages==1.14.4 Settings: DEFAULT_FILE_STORAGE = 'project.utils.storage.HashedFilenameMediaS3Boto3Storage' Storage class - this storage class setup was implemented about 8 years ago so maybe I need to make some changes?: def HashedFilenameMetaStorage(storage_class): class HashedFilenameStorage(storage_class): def __init__(self, *args, **kwargs): # Try to tell storage_class not to uniquify filenames. # This class will be the one that uniquifies. try: new_kwargs = dict(kwargs) #, uniquify_names=False) super(HashedFilenameStorage, self).__init__(*args, **new_kwargs) except TypeError: super(HashedFilenameStorage, self).__init__(*args, **kwargs) def get_available_name(self, name): raise NoAvailableName() def _get_content_name(self, name, content, chunk_size=None): dir_name, file_name = os.path.split(name) file_ext = os.path.splitext(file_name)[1] file_root = self._compute_hash(content=content, chunk_size=chunk_size) # file_ext includes the dot. out = os.path.join(dir_name, file_root + file_ext) return out def _compute_hash(self, content, chunk_size=None): … -
How to Resolve the Issue: Django with Visual Studio Code Changing Template Without Effect?
I have a Django app, and I am using Visual Studio Code as my editor. I have implemented functionality for recovering passwords via an email template. I edited the template to see what effect it would have on the email, but the changes had no effect. I even deleted the email template, but I still received the old email template in my inbox. The email template is within a folder named templates in my account app. Here is my email template (password_reset_email.html): <!-- templates/password_reset_email.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Password Reset Request</title> <style> /* Add any styles you want for your email */ </style> </head> <body> <p>Je hebt om een wachtwoord reset aanvraag gevraagd voor je account.</p><br><p> Klik de link beneden om je wachtwoord te veranderen:</p> <p>Als je niet om een wachtwoord reset hebt gevraag, neem dan contact op met:</p> <br><p> test@test.nl. En klik niet op de link.</p> <p>Met vriendelijke groet,<br>Het app team</p> </body> </html> But in my email box I still got this email: Dag test gebruiker , Je hebt om een wachtwoord reset aanvraag gevraagd voor je account. Klik de link beneden om je wachtwoord te veranderen: Reset je wachtwoord Als je niet om een wachtwoord … -
Django channels stops working after some time
I have a system that has two forms of communication, one through http connections for specific tasks and another through websockets for tasks that require real-time communication. For the deployment I used nginx, daphne and redis, these are the configurations: Service [Unit] Description=FBO Requires=fbo.socket After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/api.fbo.org.py/backend Environment="DJANGO_SETTINGS_MODULE=fbo-backend.settings" ExecStart=/var/www/api.fbo.org.py/backend/.venv/bin/daphne \ --bind 127.0.0.1 -p 8001 \ fbo-backend.asgi:application [Install] WantedBy=multi-user.target Nginx server { server_name api.fbo.org.py; access_log /var/log/nginx/access.log custom_format; location /static/ { alias /var/www/api.fbo.org.py/backend/staticfiles/; expires 86400; log_not_found off; } location /media/ { root /var/www/api.fbo.org.py/backend; expires 86400; log_not_found off; } location / { proxy_pass http://localhost:8001; proxy_set_header Host $host; proxy_set_header X-Real_IP $remote_addr; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://127.0.0.1:8001; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } Library versions channels==4.0.0 channels-redis==4.2.0 daphne==4.1.2 Django==3.2.25 Reviewing the log when the system crashes I found that the following is repeated for different actions performed on the system: WARNING Application instance <Task pending name='Task-3802' coro=<ProtocolTypeRouter.__call__() running at /var/www/api.bancodeojos.org.py/backend/.venv/lib/python3.8/site-packages/channels/routing.py:62> wait_for=<Future pending cb=[shield.<locals>._outer_done_callback() at /usr/lib/python3.8/asyncio/tasks.py:902, <TaskWakeupMethWrapper object at 0x7f93a6c84c70>()]>> for connection <WebRequest at 0x7f93a6754b80 method=PUT uri=/turns/9141/ clientproto=HTTP/1.0> took too long to shut down and was killed. I tried changing the versions of the libraries, … -
Django formtools' "done" method is not getting called on form submission
I am trying to build a multistep html form using Django formtools. I have 2 forms with 2 fields at most. After filling the last form (i.e. step 2) and clicking the submit button, I am taken back to step 1 instead of the "done" method being called. And the whole thing just becomes a never ending loop. Here is my code. forms.py class ListingForm1(forms.Form): company_name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', })) address = forms.CharField(max_length=500, required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', })) class ListingForm2(forms.Form): business_category = forms.ModelChoiceField(queryset=BusinessCategory.objects.all(), required=True, widget=forms.Select(attrs={ 'id': 'cat-select', 'class': 'form-control', })) views.py class AddListing(SessionWizardView): form_list = [ListingForm1, ListingForm2] template_name = 'registration/listing_templates/addlisting.html' def done(self, form_list, form_dict, **kwargs): return HttpResponse("form submitted") {% extends "base.html" %} {% load static %} {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block css %} <!-- <link href="{% static 'dashboard_assets/css/custom.css' %}" rel="stylesheet"> --> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <style> #div_id_2-allkws{ display: none !important; } .select2{ width: 100% !important; } .select2-container .select2-selection--single{ height: calc(2.68rem + 2px) !important; } .select2-container--default .select2-selection--single .select2-selection__arrow{ top: 10px !important; } </style> {% endblock css %} {% block content %} <div class="content-container container"> {{ form.media }} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" … -
I need to sum same amount field for day and month in django query
class MyModel(models.Model): amount = models.FloatField() datetime = models.DateField() and MyModel have some types like card and p2p and other so I need to give in query SUM(amount)and filter(type=some_type ) and also I need full amount for month [. full_amount: ......, { "datetime_date": "2024-08-15", "terminal": "0.00", "cash": "0.00", "p2p": "0.00", "bank": "400000.00", "other": "0.00" }, { "datetime_date": "2024-08-28", "terminal": "100000.00", "cash": "200000.00", "p2p": "0.00", "bank": "0.00", "other": "0.00" } ] if I -
I'm stuck in creating a Django custom user model, I added my app to settings, created superuser but when I login it fails
Here is the code, it fails to login on admin even after doing all necessary migrations from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('users must have an email address') email = self.normalize_email(email) email = email.lower() user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user #def create_user(self, email, name, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_agent', False) extra_fields.setdefault('is_business', False) extra_fields.setdefault('is_personal', True) return self.create_user(email, name, password=None, **extra_fields) def create_personal(self, email, name, password=None): user = self.create_user(email, name, password) user.is_personal = True user.save(using=self._db) return user def create_agent(self, email, name, password=None): user = self.create_user(email, name, password) user.is_agent = True user.save(using=self._db) return user def create_business(self, email, name, password=None): user = self.create_user(email, name, password) user.is_business = True user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password=password) user.is_superuser = True user.is_active = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): USER_TYPE = ( ('personal', 'is_personal'), ('agent', 'is_agent'), ('business', 'is_business'), ('staff', 'is_staff'), ('superuser', 'is_superuser') ) type = models.CharField(choices=USER_TYPE, default='personal', max_length=255) email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_personal = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) is_business = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
Django with Signoz opentelemetry Tracing issue
I am trying to setup signoz for my Django project, but I have hit a dead end and now I am not able to proceed further, so I request you to help me out with this case. SigNoz Steps Requirements Python 3.8 or newer for Django, you must define DJANGO_SETTINGS_MODULE correctly. If your project is called mysite, something like following should work: export DJANGO_SETTINGS_MODULE=mysite.settings Step 1 : Add OpenTelemetry dependencies In your requirements.txt file, add these two OpenTelemetry dependencies: opentelemetry-distro==0.43b0 opentelemetry-exporter-otlp==1.22.0 Step 2 : Dockerize your application Update your dockerfile along with OpenTelemetry instructions as shown below: ... # Install any needed packages specified in requirements.txt # And install OpenTelemetry packages RUN pip install --no-cache-dir -r requirements.txt RUN opentelemetry-bootstrap --action=install # (Optional) Make port 5000 available to the world outside this container (You can choose your own port for this) EXPOSE 5000 # Set environment variables for OpenTelemetry ENV OTEL_RESOURCE_ATTRIBUTES=service.name=<SERVICE_NAME> ENV OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.{REGION}.signoz.cloud:443 ENV OTEL_EXPORTER_OTLP_HEADERS=signoz-access-token=<SIGNOZ_TOKEN> ENV OTEL_EXPORTER_OTLP_PROTOCOL=grpc # Run app.py with OpenTelemetry instrumentation when the container launches CMD ["opentelemetry-instrument", "<your_run_command>"] ... <your_run_command> can be python3 app.py or python manage.py runserver --noreload After following the above steps I've setup my django project accordingly, I've shared the my project changes below. Dockerfile FROM … -
Django filtering by annotated field
I'm trying to sort only those objects that contain arrays in the JSON field class Rule(models.Model): data = models.JSONField() class JsonbTypeof(Func): function = 'jsonb_typeof' Rule.objects.annotate(type=JsonbTypeof("data")).filter(type="array") But this query always returns an empty queryset However, if you call Rule.objects.annotate(type=JsonbTypeof("data")).values("type") then the expected queryset with a set of objects is returned: <QuerySet [{'type': 'object'}, {'type': 'object'}, {'type': 'array'}, {'type': 'array'}]> And if you do like this: Rule.objects.annotate(type=Value("array")).filter(type="array") Then the filtering is done correctly Are there any experts who can tell me how to filter and leave only arrays? -
Auto-generated DRF route *-detail not found while using ViewSets
I try to use Django Rest Framework (DRF) with HyperlinkedModelSerializers, ViewSets and a Routers. When I check the generated routes, Django shows me vehicle-detail, but DRF complains with an error: ImproperlyConfigured at /api/vehicles/ Could not resolve URL for hyperlinked relationship using view name "vehicle-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. The code below works well if a leave out the url from fields. Anyone an idea what is missing? urls.py from rest_framework.routers import DefaultRouter from vehicles import viewsets # Create a router and register our ViewSets with it. router = DefaultRouter() router.register(r'vehicles', viewsets.VehicleViewSet, basename='vehicle') # The API URLs are now determined automatically by the router. urlpatterns = [ path('', include(router.urls)), ] vehicles/viewsets.py class VehicleViewSet(viewsets.ModelViewSet): queryset = Vehicle.objects.all() serializer_class = VehicleSerializer vehicles/serializers.py class VehicleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Vehicle fields = ['url', 'name', 'description'] # fields = ['name', 'description'] # Removed 'url'. Now the API works Generated URLs api/ ^vehicles/$ [name='vehicle-list'] api/ ^vehicles\.(?P<format>[a-z0-9]+)/?$ [name='vehicle-list'] api/ ^vehicles/(?P<pk>[^/.]+)/$ [name='vehicle-detail'] api/ ^vehicles/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='vehicle-detail'] api/ [name='api-root'] api/ <drf_format_suffix:format> [name='api-root'] -
Django LoginView It doesn't show any error if I enter wrong input
im using django built in authentication but when im enter wrong email or password no errors comes up views.py from django.contrib.auth.views import LoginView,LogoutView class Login(LoginView): redirect_authenticated_user = True login.html <form method ="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> {{ field.errors }} {{ field.label_tag }} {{ field }} {{field.help_text }} </div> {% endfor %} <button type="submit" class="btn ">تایید</button> </form> output in browser so i expect if i enter email dose not exist in database tell me user not exist or if i enter wrong password show me a error message says wrong password consol log [30/Aug/2024 02:49:04] "POST /auth/login/ HTTP/1.1" 200 7144 Not Found: /favicon.ico [30/Aug/2024 02:49:05,079] - Broken pipe from ('127.0.0.1', 58248) -
Python, Django, Creating table model insert data
How can I correct the numbers in a table that lists ID numbers one by one in numerical order using Python and Django? Would you be polite and help me please guys i have no idea even if i deleted them all the next one goes with highest numbers up and so on -
MetabaseDashboardAPIView groups and dashboard and i am not still created any groups and dashboard for MetabaseDashboardAPIViewRoots
MetabaseDashboardAPIView groups and dashboard and i am not still created any groups and dashboard for MetabaseDashboardAPIViewRoots MetabaseDashboardAPIView groups and dashboard and i am not still created any groups and dashboard for -
Django I can't access the Image.url of the ImageField object
Hey im new in django and Im playing with uploading and showing images here. I have a model product : class Product(models.Model): title = models.CharField("Title",max_length=50) description = models.CharField("Description",max_length=200) active = models.BooleanField("Active",default=False) price = models.IntegerField("Price",default=0) stock = models.IntegerField("Stock",default=0) discount = models.IntegerField("Discount",default=0) date_created = models.DateTimeField("Date Created",auto_now_add=True) image = models.ImageField(null=True,blank=True ,upload_to="images/product/") def __str__(self): return self.title when Im retrieving this model using Product.objects.all(), and do for prod in products : print(prod.image.url) it returns error : The 'image' attribute has no file associated with it. but when im doing single query : Products.object.get(pk=5), I can access the image.url. I wonder why this happens tho. My english is bad so I hope I delivers it well. -
Datadog Integration with Azure App Service doesnt work
Summary of problem I have a django application which is containerised and running on Azure app service and I am having trouble sending traces to datadog. I have been stuck on this issue for a while and cant seem to solve it 2024-08-30T07:45:27.7503477Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 1 additional messages skipped 2024-08-30T07:45:33.5918905Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:45:46.1090952Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:46:08.9280102Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:46:12.7362637Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:46:20.2283515Z failed to send, dropping 2 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:47:03.2944981Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 3 additional messages skipped 2024-08-30T07:47:13.1601344Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 4 additional messages skipped 2024-08-30T07:48:02.5895355Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 2 additional messages skipped 2024-08-30T07:48:04.6799632Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 9 additional … -
How to do Markdown-like custom text to HTML formatting in Django?
My aim is to get text input, pass it through regex to turn it into HTML tags, and then safely display that HTML. Something like this: It's <script> *Bold*...! @sysop! which becomes, rendered faithfully, It's &lt;script&gt; <span class="f-b">Bold</span>...! @<a class="f-at" href="/user/123">sysop</a>! (It doesn't have to be exactly this, this is just an example.) Note that my output is able to grab values like the user sysop and get the user instance's URL /user/123 from the database - a good solution should be free enough to allow things like this. What I'm looking for is not specifically Markdown. What I'm looking for is the ability to do custom regex filters as shown above. If there is a way to do this, or even a package that allows me to do that (and remove/disable the existing Markdown/BBCode/etc. filters), that would be really great. -
How to integerate Saleor in my Django project
I have an existing Django project that I've been working on, and I'm interested in integrating the Saleor dashboard as an app within this project. Ideally, I would like to access the Saleor dashboard through a route like backend/. Additionally, I want to connect the Saleor dashboard with my existing product database. I already have a fully responsive frontend built with HTML and CSS that displays products and other related information. My goal is to integrate all the features of Saleor, such as checkout, payment processing, and other e-commerce functionalities, into my current project without needing to start a new project. How can I achieve this integration while maintaining my existing frontend and backend structure? Any guidance or suggestions on how to approach this would be greatly appreciated! -
HTML page to PDF using pdfkit in python django returning blank
I am trying to convert an html file to pdf after passing and populating it with some data. But it is returning a blank white page.I am using pdfkit and django and below is my code. def generate_pdf(data): """ Convert HTML content to PDF. """ html_string = render_to_string('timeline_template.html', {'data': data}) pdf_file = pdfkit.from_string(html_string, False) return pdf_file Also below is the html page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Timeline Report</title> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic' rel='stylesheet' type='text/css'> <style> body { margin: 0; padding: 0; background: rgb(245,245,245); color: rgb(50,50,50); font-family: 'Open Sans', sans-serif; font-size: 14px; line-height: 1.6em; } /* Timeline container */ .timeline { position: relative; width: 80%; margin: 0 auto; margin-top: 20px; padding: 1em 0; list-style-type: none; } /* Vertical line on the left */ .timeline:before { content: ''; position: absolute; left: 40px; top: 0; width: 2px; height: 100%; background: rgb(230,230,230); } /* Individual timeline items */ .timeline li { padding: 20px 0; position: relative; } /* Circle markers */ .timeline li:before { content: ''; position: absolute; left: 31.5px; top: 24px; width: 16px; height: 16px; border-radius: 50%; background: white; border: 2px solid rgb(0,0,0); } .timeline li .desc ul{ margin-left: 0; padding-left: 0; list-style: none; } .timeline li .desc …