Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Resizing image in javascript before uploading to server doesn't work
In my Django project, I used a form in a template html allowing users to upload images to the server. I used basic Django **ModelForm** with **ImageField** model and a basic view. Nothing special. I attached the following **JavaScript** file to that template: // Get the file input element const input = document.getElementById('id_image'); // Listen for the "change" event on the file input input.addEventListener('change', (event) => { // Get the selected file const file = event.target.files[0]; console.log(file); // Create a new FileReader object const reader = new FileReader(); // Set the onload event handler reader.onload = (event) => { // Create a new image object const img = new Image(); // Set the onload event handler img.onload = () => { // Set the maximum size of the image const max_size = 800; // Calculate the new width and height while maintaining aspect ratio let width, height; if (img.width > img.height) { width = max_size; height = img.height * (max_size / img.width); } else { height = max_size; width = img.width * (max_size / img.height); } // Create a canvas element const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; // Draw the resized image onto the canvas const … -
Django child model's Meta not available in a @classmethod
I am trying to write a check for django abstract base model that verifies some facts about the inner Meta of a derived class. As per documentation the check is a @classmethod. The problem is that in the method the cls parameter is the correct type of the derived class (Child1 or Child2), but its Meta is the Base.Meta and not the Meta of the appropriate child class. How can I access the inner Meta of a child model in a base model's @classmethod? I've tried both with a simple Meta class (no base class - Child1 below) and with one that derives from the base class' Meta (Child2) - as per https://docs.djangoproject.com/en/4.1/topics/db/models/#meta-inheritance from django.db import models class Mixin: @classmethod def method(cls): print(f"{cls=}, {cls.Meta=}") print([attr for attr in dir(cls.Meta) if not attr.startswith("__")]) class Base(Mixin, models.Model): name = models.TextField(blank=False, null=False) age = models.IntegerField(blank=False, null=False) class Meta: abstract = True class Child1(Base): city = models.TextField(blank=True, null=True) class Meta: db_table = "city_table" verbose_name = "12345" class Child2(Base): city = models.TextField(blank=True, null=True) class Meta(Base.Meta): db_table = "other_city_table" verbose_name_plural = "qwerty" Child1.method() Child2.method() In both cases the output is: cls=<class 'mnbvc.models.Child1'>, cls.Meta=<class 'mnbvc.models.Base.Meta'> ['abstract'] cls=<class 'mnbvc.models.Child2'>, cls.Meta=<class 'mnbvc.models.Base.Meta'> ['abstract'] While I want cls.Meta to be … -
Avoid simultaneous concurrent sessions django
I am developing a website which authenticates it's users based on mobile number already registered in external application's database and allows further journey on the website. How do I avoid users to authenticate with same mobile number from two different devices at the same time. I am using django framework for website's development?. Note: Django's auth model is not being used here. Also each session will timeout after 30 mins of inactivity, which is being handled by django-session-timeout library. Use of custom database and tables is allowed. -
A timeout error occurred when trying to upload an image in a Django application that is hosted on a cPanel server
Request Timeout This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact the administrator of this web site to increase 'Connection Timeout'. -
Generating a unique code/string in Django database
All I want is to generate a unique code preferably a mix of both letters and numbers when I create a Model Class called Competition in django. I want to use this code as a reference code for users to be able to fill in a form that will allow them to join that specific Competition. I have this code in my models.py: class Competition(models.Model): name = models.CharField(max_length=100) location = models.CharField(max_length=50) no_of_rounds = models.IntegerField(validators= [MinValueValidator (1, message='Please enter a number greater than or equal to 1'), MaxValueValidator (30, message='Please enter a number less than or equal to 30')]) gates_per_round = models.IntegerField(validators= [MinValueValidator (1), MaxValueValidator (30)]) ref_code = models.CharField( max_length = 10, blank=True, editable=False, unique=True, default=get_random_string(10, allowed_chars=string.ascii_uppercase + string.digits) ) def __str__(self): return self.name Preferably I don't want the unique code field to be a primary key if possible and that's why I have that field called ref_code. I tried creating a competition, which generated me this code LZDMGOQUFX. I am also wondering why the code only consists of letters. Anyways I tried creating a different competition but it raises an IntegrityError that says UNIQUE constraint failed in my ref_code field. Someone send help, thanks. -
django finding file in custom static folder returns none
trying to find file in custom static folder and it returns none i created a folder named 'static_test' in the project folder and added 'STATICFILES_DIRS' in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [ ("test",os.path.join(BASE_DIR, 'static_test')) ] also added static_url to urlpatterns in the main folder urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and when i call on find a file (in the folder) it return none from django.contrib.staticfiles import finders ... value = 'file.png' finders.find(value) i checked 'finders.searched_locations' and the folder is there is there anything i'm missing or .. ?? -
In which it is better to make an e-commerce shopping cart function in django or js
Hi I'm wondering if my way of making a shopping cart is good, all the tutorials I see on the web rather insist on doing it using js rather than recording it in a model table. class Cart(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def total(self): user_cart = Cart.objects.get(user=self.user) items_in_cart = CartItem.objects.filter(cart=user_cart) total_price = 0 for item in items_in_cart: total_price += item.product.price return total_price def quantity_of_items(self): user_cart = Cart.objects.get(user=self.user) items_in_cart = CartItem.objects.filter(cart=user_cart) return len(items_in_cart) class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) view to save class ProductDetailView(View): def get(self, request, pk): product = Product.objects.get(id=pk) context = {'object': product} return render(request, "products/detailview.html", context) def post(self, request, pk): if not request.user.is_authenticated: messages.success(request, "You must be logged in") return redirect('Login') cart, created = Cart.objects.get_or_create( user=request.user, ) cart.save() added_item = Product.objects.get(id=pk) added_item.popularity += 1 added_item.save() item_in_cart = CartItem.objects.filter(cart=cart) for item in item_in_cart: if item.product.title == added_item.title: messages.success(request, "It's already in the basket") return redirect('ProductDetail', pk=pk) new_item_in_cart = CartItem.objects.create( product=added_item, cart=cart, ) new_item_in_cart.save() added_item.quantity -= 1 if added_item.quantity == 0: added_item.is_available = False added_item.save() messages.success(request, "Add to cart") return redirect('home') With the help of redis I check every hour the time of the last change of the basket if it is greater than 1 hour … -
locate Error in django templates with multi inheritance
The issue occures when i'm rendering a template from a view, the template itself is including other templates, that also needs other templates and so forth, when an error happened at some leve.The console shows ONLY that there is an error when rendering the main template from the view, and it takes a lot of time to know exactly which template in the chain has the error, not like if the error happend in the .py file where it gives the exact file with the error. My current approach to help me debbuging is to use a function that is called from each file that is called each time, so at least i mimise the scope, are there better ways to do the job. -
Django Custom Commands Not Creating New Entries
I'm pretty new to Django, and I'm working on a simple app that generates json forecast data for a list of locations daily. This data is then used to display the forecasts to the user. I have a startjobs.py set up to run some functions that generate the json data I need for my app. I'm running into a problem where the jobs are successfully running, however, no new entries are added and no new json files created. I've looked through some similar questions, but couldn't find any solutions that work for my case. Here are my models: class Location(models.Model): location = models.CharField(max_length = 75, unique = True) def __str__(self): return f"{self.location}" INTERVAL_CHOICES = [ ('today', 'Today'), ('hourly', 'Hourly'), ('daily', 'Daily'), ] class Forecast(models.Model): location = models.ForeignKey(Location, on_delete = models.CASCADE) date = models.DateField() interval = models.CharField(max_length = 6, choices = INTERVAL_CHOICES, default = 'today') filename = models.FileField(upload_to = 'test/') def __str__(self): return f"Forecast for max wave height - {self.interval} in {self.location} on {self.date}" And my startjobs.py (I have my job running every 2 minutes for testing): locations = Location.objects.values_list("location", flat=True) def save_new_forecasts(): date = dt.date.today().strftime("%Y-%m-%d") for location in locations: if not Forecast.objects.filter(date = date).exists: daily_data = create_daily_forecast(location) hourly_data = create_hourly_forecast(location) … -
Why is refresh token not being returned from TokenRefreshView?
I'm using DRF-simple-jwt to implement auth. Since I want the tokens to be returned in a cookie instead of the response, I'm using the code I found in this github issue, where people have a workaround for sending the token in the cookie (as this is not implemented in the package). The issue for me is, in the CookieTokenRefreshView, "refresh" is not present in the response data. Because of which I'm getting a 500. The specific error is: ValueError: The view team.views.auth_viewset.view didn't return an HttpResponse object. It returned None instead None is being returned because the else condition is not being handled in the finalize_response of CookieTokenRefreshView. Why is it not present? The CookieTokenRefreshView: class CookieTokenRefreshView(TokenRefreshView): def finalize_response(self, request, response, *args, **kwargs): print("REFRESH -> ",response.data.get("refresh")) if response.data.get("refresh"): cookie_max_age = 3600 * 24 * 14 response.set_cookie( "refresh_token", response.data["refresh"], max_age=cookie_max_age, httponly=True, secure=True, samesite='Strict' ) # don't return tokens in response del response.data["refresh"] return super().finalize_response(request, response, *args, **kwargs) serializer_class = CookieTokenRefreshSerializer Apologies if this is a dumb question, I'm very new to both django and backend in general. -
Remove item from basket function in Django
I have recently amended my basket in my Django e-commerce site to take multiple variations of a product. I have got everything to work except the remove item method in views.py. It deletes all items with the same product ID. I can't work out how to get the method to recognise that an item variation is in the basket. Here is my function from views.py: def remove_from_basket(request, item_id): """Remove the item from the shopping basket""" try: product = get_object_or_404(Product, pk=item_id) item = None if 'product_item' in request.POST: flavour = request.POST['product_flavour'] strength = request.POST['product_strength'] product_item = request.POST['product_item'] item = f'{item_id}_{flavour}_{strength}' print(item) basket = request.session.get('basket', {}) if item: del basket[item_id]['items_by_variation'][item] if not basket[item_id]['items_by_variation']: basket.pop(item_id) messages.success(request, (f'Removed 'f'{product.name} flavour {flavour.upper()} from your basket')) print('test 1') else: basket.pop(item_id) messages.success(request, f'Removed {product.name} from your basket') print('test 2') request.session['basket'] = basket return HttpResponse(status=200) except Exception as e: messages.error(request, f'Error removing item: {e}') return HttpResponse(status=500) This was previously working with some Javscript in the Django html template. I have renamed the data attribute in the anchor tag and updated the JS. Here is the complete section of template code: {% for item in basket_items %} <tr> <td class="p-3 w-25"> {% if product.image %} <a href="{{ product.image.url }}" … -
Nested For loop in Django html template to create cards groups
I'm trying to do a script to create cards groups in my Django project. I send "mylist" data to frontend and I want to use also "my_dict" data to create nested for loop. I think I'm using a script that is not supported in templating. The logic is good but syntax is wrong and I can't find a right way to solve (also because I'm a beginner). my_dict = [ { "idToolGroup_id": 2, "idToolName": 2, "ToolName": "Tool 02", }, { "idToolGroup_id": 2, "idToolName": 3, "ToolName": "Tool 03", } ] my_list = [ [ { "idToolGroup_id": 2, "idToolName_id": 2, "idTable": 3, "TableName": "Table 3", "LinkToolPage": "TOOL03" }, { "idToolGroup_id": 2, "idToolName_id": 2, "idTable": 4, "TableName": "Table 4", "LinkToolPage": "TOOL04" } ], [ { "idToolGroup_id": 2, "idToolName_id": 3, "idTable": 5, "TableName": "Table 5", "LinkToolPage": "TOOL05" }, { "idToolGroup_id": 2, "idToolName_id": 3, "idTable": 6, "TableName": "Table 6", "LinkToolPage": "TOOL06" } ] ] Script I'm using is the following but doesn't work: {% for index, tool in enumerate(my_dict) %} <div class="RowGroup"> <div class="Block1"> <div class="card" style="width: 18rem;"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"> {{ tool.ToolName }} </h5> <p class="card-text">Some quick.</p> </div> </div> </div> <div class="Block2"> {% for item in my_list[index] %} <div … -
'QuerySet' object has no attribute 'user' in django
I am usign Django and have this function in view.py def ausers(request): result_list = list(Member.objects.all()\ .values('id', 'firstname', 'lastname', 'description', 'location', )) return JsonResponse(result_list, safe=False) And this is the javascript that call via ajax the function to fill a jquery datatable: <script> $(document).ready(function() { var table = $('#ourtable2').DataTable({ "ajax": { "processing": true, "url": "{% url 'ausers' %}", "dataSrc": "", }, "columns": [ { "data": "id"}, { "data": "firstname"}, { "data": "lastname"}, { "data": "description"}, { "data": "location"}, ], }); }); </script> I have the strange error: 'QuerySet' object has no attribute 'user' Could someone explain howto fix ? If i try to remove list( i have jason object not serializable Full traceback: Internal Server Error: /jsonresponse/ausers Traceback (most recent call last): File "/home/amedeo/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/amedeo/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/amedeo/.local/lib/python3.10/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/var/www/html/django-crud-ajax-login-register-fileupload/crud/views.py", line 189, in ausers result_list = list(Member.objects.all()\ File "/home/amedeo/.local/lib/python3.10/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view if test_func(request.user): AttributeError: 'QuerySet' object has no attribute 'user' [11/Mar/2023 20:00:30] "GET /jsonresponse/ausers?_=1678545030287 HTTP/1.1" 500 78597 Entire view from django.shortcuts import render, redirect from .models import Member, Document, Ajax, CsvUpload import datetime from django.contrib import … -
How to save fingerprint data in django
So I have a project where I have a model called Beneficiary where i need to store the fingerprint This is the model `class Beneficiary(models.Model): image=models.ImageField(upload_to='home/images/',blank=True,null=True) name = models.CharField(max_length=200) gender=models.CharField(max_length=6,choices=GENDER_CHOICES,default='male') dob=models.DateField() registration_date=models.DateField()` I want to save the fingerprints of the beneficiaries in the model. I am using DigitalPersona2 fingerprint sensor. I am pretty new to fingerprints so can anyone help? -
Why ajax like button in django is going crazy?
I've created a vanilla like button. It worked fine, but refreshes were really annoying, so I decided to implement ajax. It works kinda well, but I forced to update the page by myself to view the changes, cause I use <script></script> outside of the for post in posts loop. In case I include it inside the loop, like counter is going crazy and update ALL posts on the page with reversed like/unlike state. Maybe, somebody will point my mistake. posts/urls.py urlpatterns = [ path('create/', PostCreateView.as_view(), name='create_post'), path('like/', like_view, name='like_post'), path('<int:pk>/update/', PostUpdateView.as_view(), name='update_post'), path('<int:pk>/delete/', PostDeleteView.as_view(), name='delete_post'), path('<int:pk>/', PostDetailView.as_view(), name='detail_post'), ] posts/view.py def like_view(request, *args, **kwargs): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) context = { 'post': post, } if is_ajax(request): html = render_to_string('like_template.html', context, request=request) return JsonResponse({'form': html}) post_inclde.html AND ajax script. This html file I include in the user profile page and in the feed. <script> $(document).ready(function(){ $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like_post" request.user.slug %}', data: { 'post_id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function(response){ $('#like_section_{{ post.id }}').html(response['form']) }, error: function(rs, e){ console.log(rs.responseText); }, }); crossDomain: false }); }) </script> {% if posts %} {% for post in … -
Edit an Object of the PostgresSQL Database in Django from Celery Worker
I'm trying to edit an object which is saved into my Postgress Database used by Django from a Celery Worker. The Worker is called when the signal post_save is called with @receiver(post_save, sender=Task) def send_task_creation(sender, instance, created, raw, using, **kwargs): print(str(instance.pk)) rephrase_task.delay(instance.pk) My task.py contains the function for the Worker from celery import shared_task from celery import Celery from celery_progress.backend import ProgressRecorder from .models import Task from time import sleep from celery.utils.log import get_task_logger celery = Celery(__name__) celery.config_from_object(__name__) @shared_task(bind=True) def rephrase_task(self, primary_key): print('ID Worker ' + self.request.id) Task.objects.filter(pk=primary_key).update(TaskId=str(self.request.id)) progress_recorder = ProgressRecorder(self) for i in range(0,100): sleep(1) i += 1 progress_recorder.set_progress(i, 100) return 1 Now, everything seems to work expect the fact that Task.objects.filter(pk=primary_key).update(TaskId=str(self.request.id)) does really nothing I'm seeing the Celery task processing correctly but it seems it can't access the database My Celery settings in settings.py REDIS_HOST = 'localhost' REDIS_PORT = '6379' BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' How can I access the database from the Celery Worker -
I can’t access my backend (Django/Python) from an expo React Native App (Android Device)
I built a simple backend with Django/Python, I’m able to access it from Postman, but when I try to access it from an Expo React native App I get a network Error The way I test it is with my Samsung Android device I’ve tried everything From postman, if I send a get request like ‘http://127.0.0.1:8000/drinks/’, I get [ { "id": 1, "name": "Grape Soda", "description": "Soda with Grapes" }, { "id": 2, "name": "Orange Soda", "description": "Soda with Orange" } ] In the settings.py I have: CORS_ORIGIN_ALLOW_ALL = True From my Expo React Native App (ran on an Android): I have an apiCall component: import axios from "axios"; export const apiCall = axios.create({ baseURL: "http://127.0.0.1:8000/drinks/", timeout: 3000, // optional timeout setting headers: { "Content-Type": "application/json", }, }); Using it from a DrinksScreen.js: import { StyleSheet, Text, View } from "react-native"; import React, { useEffect, useState } from "react"; import { apiCall } from "../api/apicall"; const DrinksScreen = () => { const [drinks, setDrinks] = useState([]); function loadDrinksData() { apiCall .get("/drinks/") .then((drinks) => { console.log("success!, data: ", data); return drinks; }) .catch((error) => { console.log("error!: ", error); return error; }); } useEffect(() => { let data = loadDrinksData(); }, []); … -
How to use aio-pika in django project?
In my django project I want to publish messages to rabbitmq queues from its async views. For this I have created communication package inside my app where __init__.py contains: from myapp.communication.queue import Queue queue_instance = Queue() Class Queue is responsible for all queue-related actions like connection managing, message publishing etc. I establish the connection in myapp.apps:MyappConfig.ready method: from asgiref.sync import async_to_sync from django.apps import AppConfig from myapp.communication import queue_instance class MyappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myapp' def ready(self): connect_sync = async_to_sync(queue_instance.connect) connect_sync(...) But I get this on server start: Task was destroyed but it is pending! task: <Task pending name='Task-13' coro=<Connection._on_reader_done..close_writer_task() running at /usr/local/lib/python3.10/site-packages/aiormq/connection.py:506> wait_for=<_GatheringFuture finished result=[CancelledError(''), CancelledError('')]>> In my views I try to send a message: class MyView(APIView): async def get(self, request, *args, **kwargs): await queue_instance.publish(b'hello') And it results to RuntimeError: Task <Task pending name='Task-18' coro=<AsyncToSync.main_wrap() running at /usr/local/lib/python3.10/site-packages/asgiref/sync.py:306> cb=[_run_until_complete_cb() at /usr/local/lib/python3.10/asyncio/base_events.py:184]> got Future <Future pending cb=[FutureStore.__on_task_done..remover() at /usr/local/lib/python3.10/site-packages/aiormq/base.py:33, FutureStore.__on_task_done..remover() at /usr/local/lib/python3.10/site-packages/aiormq/base.py:33]> attached to a different loop I have tried to save the event loop where the connection was set up but it is closed in time of request processing. I have also tried to establish the connection inside the view and save the loop again. It worked … -
Why some Django view classes had not been defined as abstract base class?
I'm writing a small and lightweight Django-like back-end framework for myself just for experiment. If we look at ProcessFormView view(and some other views): class ProcessFormView(View): def get(self, request, *args, **kwargs): return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) ... To me it sounds like a valid case to define this class as an "abstract base class". After all, It needs that sub-classes provide render_to_response(), get_context_data(), get_form(), form_valid(), form_invalid(). (They will be provided by TemplateResponseMixin and FormMixin.) I can do something like this: class ProcessFormView(View, metaclass=ABCMeta): @abstractmethod def render_to_response(self, context): pass @abstractmethod def get_context_data(self): pass @abstractmethod def get_form(self): pass @abstractmethod def form_valid(self, form): pass @abstractmethod def form_invalid(self, form): pass def get(self, request, *args, **kwargs): return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) ... Or even better we can factor these abstract methods out to another ABC class and inherit from it to clear things up. I know that of course it's a made decision and nothing is wrong with it. I mostly interested to know if do what I just showed, how can it cause problem in future? what would be the cons … -
ERROR ModuleNotFoundError: No module named 'config'
We use the Django framework. I ran the testapscheduler.py file to test how many TODO lists I have within the 30 minute deadline and whether I get a proper LINE notification, and I get the following error. I believe I have the config set up correctly, so I don't know the cause of the error. ERROR ModuleNotFoundError: No module named 'config' testapscheduler.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') django.setup() import logging from models import Todo from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler from datetime import datetime, timedelta import pytz import requests from django.conf import settings import sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) def notify_todo(): # 現在の日時を取得 now = datetime.now(pytz.timezone('Asia/Tokyo')) # 締め切りが30分以内のTODOリストを取得 todos = Todo.objects.filter( deadline__gt=now - timedelta(minutes=30), deadline__lt=now + timedelta(minutes=30), ttime__isnull=False, ttime__gt=now.time() ) # 30分以内のTODOリストの数を出力 # ログの出力名を設定 logger = logging.getLogger('mylog') #ログレベルを設定 logger.setLevel(logging.DEBUG) #ログをコンソール出力するための設定 sh = logging.StreamHandler() logger.addHandler(sh) logger.debug(f'{len(todos)}個のTODOリストが締め切り30分以内にあります。') for todo in todos: #LINE NotifyのAPIトークンを取得 api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 通知メッセージの作成 message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}" # LINE Notifyに通知を送信 headers = {'Authorization': f'Bearer {api_token}'} payload = {'message': message} requests.post('https://notify-api.line.me/api/notify', headers=headers, data=payload) scheduler =BlockingScheduler(timezone='Asia/Tokyo') scheduler.add_job(notify_todo, 'interval', seconds=2) # 2秒ごとに実行 scheduler.start() -
Redirect after PUT or GET method in Django rest framework
view.py class Update (RetrieveUpdateDestroyAPIView): queryset = Main.objects.all() serializer_class = MainSerializer permission_classes = [IsAuthenticated] I want to redirect url after update or delete my article To '/api/. -
How can I change language of django errors to english?
So, As you can see there is russian language in django error message. I want switch language of errors to english. Also, I all my django projects errors are displayed in russian. I also use postgres as database, and this error is about wrong database relations. P.S I am so sorry for pictures censoring, but I must do it. -
Django upload file from the production area is not going to the folder I want
I got a problem. when I upload a file from admin area it goes to the correct folder and shows up correctly as I specified in the models.py : photo_service_1 = models.ImageField(upload to = 'photos_service/%y/%m/%d/', blank=True) but when I upload the file in production area it doesn't go to the correct path. thanks 4 helping me out. this is my html: and here is my related views.py: photo_service_1 = request. POST['photo_service_1'] contact.photo_service_1 = photo_service_1 -
django user profiles and different views
I'm building a CRM system and i want to have two types of users Administrator (More than 5 users) Supervisor (One person) Administrator will capture details in a django form, save it, and only have access to see their own work. A Supervisor will have a view of all Administrators captured work from the CRM, in a form of a list and all the of details the administrators. Question: How do i create two different types of users and how do i display the different types of views (Administrator = Their own work only, and Supervisor = All of the Administrators work). App One for users from django.db import models from django.contrib.auth.models import User # Create your models here. class UsersModels(models.Model): Role = [ ('Agent','Agent'), ('Manager','Manager'), ] TheUser = models.OneToOneField(User, on_delete=models.CASCADE) Rank = models.CharField(max_length=10, choices=Role, null=True) def __str__(self): return self.TheUser App Two from django.db import models from django.contrib.auth.models import User # Create your models here. class ExperimentalModels(models.Model): Name = models.CharField(max_length=12) Surname = models.CharField(max_length=12) created_by = models.ForeignKey(User, null=True, on_delete=models.CASCADE) def __str__(self): return self.Name Views is from django.shortcuts import render, redirect from . models import ExperimentalModels from . forms import ExperimentalForms from django.contrib import messages from django.contrib.auth.models import User # Create your … -
Django: CSRF verification failed. Request aborted. in production without domain name
I am running a Django app behind Nginx in a Docker environment. My problem is sort of the same from this thread: Django returning "CSRF verification failed. Request aborted. " behind Nginx proxy locally. Upon learning that I have to add CSRF_TRUSTED_ORIGINS in settings, since I am using Django version 4.X, I added my localhost CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://localhost:3000', 'https://example.com', ] I can login to my admin when the container is deployed locally. However, when I deployed it to production, I still get the error: CSRF verification failed. Request aborted. I deployed it in a Google compute engine. The app does not have a domain name yet. Thus, I visit the app using its external address of the machine: http://XX.XX.XX.XX/admin. Should I add this address to my CSRF_TRUSTED_ORIGINS? My understanding is that this is the same as adding the localhost http://localhost since I am visiting the host machine's address. CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://localhost:3000', 'https://example.com', 'http://XX.XX.XX.XX' ] What if I deployed it to another machine with a different address? Should I again add it? Is there any other way to allow the CSRF without specifically adding the address since it would be tedious if I would be changing/migrating in …