Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app on Cloud Run infinite redirects (301)
I am trying to deploy a Django app in a container to Cloud Run. I have it running well locally using Docker. However, when I deploy it to Cloud Run, I get infinite 301 redirects. The Cloud Run logs do not seem to show any meaningful info about why that happens. Below is my Dockerfile that I use for deployment: # Pull base image FROM python:3.9.0 # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY requirements.txt requirements.txt RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home django-user # Copy project COPY . /code USER django-user # Run server CMD exec gunicorn -b :$PORT my_app.wsgi:application I store all the sensitive info in Secrets Manager, and the connection to it seems to work fine (I know because I had an issue with it and now I fixed that). Could you suggest what I might have done wrong, or where can I look for hints as to why the redirects happen? Thank you! -
Forbidden (CSRF cookie not set.)
I am creating an app in Django, and I am getting this error: Forbidden (CSRF cookie not set.) I am using Elastic Beanstalk to host my website, and everything was fine until it started doing this. My settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'i1kf*^g1+dt*8n9bgcl80$d!970186x(x(9z2)7dfy1ynlxixn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['travelApp-kool4-env.eba-pfvej56m.us-west-2.elasticbeanstalk.com', "52.27.98.222", "35.166.8.118", "127.0.0.1",] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'crispy_forms', 'django.contrib.staticfiles', 'sights.apps.SightsConfig', 'itineraries.apps.ItinerariesConfig', ] 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', ] ROOT_URLCONF = 'travelApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'static')], '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', ], }, }, ] TEMPLATE_DIRS = ( '/home/django/myproject/templates', ) WSGI_APPLICATION = 'travelApp.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, … -
Why is my web service trying to redirect to a url that does not exist?
Basically, I have a web service that I am trying to build using Django. While working on the user LogIn, I ran into a confusing error. If the user is None (in my code, this means that the password or username does not match an existing one), then the user should be redirected to the LogIn page again, wich has a url path of /accounts/login, however, is instead sent to /accounts/login/login This is the code that controls the user LogIn def logIn(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if username is not None: auth.login(request, user) return redirect('/') else: return redirect('/accounts/register/') else: return render(request, 'logIn.html') This is the urls file inside the app from django.urls import path from . import views urlpatterns = [ path('', views.Empty), path('register/', views.register), path('login/', views.logIn) ] and this is the main urls file in the project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('ControlApp.urls')), path('accounts/', include('Accounts.urls')) ] Here's the full code in case it helps I tried changing removing completely the redirect instruction from the logIn function, however, evenm then the user was getting redirected to /accounts/login/login I assume there … -
Django template with forloop. Exception Type: IndexErrorm, Exception Value: pop from empty list
I have a web page with essays. Each essay (on its own sub-page) can have multiple videos from another model (linked with many-to-many relations). When I had - in the past - one video in a subpage with a particular essay (with a different column related to the video, in the same model: 'one-to-many model', now hashed in my models.py) then I used to be able to invoke the video in my essay page with: <p>{% video essay_videos.video.video_item_url %}</p> But now when I try to invoke a list of videos, with this code: <ul> {% for vid in essay_videos %} <li>{{ vid.video_item_url }}</li> {% endfor %} </ul> I'm getting a list of URLs - that's ok, but, when I try to use the embed-video tag (like before): <ul> {% for vid in essay_videos %} <li>{% video %}{{ vid.video_item_url }}{% endvideo %}</li> {% endfor %} </ul> or <ul> {% for vid in essay_videos %} {% video %} <li>{{ vid.video_item_url }}</li> {% endvideo %} {% endfor %} </ul> or <ul> {% video %} {% for vid in essay_videos %} <li>{{ vid.video_item_url }}</li> {% endfor %} {% endvideo %} </ul> ...In all cases, I've got Exception Type: IndexErrorm, Exception Value: pop from empty … -
django-money object not limiting decimal fields
I'm using django-money for all currency fields in an app I'm building. According to the documentation the default CURRENCY_DECIMAL_PLACES is 2, and I am explicitly calling it in my settings.py file as well. However, when I am checking a remaining balance on an order it is returning a Money object, but showing all the decimal places instead of just 2. In [2]: order.remaining_balance Out[2]: Money('0.002500000000', 'USD') Is there a reason it isn't restricting it to only the 2 decimal places that I am wanting? In the templates it is only showing two decimal places, but in my views.py file or the shell it renders the full decimal places. I've set the CURRENCY_DECIMAL_PLACES to 2, but I'm getting back more than 2 decimal places. -
Django admin open modal and create inlineobects
I would like to add a button in my admin change_view (of orders) to open a modal or and other page with a form. After submitting the form i want to create some inline objects (articles). Whats the best way to achieve this? I tried using admin_extra_buttons but i didnt figured out how to open a template and go back after submitting the data to create the inline objects. -
Error downloading file using Vue.js and Blob in frontend
I am using Vue.js in my frontend and facing an issue while downloading a CSV file from my API endpoint (Django backend) using the following endpoint and code. The error in the console says "Error while downloading file: Unknown Error". Can someone please help me resolve this issue? I'm using downloadData method to handle the download and DataRepository.ts to retrieve the data from the API. The endpoint GET /api/mydata/data_export/ returns a Content-Type header of text/csv and a Content-Disposition header of attachment; filename="data_export.csv" when the request is successful. @action(detail=False, methods=["get"]) def data_export(self, request, pk=None): feedbacks = self.get_queryset().filter(type=DataType.FEEDBACKPROPOSAL) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = 'attachment; filename="data_export.csv"' response["Access-Control-Allow-Origin"] = "*" writer = csv.writer(response) writer.writerow(["Question", "Answers", "Status", "Comment", "Email", "Phonenumber", "Proposed by"]) for feedback in feedbacks: writer.writerow( [ feedback.content, ";".join(feedback._question_answers), feedback.status, feedback.comment, feedback.email, feedback.phone_number, # feedback.proposed_by if not feedback.is_anonymous else "", ] ) return response Here's my code for the downloadData method: const downloadData = async () => { try { const repository = RepositoryFactory.get(DataRepository) const response = await repository.DataExport() if (response.status === 200) { const content = await response.text() const blob = new Blob([content], { type: 'text/csv' }) const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.setAttribute('download', 'data_export.csv') document.body.appendChild(link) link.click() } … -
Django Websocket is not sending instant within group
I have a websocket that should send messages very x seconds. I am connecting to the socket from two clients. THe socket should send the message to both when one of them sends a start message but only the one which doesnt started is getting the message every x seconds. The one which send is getting all messages after all the time passed This is the loop. The normal send is getting send instant to one that initialized the send (i used this for now as a half fix). My problem is that the send to the group is not send every x second as it should. Only the other connected client are getting it every seconds. The starting person is getting them all at once after the time passed async def init_starting(self): if not self.lobby.status == "waiting": print("Already Started") return False else: print("Starting Countdown") #self.lobby.status = 'starting' #await self.save_lobby() await self.send_status_message_with_status(status='starting', data={'has_started': self.lobby.has_started, 'host': self.host.username, 'players': self.players, 'lobby_code': self.lobby_code, 'countdown': 3}) countdown = 3 while countdown >= 0: countdown_data = { 'countdown': countdown } await self.send(json.dumps({"type": "msg", "message": countdown})) await self.send_status_message_with_status(status='starting', data=countdown_data) print(countdown) countdown -= 1 await asyncio.sleep(1) await self.send_status_message_with_status(status='started', data={ 'message': "Test" }) return True async def send_status_message_with_status(self, … -
Django Allauth Email Verification ( not effective after signup ) .. works after first login
I'm using allauth in my Django project and it's configured as below to use email for authentication. allauth configuration* ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_PASSWORD_MIN_LENGTH = 8 ACCOUNT_EMAIL_VERIFICATION = 'mandatory' SOCIALACCOUNT_EMAIL_REQUIRED = True Problem is : after signup, i'm directed to Home page without confirming email. if it tried to logout and login again, it directs me to (accounts/confirm-email/) and is now required to confirm my email. Note user is overridden *(settings.py)* AUTH_USER_MODEL = 'home.User'` *(models.py)* `class User(AbstractUser): photo = models.ImageField(upload_to='user/', blank=True, null=True) address = models.CharField(max_length=50, null=True, blank=True) date_of_birth = models.DateField(blank=True, null=True) phone = models.CharField(max_length=20) email = models.EmailField(unique=True) i think after signup the user shouldn't be able to login before confirming his email. -
DJStripe create subscription for user after logging in
When a user signs up for the service, a stripe subscription should be automatically created when the user logs in. To achieve this, I added the following code snippet to my middleware. stripe_customer, _ = Customer.get_or_create(subscriber=user) user.update_stripe_customer(update_name=True) subscription = stripe.Subscription.create( customer=stripe_customer.id, items=[{"price": "price_id"}], metadata={ "user_id": user.id, "product_type": "type1", }, trial_period_days=trial_period_days, cancel_at_period_end=True, currency="eur", ) # Option 1 Subscription._get_or_retrieve(subscription.id) # Option 2 Subscription.sync_from_stripe_data(subscription) Both options work locally, also another option using djstripe. In the moment, I deploy my app to the staging enviroment, the subscription is being created but not saved into the database. As the staging enviroment uses transactions, I also tried to call the signup action after the transaction has been finished but the problems continues. What happens, stripe is being called, a customer and a subscription created but not saved into the database. -
Django static files not found in production 1.2
My code is working fine in the testing environment (DEBUG=TRUE) but when I switch to DEBUG=FALSE, static files are not being loaded. To run the application I follow: python3 manage.py collectstatic --no-input --clear python3 manage.py runserver settings.py: from pathlib import Path, os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-z$w^9$+no7vh2hbu#d6j7b3rx!+m=ombxy9=h%u&cr_=0v)ojv' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['.vercel.app', '.alisolanki.com', '.now.sh'] # Application definition INSTALLED_APPS = [ 'home', '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', ] ROOT_URLCONF = 'sentiment_analysis.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] WSGI_APPLICATION = 'sentiment_analysis.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # } # } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', … -
Django Form fields changing after page refresh
The first time I open this ModelAdmin's /add page, all the fields of the ServiceProvider model are displayed, although I specified with self.fields the fields that should be displayed. When pressing F5 to reload the page, the unsolicited fields do not appear. I suspected cache, but disabling the caches did not cause changes. The problem with loading all fields is that it also does some heavy querying related to those fields. class ServiceProviderAdmin(admin.ModelAdmin): ... def get_form(self, request, obj=None, **kwargs): self.fields = ( "name_registration", "name_social", "nome_usual", ("gender","document"), "department", "department_aditionals", "picture", "active", ) if request.user.has_perm("rh.can_edit_secondary_mail"): self.fields = self.fields + ("email_secondary",) self.form = ServiceProviderFormFactory(request.user) return super().get_form(request, obj=obj, **kwargs) def ServiceProviderFormFactory(user): class ServiceProviderForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ... class Meta: model = ServiceProvider exclude = ("",) -
How do I rectify this collectstatic error?
I am trying to run python manage.py collectstatic But I got the following error message: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\User\\Desktop\\PY4E\\djangoPorfolio\\static' Below are my settings.py STATIC_URL and STATIC_ROOT from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media') ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'mediafiles/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" Am I missing something? -
javascript fetch request(PUT) for formdata doesnt work when i specify the Content-type in the headers param
this is the request: let form = document.querySelector('form') let data = new FormData(form) fetch("http://127.0.0.1:8000/products/", { method: 'PUT', body: data, headers: { 'X-CSRFToken': "{{ csrf_token }}", } }) .then((response) => response) .then((data) => console.log(data)); So when I specify the Content-type in the headers param(doesnt matter if multipart/form-data, urlencoded etc. I tried it all) it doesnt work, but when I omit the content-type my backend(django) can process the request and the image is uploaded to the server and the rest of the formdata is being processed too. I looked at the network tab in ChromeDev Tools and the header is set to multipart with a strange ending: "multipart/form-data; boundary=----WebKitFormBoundary1QDdcJugTKrSMnto", does someone know the reason for this strange behavior? enctype is not set in the form element Thanks in advance <3 the content type header is set automatically. -
Django: Return values based on condition using SerializerMethodField
I have the tables: User, Event and EventTicket. I have to return total transactions and total tickets sold of each event. I am trying to achieve this using Django serializers. Using only serializers, I need to find the following: 1. total tickets sold: count of items in EventTicket table for each event 2. total transactions: sum of total_amount of items in EventTicket table for each event where payment_status: 1 models.py: class User(AbstractUser): first_name = models.CharField(max_length=50,blank=False) middle_name = models.CharField(max_length=50,blank=True) last_name = models.CharField(max_length=50,blank=True) class Event(models.Model): name = models.CharField(max_length=100, null=False, blank=False) user = models.ForeignKey(User, related_name='%(class)s_owner', on_delete=models.CASCADE) description = models.TextField(null=False, blank=False) date_time = models.DateTimeField() class EventTicket(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) event = models.ForeignKey(Event,on_delete=models.CASCADE, related_name='event_tickets') payment_status = models.SmallIntegerField(default=0, null=False, blank=False) ## payment_success: 1, payment_failed: 0 total_amount = models.FloatField() date_time = models.DateTimeField() My desired output is: "ticket_details": [ { "event_id": 1, "event_name": Event-1, "total_transactions": 10000, ## Sum of all ticket amounts of event_id: 1, where payment_status: 1 "total_tickets": 24, ## Count of all tickets that belong to event_id: 1 }, { "event_id": 2, "event_name": Event-2, "total_transactions": 10000, ## Sum of all ticket amounts of event_id: 2, where payment_status: 1 "total_tickets": 24, ## Count of all tickets that belong to event_id: 2 }] This is what I have … -
How to get value from the different django model in DTL?
I am having 3 different models - User, Thread and UserProfile. User model contains information like ID, First_name and Last_name. Thread model contains information like class Thread(models.Model): first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person') second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,related_name='thread_second_person') updated = models.DateTimeField(auto_now=True) and UserProfile model, class master_personal_profile(models.Model): custom_user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) picture = models.ImageField(default='profile_image/pro.png', upload_to='profile_image', blank=True) when I am trying to get all the threads from Thread model and pass it from views.py to my HTML template then I can access User model fields like - {{ thread.second_person.ID}} {{ thread.second_person.First_name}} But how can I access picture field from UserProfile with the help of custom_user ? -
Access django url without apache http basic authentication
I'm working on a Django 3.2 project which is hosted using Apache 2.4 server. The user authentication in this project is handled using HTTP Basic Authentication configured using LDAP. I have implemented a sign up feature for new users. For that I have created the necessary form, view, template and url pattern in the Django project. The urlpattern to visit the sign up form is /signup. My goal is to make the sign up urlpattern accessible to anyone i.e. prevent the Basic Authentication from showing when the sign up urlpattern is requested by user in the browser. JFI, the complete Apache configuration is already complete and works already. To achieve this, I have used the "LocationMatch" directive in the Apache configuration within the VirtualHost directive: ... <LocationMatch "^/signup$"> Require all granted </LocationMatch> ... With this the Basic Authentication is removed when /signup URI is requested, but the server always redirects to another url which ultimately requires authentication hence giving the basic auth pop-up. $ curl -I https://*****.com/signup HTTP/1.1 302 Found ... I have tried to redirect the request explicitly to /signup whenever the is /signup. This ends up in an endless loop of redirections. RewriteEngine on ... RewriteRule ^/signup$ /signup … -
How add object variable in static block django?
How can I implement addition object variable in static block, for example: <script src="{% static 'base/js/{{obj.id}}_container.js' %}"></script> How to make it works? -
how do I render out all objects of a loop in a email template
I'm trying to render all the product names, prices and quantities related to list_ordered_items into my email template. But the email contains just one product object detail instead of multiple product object details, I'm already looping through in the view! what's causing this? how do I fix this? models class Product(models.Model): name = models.CharField() final_price = models.DecimalField() class OrderItem(models.Model): product = models.ForeignKey(Product) quantity = models.IntegerField(default=0) views list_ordered_items = OrderItem.objects.filter(order__customer__user=request.user).select_related('product') for loi in list_ordered_items: product_name = loi.product.name product_price = loi.product.final_price product_qty = loi.quantity context = {'product_name': product_name, 'product_qty': product_qty, 'product_price': product_price} email template <tr> <td align="left" style="padding:0;Margin:0"><h4 style="Margin:0;line-height:17px;mso-line-height-rule:exactly;font-family:arial, 'helvetica neue', helvetica, sans-serif;font-size:14px"><strong></strong>{{product_name}}<strong></strong></h4></td> </tr> <tr> <td style="padding:0;Margin:0;text-align:center;font-size:13px;line-height:13px" width="15%" align="center"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-family:arial, 'helvetica neue', helvetica, sans-serif;line-height:21px;color:#333333;font-size:14px"><strong></strong>{{product_qty}}<strong></strong></p></td> <td style="padding:0;Margin:0;text-align:center;font-size:13px;line-height:13px" width="30%"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-family:arial, 'helvetica neue', helvetica, sans-serif;line-height:21px;color:#333333;font-size:14px"><strong></strong>${{product_price | floatformat:2}}<strong></strong></p></td> </tr> current view: should look like this: -
django: Exception has occurred: IndexError pop from empty list
I have been building a website where each essay may have a video object. For some reason, this error in Django continues to persist and I cannot understand where it comes from and how to fix it. The error related to views.py Exception has occurred: IndexError pop from empty list File "C:\foo\project\bar\views.py", line 65, in index_dev return render( IndexError: pop from empty list views.py: def index_dev(request): essay = EssayCls.objects.all().order_by('-date')[:3] video_obj = VideoObject.objects.all() user_agent = get_user_agent(request) context = { 'text_content': essay, 'show_text_content': True, 'video_obj': video_obj } if user_agent.is_pc: return render( request, 'dev/index_page.html', context ) models.py: ... from embed_video.fields import EmbedVideoField ... class VideoObject(models.Model): video_item_url = EmbedVideoField() # same like models.URLField() added_date = models.DateTimeField(auto_now_add=True, null=True) title_video = models.CharField(max_length=200) class Meta: ordering = ['-added_date'] class EssayCls(models.Model): title = models.CharField(max_length=200) organizer_email = models.EmailField(null=True) date = models.DateField(null=True) slug = models.SlugField(unique=True, db_index=True) description = models.TextField(validators = [MinLengthValidator(10)]) details = models.TextField() image = models.ImageField(upload_to='images') video = models.ForeignKey(VideoObject, blank=True, null=True, on_delete=models.SET_NULL, related_name="video_obj") language = models.ForeignKey(ProgLang, null=True, on_delete=models.SET_NULL) guest = models.ManyToManyField(SendMeMessage, blank=True) tags = models.ManyToManyField(Tag) template.html: {% for essay_item in text_content %} <div class="contact-details"> <h3><a href="{% url 'essay-path' slug %}" style="text-decoration: none; color: #35049080;">{{ title}}</a></h3> <p>{{ essay_item.description|convert_markdown|safe }}</p> <br /><br /> <p>Does this video work? check below:</p> {% comment … -
How to use HTML and JSON at the same time in DRF
I started using Django REST framework just a while ago and I had a little question. How can I get an HTML page on the site that I am currently making and get JSON format for other "clients"(e.g mobile aps, desktop etc) I searched for the answer on the internet, but didn't found any information about this -
Django. Websockets. Replace repalce part websocket URL
I have page with chat. There is list which consist of started dialogues and current dialog. Example Current dialog work by using webscoket connection and Django channels. I want then when click then jump in other dialog without refresh page. At the same time, URL changes, but websocket connection not changes - it is problem. How change websocket connetion? Example: .../chat/Joseph change to .../chat/Tyler If this can be implemented in some other way, I will be glad to have a couple of words. Thank you! -
СМС рассылка на Python/ Django
Я делаю сайт на DJANGO для одной компании. Они хотят внедрить СМС рассылку. Есть база данных номеров. Как это все можно реализовать? Подскажите если не сложно P.s. Я знаю что есть платные смс сервисы для этого. Но я бы хотел использовать самый правильный способ. -=========================== -
django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" 2023
I have got this error when I 'am doing for the first time dockerizing a Django existing app. bellow I have PostgreSQL db. image and conf its volume and add it to my app web...… can u help this one plz compose.yml version: '3.8' services: web: build: . volumes: - .:/dstorage ports: - 8000:8000 container_name: web_container command: python manage.py runserver 0.0.0.0:8000 depends_on: db: condition: service_healthy db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB= postgres - POSTGRES_USER = postgres - POSTGRES_PASSWORD= 123654 container_name: POSTGRES_db healthcheck: test: ["CMD", "pg_isready", "-q"] settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD': '123654', 'HOST':'db', 'PORT': 5432, i can't pass this error in return i have got FATAL: password authentication failed for user -
Control an asynchronous routine elegantly in Django
Using Django, I need to poll updates from a GraphQL subscription and being able to turn the updates on and off. My implementation uses websockets package wrapped in an async function to poll updates from a local container providing a GraphQL subscription and stores them in Django database. I need to find a way to control this polling feature with an on/off GraphQL mutation that would start or stop the readings and database updates. I've tried using celery by starting a celery task upon Django apps.py ready() method, but I think it became overkill and I ended up having multiple tasks being too hard to manage. I've also thought about using a database record to keep the status and run the asynchronous polling code in a management command, but it seems not a great idea to continuously read the feed status from database without any hook or so. My last attempt was to trigger a GraphQL mutation on my own service using a management command at the start of my docker-compose fleet to start the readings, but the asyncio event loop ends up locking the main thread for some reason. Here's my current implementation unsing asyncio : """ Feed listener …