Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I Deploy a Django App as a .war file or in any other packaged way?
I have a Django Project for which I am trying to find a way to deploy as a .war file. My objective is to not reveal the source code during deployment to De-Couple Django App from Database and deploy as a .war file. This will help me to update the app without re-initializing database. As Jython is not supported for Python3, is there an alternative? I also tried to create an exe through PyIntsaller but it acts as a malicious executable. -
Django crontab can’t connect database(Postgresql) with docker; no such table err
I am using django and postgresql. I am using django-crontab to change the data. It runs well in the local environment, but we use docker to deploy and watch, and I confirmed that when cron runs, we refer to sqlite3. I also made a separate cron container in docker composite and ran it, I am using it incorrectly because I am a beginner. Help me #goods/cron.py from goods.models import Goods def test(): print(Goods.objects.all()) ./docker-compose.yml version: '3.8' volumes: postgres: {} django_media: {} django_static: {} static_volume: {} services: postgres: container_name: postgres image: postgres:14.5 volumes: - postgres:/var/lib/postgresql/data/ environment: - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_DB restart: always nginx: container_name: nginx image: nginx:1.23.2 ports: - "80:80" - "443:443" volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - django_media:/media/ - django_static:/static/ depends_on: - asgiserver - backend restart: always django_backend:/app/media backend: host:container container_name: django_backend build: . entrypoint: sh -c "python manage.py migrate && gunicorn handsup.wsgi --workers=5 -b 0.0.0.0:8000" restart: always volumes: - ./:/app/ - /etc/localtime:/etc/localtime:ro - django_media:/app/media/ - django_static:/app/static/ environment: # - DEBUG - POSTGRES_DB - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_HOST - POSTGRES_PORT depends_on: - postgres redis: image: redis:5 asgiserver: build: . command: daphne -b 0.0.0.0 -p 8080 handsup.asgi:application volumes: - ./:/app/ restart: always environment: - DEBUG - POSTGRES_DB - POSTGRES_USER - … -
what is the quickest way to style django model form fields one by one
I have ModelForm which renders successfully. this is my forms.py form class UploadPostsForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'description', 'date', 'file'] this is how it looks in templates I want it to look like below using bootstrap5 what is the fastest and easiest way to do it? I have found three ways. adding custom template tags defining styles in each form fields or all at once overriding __init__ method what is the best way to do this? -
Redirect after saving site setting
I'm trying to redirect the user to a custom HTML page after saving a BaseSiteSetting model in Wagtail 4.1.1 I'm not sure how to accomplish this, the BaseSiteSetting inherits from django models.Model which means it's possible to override the save() function but how would I do the actual redirect without having access to the request? Another acceptable solution would be to add an extra button in the CMS by overriding the default BaseSiteSetting HTML template but I can't seem to get that working either, except for ModelAdmin templates. I've opened a stackoverflow question about that here. My view with the custom HTML page: def sync(request): return render(request, "import.html", {"WS_PROTOCOL": settings.WS_PROTOCOL}) My BaseSiteSetting model: @register_setting class AnonymousSuccessStoryImportSetting(BaseSiteSetting): """ Setting for importing anonymous success stories. """ file = models.FileField( upload_to="success_story_imports/%Y/%m/%d/", validators=[validate_file_extension], help_text="Upload a CSV file, then click 'Save' afterwards", blank=True, null=True, ) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Importer" I've looked around for possible solutions, and found some wagtail hooks but these only apply to the Wagtail Page model, for example: after_publish_page. It's unfortunate that there's no hook for standard django models. -
How to set the queryset in forms.Form(ModelChoiceField) for Drop Down city List?
I have set a ForeignKey() for class Town in the models file. Ideally, when I select a state, all towns belonging to this state will be listed in town. #models.py class State(models.Model): state = models.CharField(max_length=50) code = models.CharField(max_length=3) def __str__(self): return self.state class Town(models.Model): town = models.CharField(max_length=50) code = models.CharField(max_length=4) state = models.ForeignKey(State, on_delete=models.CASCADE) def __str__(self): return self.town Now I can only use all() in queryset to display all towns. I feel like I should use filter(), but I can't find a way to do it。 #forms.py class Location(forms.Form): state = forms.ModelChoiceField( required = True, label = "State", queryset = State.objects.all(), widget = forms.Select(attrs = { "class": "form-list-field"} )) town = forms.ModelChoiceField( required = True, label = "Town", queryset = Town.objects.filter( ??? ).order_by('town'), widget = forms.Select(attrs = { "class": "form-list-field"} )) -
Trying to find a way to pass a list to an item in request.POST. How do I do it?
This is my html code in django project: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <script src="{% static 'jquery-3.6.2.min.js' %}" ></script> </head> <body> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <button id="button1" name="action" value="">button2</button> <script> $("#button1").click( function(){ arr = ["one", "two"] $("#button1").attr('value',arr) } ) </script> </form> </body> </html> By clicking the button I run JQuery that assigns an array: arr to button1's value. This is request.POST afterwards: <QueryDict: {'csrfmiddlewaretoken': ['Rws3PVVBVOGsoXm720M5YbuZNTYMin6CxklI78in2PWdrxAYKxw3XqV7cba2xt7P'], 'action': ['one,two']}> Instead of 'action': ['one,two'] I want to get 'action': ['one', 'two'], or 'action': [['one', 'two']] How do I do it? -
Why is Django's client.post nesting arg values in lists?
I'm unit testing my api with Django like this: result = self.client.post( reverse(path), { "arg1":"value" }) Inside the view, I breakpoint. @api_view(["POST"]) def post_arg(request): breakpoint() But when I print the POST data, the values have been added to lists. (Pdb) request.POST { 'arg1': ['value'] } This example only has one arg, but if I add more they are each added to a list. I don't think this happens when my frontend posts data, so why does it here? And is there a way to not have the values added to a list? -
telebot register_next_step_handler_by_chat_id not works in celery shared task
I have a small tg bot django project and the bot needs to send a message to users that have been inactive for over an hour and then wait for input from the user using tg_nick_or_phone_input_handler and write it to TelegramBotClientModel instance, sending more messages to chat def tg_nick_or_phone_input_handler(message): chat_id = message.chat.id bot_client = TelegramBotClientModel.objects.get(chat_id=chat_id) bot_client.phone_or_nickname = message.text bot_client.request_sent = True bot_client.save() bot.send_message( chat_id=chat_id, text='REQUEST SENT' ) bot.send_message( chat_id=chat_id, text='some message' ) import django.utils.timezone as tz from celery import shared_task from tg_funnel_bot.bot import bot from .views import tg_nick_or_phone_input_handler from .models import TelegramBotClientModel, BotMessagesSettingsModel # celery task where should register next step handler @shared_task(name='send_message_for_interrupted_dialog_after_one_hour') def send_message_for_interrupted_dialog_after_one_hour(): bot_messages_settings = BotMessagesSettingsModel.objects.all().first() inactive_for_hour_clients = TelegramBotClientModel.objects.filter( updated_at__lte=tz.now() - tz.timedelta(minutes=5), request_sent=False, message_for_one_hour_inactive_sent=False ) for inactive_client in inactive_for_hour_clients: chat_id = inactive_client.chat_id bot.send_message( chat_id=chat_id, text=bot_messages_settings.user_inactive_for_hour_message_text_first_part ) bot.send_message( chat_id=chat_id, text=bot_messages_settings.user_inactive_for_hour_message_text_second_part, reply_markup=bot_messages_settings.get_inactive_message_second_part_markup() ) bot.register_next_step_handler_by_chat_id( chat_id=chat_id, callback=tg_nick_or_phone_input_handler ) inactive_client = TelegramBotClientModel.objects.get(pk=inactive_client.pk) inactive_client.message_for_one_hour_inactive_sent = True inactive_client.save() return tz.now() bot.register_next_step_handler_by_chat_id not register handler and follow input in bot chat not processing. Maybe i cannot use bot instance in another processes, but i can send messages, so strange. Give me a hand please -
Django autogenerated models and relationships doesn't show up in model meta
I have the below code to create a Vote model for any given other model that I want to attach this relation to. from functools import lru_cache from django.contrib.auth import get_user_model from django.db import models from django.utils.translation import gettext_lazy as _ from apps.common.models.base import BaseModel from apps.common.utils import camel_to_snake @lru_cache(maxsize=None) def create_vote_class(klass): class Vote(BaseModel): class VoteType(models.IntegerChoices): UPVOTE = 1, _("Upvote") DOWNVOTE = -1, _("Downvote") user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name=f"{camel_to_snake(klass.__name__)}_votes", verbose_name=_("User"), help_text=_("The voter."), ) post = models.ForeignKey( klass, on_delete=models.CASCADE, related_name=f"{camel_to_snake(klass.__name__)}_votes", verbose_name=_("Post"), help_text=_("The post this vote is for."), ) body = models.IntegerField( choices=VoteType.choices, verbose_name=_("Body"), help_text=_("The actual vote. -1 or +1"), ) def type(self): return self.get_body_display() class Meta: abstract = True app_label = klass._meta.app_label # NOQA klass_name = f"{klass.__name__}Vote" bases = (Vote,) class Meta: app_label = klass._meta.app_label # NOQA verbose_name = _(klass_name) verbose_name_plural = _(f"{klass_name}s") klass_dict = {"__module__": klass.__module__, "Meta": Meta} vote_class = (type(klass_name, bases, klass_dict) # NOQA return vote_class class VoteMaker: is_relation = True many_to_many = True def __init__(self, **kwargs): self.related_name = kwargs.get("related_name") self.vote_class_attribute_name = kwargs.get("vote_class_attribute_name") def contribute_to_class(self, cls, name): setattr(cls, self.vote_class_attribute_name, create_vote_class(cls)) setattr(cls, name, self.get_votes_field(cls)) def get_votes_field(self, cls): field = models.ManyToManyField( get_user_model(), through=create_vote_class(cls), related_name=self.related_name or f"voted_{camel_to_snake(cls.__name__)}s", verbose_name=_("Votes"), help_text=_("Votes for this post."), ) return field def votes(related_name=None, vote_class_attribute_name="vote_class"): vote_maker = VoteMaker( … -
Connecting my MySQL database ran with docker-compose to Django
I can't figure out how to get it connected. When I run the command - python manage.py check --database default I get the error below. **ERROR: django.db.utils.OperationalError: (1049, "Unknown database 'bears-local-db'") ** When I log into mysql with the CL I don't see the database when I run show databases; DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bears-local-db', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '127.0.0.1', 'PORT': '3306' } } services: local-db: image: mysql:8.0 container_name: local-db ports: - 3308:3306 # - ${MYSQL_OUTER_PORT}:${MYSQL_INNER_PORT} network_mode: host environment: MYSQL_ROOT_PASSWORD: 'password' MYSQL_USER: 'user1' MYSQL_DATABASE: bears-local-db volumes: - ./mysql:/var/lib/mysql It took me 5 errors to get to this point so I haven't tried a whole lot but messing with the django settings. -
Django Fetch API JSON Parse Unexpected Character
I'm trying to update an upvote downvote counter with fetch api on my Django App about poop. I'm new to fetch and using this project to learn about it. It is returning the JsonResponse, but it kicks out an Error which I'm not sure how to troubleshoot. I've Followed the Basic Structure of the Fetch Tutorials, but I'm getting this strange error. I don't see what's wrong with my syntax, please help! .html this is the div counter I'm trying to replace <div class="voteCount{{poopfact.id}}">{{ poopfact.total_votes }}</div> .script here's my basic javascript, kicking out the error fetch(url, { headers:{ method: 'POST', 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'poopfact_id':poopfact_id } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log('error')) .views this is what I'm returning, it seems successful def vote(request, poopfact_id): ... data = { "total_votes": total_votes, "value":poopfact_id } return JsonResponse(data, safe=False) console.log error I'm not sure how to troubleshoot it. Can anybody point me in the right direction? -
Django Cellery stuck as Pending
I am attempting to use celery within my django app to speed up processing time of a function and I can't get it to work correctly. I am using RabbitMQ. my tasks.py from celery import Celery from celery import shared_task,current_task from myapp.celery import app @app.task def add(x,y): for i in range(25000000): a = x+y return x+y my python code def test_multi_func(): x = 5 y = 10 i = 15 print(f"start = {time.perf_counter()}") while i > 0: g = add.delay(x,y) result = add.AsyncResult(g) i -= 1 print(result.backend) print(result.status) print(f"end = {time.perf_counter()}") print(f"g = {g.get()}") print(f"x = {x} ; y = {y}") my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_select2', 'chartjs', 'django_material_icons', 'material', 'django_celery_results', 'celery_progress', 'django_apscheduler' ] BROKER_URL = 'django://' result_backend = 'django-db' CELERY_RESULT_BACKEND = 'django-db' result_persistent = True task_result_expires = None send_events = True CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BROKER_URL = 'amqp://localhost' CELERY_CACHE_BACKEND = 'django-cache' CELERY_IGNORE_RESULT = False my celery.py import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp', backend='amqp://guest@localhost:15672/', broker='amqp://guest@localhost:15672/', include=['myapp.tasks']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') What am I doing wrong? I am have a … -
<link rel="stylesheet" type="text/css" href="{% static 'css/admin.css' %}"> Not working
When I make the website outside of Django it works perfectly fine. However, when I integrate everything in and put the CSS file in static files, it fails to load. The JavaScript file in the same folder loads perfectly fine. The files being used are: base.html, adminDash.html, admin.js, main.css, and admin.css. The admin.css file is the one specific to adminDash.html and is the one failing to load. Attached are images of all files, what the site should look like, and what it currently looks like. admin.js main.css admin.css adminDash.html base.html what it looks like outside django what it looks like inside django I have tried running it outside of the django project, changing the file location, got some friends to have a go at it, and got chatGPT to try rewriting it it. -
Django - ModelForm Change with ChoiceField
I have a ModelForm and i want to hide some fields and add help text according to values getting from the choiceField ex: if value_getting_from_the_choiceField == '1' hide_some fields in ModelForm elif value_getting_from_the_choiceField == '2' add help text to some fields -
Django Rest Framework web service - `Unsupported Media Type: /api/function_name`
I'm working on building a React (Next.js) application that will communicate with a DRF web service. The application will not be interacting with a database very much but instead sending in data to crunch with the DRF app which will return derived values for display in the React app. On a form submission, I have the following function run on the React side: (values) => { fetch(http://localhost:8000/api/testing_post/", { mode: 'no-cors', method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(values, null, 2) }).then(res => { console.log("Request complete! response:", res); }); } This posts the form data to the following view function in the DRF app: @api_view(["POST"]) @parser_classes([JSONParser]) def testing_post(request): print(dir(request)) print(request.data) return Response(status=status.HTTP_200_OK) When I run without print(request.data), everything works as expected. However, when I include this line, I get a 415 error Unsupported Media Type: /api/testing_post/ I'm confused as to why I'm receiving this message - I'm clearly setting the content type in the request; and, on the server side, am using a JSON parser. Does anyone know where the issue is stemming from? Thanks in advance! -
How to add data from an API to Django's database when i click on a button
My question is going to be split into two halves for a better understanding. First half: I'm trying to add a bunch of data that I rendered on a page from an API endpoint, to my database when I click "Add to my records", as can be seen in the image below, keeping in my mind that there are a lot more cards such as for other countries and I'm only trying to store "Date and Country" into the database: enter image description here and the second half, is after adding to the database I want to render them on another page, and if the database is empty aka the user hasn't added any data to the database yet, i want the page to show "now data to display" but if the user did, i want to render what's in the database. enter image description here Here's what I've tried so far: models.py from django.db import models class CountryData(models.Model): country = models.CharField(max_length=100) date = models.DateTimeField() def __str__(self): return self.country views.py def all_countries(request): first_response = requests.get('https://api.covid19api.com/summary').json() results = len(first_response['Countries']) my_new_list = [] for i in range(0, results): my_new_list.append(first_response['Countries'][i]) # print(my_new_list) if request.method == "POST": if request.POST.get('country') and request.POST.get('date'): added_record = CountryData() … -
How to stick the second upload file button on the same place?
I have two upload buttons. But the second upload button jumps down after submit. So I have this html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ pdf_form.as_p }} </div> <div class="form-outline"> <div class="form-group"> <div class="wishlist"> <table class="paddingBetweenRows"> <tr> <th>fruit aantal </th> <th>&nbsp;&nbsp;&nbsp;fruit naam</th> <th>fruit kosten</th> <th>fruit totaal soort</th> <th>fruit totaal kosten</th> </tr> {% for value0, value1, value2, value3, value4 in content %} <tr> <td>{{ value0 }}</td> <td>{{ value1 }}</td> <td>{{ value2 }}</td> <td>{{ value3 }}</td> <td> <span {% if value4 in diff_set %} style="color: red;" {% endif %}> {{value4}}</span> </td> </span> </tr> {% endfor %} </table> </div> </div> </div> </div> </div> </span> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ excel_form.as_p }} </div> <div class="form-outline"> <div class="form-group"> <div class="wishlist"> <table class="paddingBetweenRows"> <tr> <th>fruit kosten totaal </th> </tr> {% for value0 in content_excel %} <tr> <td> <span {% if … -
How do I customize the input format accepted by Django auth's PasswordResetView?
I'm using Django 3.1 witih Python 3.9. I'm using Django's django.contrib.auth application to manage my users. I would like to setup a reset password for my users, using Django's "PasswordResetView", but am unsure how to customize it to suit submitting a JSON request. I have created this in my urls.py file path('reset_password/', views.ResetPasswordView.as_view(), name='password_reset'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), Defined this in my views.py file class ResetPasswordView(SuccessMessageMixin, PasswordResetView): template_name = 'users/password_reset.html' email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') and defined these in my settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtppro.zohopro.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = str(os.getenv('EMAIL_USER')) EMAIL_HOST_PASSWORD = str(os.getenv('EMAIL_PASSWORD')) However, when I submit a POST request to my endpoint with the data {"username": "myuser@example.com"} in which "myemail@example.com" is a registered user, I get back curl: (52) Empty reply from server The specific curl request looks like the below, for what it's worth … -
Django multiple SMTP accounts
Here are the Django simple SMTP backend settings for just 1 email account EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "mail.mysmtpserver.somewhere" EMAIL_PORT = 587 EMAIL_HOST_USER = "my@login" EMAIL_HOST_PASSWORD = "mypassword" EMAIL_USE_TLS = True How is it possible to use 2 or more email accounts on the same server instead of one? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "mail.mysmtpserver.somewhere" EMAIL_PORT =587 EMAIL_HOST_USER = "my@login2" EMAIL_HOST_PASSWORD = "mypassword2" EMAIL_USE_TLS = True I just need to send different emails based on the subject by different email account. I checked the Django documentation but there was nothing -
Returning celery task id to view
In my celery task, I want to calculate median of an array. My view: import myapp.tasks as tasks def my_view(request): data_arr = [[1,2], [3,4]] response = { 'median': tasks.median.delay(data_arr).id } return HttpResponse(json.dumps(response)) Here's the task file: from celery import shared_task import numpy @shared_task def median(arr): return numpy.mean(arr) When I call the view, I can get the following output: {"median": "88edea52-c60a-42a8-ad8d-799a4c7117a6"} The problem is celery outputs following error: File "/Users/tolgafiratoglu/Desktop/projects/python/nadir/process/tasks.py", line 7, in median return numpy.mean(arr).id AttributeError: 'numpy.float64' object has no attribute 'id' I understand the error, but I can't figure out how to proceed. -
put a word with white space as a variable in a sql query using .format()
I would like to know how to put a word with white space as a variable in a sql query (I use postgresql) data = "something with white space" choice = "DESC" limit = 10 def rDB(sql_request): with connection.cursor() as cursor: cursor.execute(sql_request) row = cursor.fetchall() return row queryWithFormat(data, choice, limit): return(''' SELECT col1, SUM(col2) as nb FROM Table WHERE col1 = {d} ORDER BY nb {c} LIMIT {l} '''.format(d=data, c=choice, l=limit) rDB(queryWithFormat(data, choice, limit)) django.db.utils.ProgrammingError: ERROR: syntax error on or near 'with' LINE 8: WHERE col1 = something with white ... -------------------------------^ -
how to get multiple input values in django loop (template) using javascript?
I am trying to get the value of some input field in my django template, the form is in a loop e.g {% for p in prediction %} {% endfor %}. I have this simple line to grab the id from the input field let odds = document.getElementById("odds").value Based on the fact that i have all these function in a django loop, am i not supposed to get all the odds when i console.log(odds) {% for p in prediction.prediction_data.all %} <form action="#" method="POST"> <input type="text" value="{{ p.odds }}" id="odds"> <input type="number" value="" name="amount" id="amount" onkeyup="CalculateNewBalance()"> <script> function CalculateNewBalance(){ let odds = document.getElementById("odds").value let stake_amount_input = document.getElementById("amount") console.log(odds); </script> </form> {% endfor %} [![enter image description here][1]][1] -
How to use both static files and media together
Is it possible to use both static files and media in a project? because all tutorials use only one of them. MEDIA_URL= 'media/' MEDIA_ROOT = BASE_DIR / 'media' STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static/' STATICFILES_DIRS = BASE_DIR / 'static/ I wrote this to setting. How am supposed to modify urls.py? urlpatterns = [ path('admin/', admin.site.urls), path('',include('pages.urls')), path('users/',include('users.urls')), path('users/',include('django.contrib.auth.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I wrote it this way but how should I add static urls? -
Twitter OAuth 2.0 Refresh Token Error - (invalid_request) Value passed for the token was invalid
I was running into this error while using Tweepy with OAuth 2.0 User Auth with PKCE when I tried to refresh the token via the User Handler. It was being returned when trying to call the non-production Tweepy refresh function on an expired token. -
Django channels + HTMX -> notification messages framework
I'd like to implement a notification framework for Django that uses channels/websockets and HTMX. But I don't get how to do that. Some things work, some are extremely complicated n my mind at least. Here's the code: from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from channels.layers import get_channel_layer from django.contrib import messages from django.template.loader import get_template from medux.common.models import User class NotificationConsumer(WebsocketConsumer): def connect(self): self.user = self.scope["user"] if not self.user.is_authenticated: self.close() return # create a group "user-<username>" async_to_sync(self.channel_layer.group_add)( f"user-{self.user.username}", self.channel_name, ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( f"user-{self.user.username}", self.channel_name, ) def notify(self, event: dict): html = get_template("common/toast.html").render( context={"message": event["message"]} ) self.send(text_data=html) <div hx-ext="ws" ws-connect="/ws/messages"> <div id="toasts" class="toast-container position-fixed bottom-0 end-0 p-3 pb-5"> {% for message in messages %} <div id="toasts" hx-swap-oob="beforeend"> <div data-toast-template class="toast align-items-center border-0 show" role="alert" aria-live="assertive" aria-atomic="true"> {# header here #} <div data-toast-body class="toast-body">{{ message }}</div> <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> </div> </div> {% endfor %} </div> </div> The client connects to the consumer, and if I write a small `self.send(text_data="foo") AFAIK, I have to send an "high level" event to the consumer with the type "notify", so the notify() method is called. So this would be a code called anywhere in a view …