Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
with regard to form.save(commit=False), what am I missing?
As explained in many posts like the following: Why do we use "form.save(commit=False)" in Django-views? "The main use case is if you have a ModelForm that doesn't contain all the required fields of a model. You need to save this form in the database, but because you didn't give it all the required fields, you will get an error.." which is all good and dandy but why not just complete all the instance fields and then call the regular save? In the bellow example: # Creates a Dog class with all fields as mandatory: class Dog(models.Model): name = models.CharField(max_length=50) race = models.CharField(max_length=50) age = models.PositiveIntegerField() # Creates a ModelForm with only name and age: class DogForm(forms.ModelForm): class Meta: model = Dog fields = ['name', 'age'] # In your view use this form: def dog_view(request): ... form = DogForm(request.POST or None) # If the form is valid we need to add a race, otherwise we will get an error: if form.is_valid(): dog = form.save(commit=False) # Define the race here: dog.race = 'Labrador retriever' # And then do the regular save to push the change in the database: dog.save() ... why not just say: form = DogForm(request.POST or None) # Define the … -
Intermittent Pooler Error in django app server
facing intermittent Pooler Error: server conn crashed? in my http server. Tried searching and fixing long running transaction in my system but didn't help. Also this happens very randomly at any point in time without any co-relation with traffic. Sharing error logs: 2025-01-31 11:41:07.067 1 LOG C-0x55d7847ac110: logs/server_application_api@127.0.0.1:34186 closing because: client close request (age=0) 2025-01-31 11:41:07.051 1 LOG C-0x55d7847ac110: logs/server_application_api@127.0.0.1:34186 login attempt: db=test user=server_application_api tls=no 2025-01-31 11:41:06.988 1 LOG C-0x55d7847ac110: logs/server_application_api@127.0.0.1:34096 closing because: client close request (age=0) 2025-01-31 11:41:06.968 1 LOG C-0x55d7847ae820: logs/server_application_api@127.0.0.1:34048 closing because: client close request (age=0) 2025-01-31 11:41:06.952 1 LOG C-0x55d7847ac110: logs/server_application_api@127.0.0.1:34096 login attempt: db=test user=server_application_api tls=no 2025-01-31 11:41:06.948 1 WARNING C-0x55d7847ac110: logs/server_application_api@127.0.0.1:40674 Pooler Error: server conn crashed? CloudWatch metrics -
Django import-export import foreign keys that do not exist
Being in a rush I'm having a hard time understanding the import concept. Where is the final board creation missing? i.e. Board(person=p, organization=p) Model class Person(BaseModel): organizations = models.ManyToManyField("Organization", blank=True, through="Board") class Organization(BaseModel): people = models.ManyToManyField("Person", blank=True, through="Board") class Board(BaseModel): person = models.ForeignKey(Person, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) Test from django.test import TestCase import tablib from import_export import resources class BoardResource(resources.ModelResource): def before_import_row(self, row, **kwargs): org_name_1 = row["organization"] o=Organization.objects.get_or_create(name_1=org_name_1, defaults={"name_1": org_name_1}) person_firstname = row["person"] p=Person.objects.get_or_create(firstname=person_firstname, defaults={"firstname": person_firstname}) class Meta: model = Board dataset = tablib.Dataset(['','john','acme'], headers=['id','person','organization']) class TestCase(TestCase): def test_basic_import(self): board_resource = BoardResource() result = board_resource.import_data(dataset, dry_run=False) print(result.totals) assert not result.has_errors() The documentation points to this thread though I'm unable to apply anything to my case -
Selenium: not working fine with the docker
I want to run the selenium chrome driver my django project with the docker configuration so i followed this: [https://hub.docker.com/r/selenium/standalone-chrome/][1] and I have created the celery task functionality is like this: def setup_driver(): try: chrome_options = Options() chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_argument("--start-maximized") chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36") driver = Remote( command_executor="http://selenium_grid:4444/wd/hub", # Use service name! options=chrome_options ) print("Successfully connected to Selenium Grid:", driver) return driver except Exception as e: print(f"Failed to connect to Selenium Grid: {e}") return None def view_fun(request): try: driver = setup_driver() time.sleep(2) logger.info(f"{driver} setup successful") except Exception as e: print(f"An error occurred: {e}") finally: driver.quit() So the error is like this: celery_worker-1 | [2025-01-31 11:50:17,605: WARNING/ForkPoolWorker-4] Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NameResolutionError("<urllib3.connection.HTTPConnection object at 0x7f08d1d0d7f0>: Failed to resolve 'selenium_grid' ([Errno -2] Name or service not known)")': /wd/hub/session celery_worker-1 | [2025-01-31 11:50:29,547: WARNING/ForkPoolWorker-4] Loading login page... celery_worker-1 | [2025-01-31 11:50:29,547: WARNING/ForkPoolWorker-4] Login failed: 'NoneType' object has no attribute 'get' celery_worker-1 | [2025-01-31 11:50:29,548: ERROR/ForkPoolWorker-4] scrape.tasks.run_weekly_scraping_zip[ebf4199d-61d4-4a3c-85ab-c64e228f3e2b]: Error in weekly scrape: 'NoneType' object has no attribute 'quit' celery_worker-1 | File "/app/scrape/utils.py", line 256, in scrape_ziprecruiter_jobs celery_worker-1 | driver.quit() celery_worker-1 | AttributeError: 'NoneType' object has no attribute 'quit' Also … -
Django customize validation error message
I have a following serializer definitions that validate request payload: # diagnosis serializer class ICD10Serializer(serializers.Serializer): icd_10 = serializers.IntegerField(required=True, allow_null=False) class DetailsSerializer(serializers.Serializer): diagnosis_details = ICD10Serializer(many=True) class ChartUpdateSerializer(serializers.Serializer): diagnosis = DetailsSerializer(many=True) Its usage: payload = ChartUpdateSerializer(data=request.data) if not payload.is_valid(): raise serializers.ValidationError(payload.errors) This throws validation error message in the following format: { "diagnosis": [ { "diagnosisDetails": [ {}, <- valid {}, <- valid {}, <- valid {}, <- valid { "icd10": [ "This field may not be null." ] } ] } ] } Here {} is also shown for valid ones. Can we simply raise validation error for invalid ones? Or better even if we can know which field and the message so custom message can be generated. -
Information on using Twilio with Whatsapp
I am making an app with Django and react about a clinic. My clients want to send automatically the appointment through WhatsApp to their patients. I have been reviewing the Twilio documentation, as I understand, I need that the phone number I use to send the WhatsApp must be WhatsApp Business. Can anyone help me on how to perform this function? I have never used Twilio, and I am very lost, I also don't understand how I am going to be able to test that it works correctly before launching it. Thanks in advance for the help. -
Firebase API is not sending notification in background
I'm creating web app using Django, and trying to send push notification via firebase API. It's working when user is on page that registers firebase-messaging-sw.js, but in background no notification is coming, even though no error was raised. def send_fcm_notification(device_token, title, body, data=None, click_action=None): headers = { "Authorization": f"Bearer {get_access_token()}", "Content-Type": "application/json", } data = { "message": { "token": device_token, # Use "topic": "your-topic" to send to a topic "notification": { "title": title, "body": body, }, "data": data or {}, "android": { "priority": "high" }, "apns": { "payload": { "aps": { "alert": { "title": title, "body": body } } } } } } response = requests.post(FCM_ENDPOINT, headers=headers, data=json.dumps(data)) return response.json() SW importScripts("https://www.gstatic.com/firebasejs/11.2.0/firebase-app-compat.js"); importScripts("https://www.gstatic.com/firebasejs/11.2.0/firebase-messaging-compat.js"); // Firebase Configuration (Same as in your main script) const firebaseConfig = { //myconfig data }; // Initialize Firebase firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); self.addEventListener('notificationclick', (event) => { event.notification.close(); // CLosing the notification when clicked const urlToOpen = event?.notification?.data?.url || 'https://www.test.com/'; // Open the URL in the default browser. event.waitUntil( clients.matchAll({ type: 'window', }) .then((windowClients) => { // Check if there is already a window/tab open with the target URL for (const client of windowClients) { if (client.url === urlToOpen && 'focus' in client) { return client.focus(); … -
I am attempting to use Django Ninja for the first time and running into a strange error
I cant quite understand error I am receiving. I am simply trying to setup a model schema for my model. I am an old Django hand but ninja is new for me. What am I doing wrong here? Would love some help and feedback. My model is this class Program(models.Model): mentor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField() start_date = models.DateField() end_date = models.DateField() attendees = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="attendees") participants = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="participants") created_on = models.DateTimeField(auto_now_add = True) updated_on = models.DateTimeField(auto_now = True) My api.py has the following definition class MentorOutSchema(Schema): class Config: model = Program model_fields = [ "mentor", "description", "start_date", "end_date", "attendees", "participants", ] My endpoint is this @router.get('/programs') async def mentor_programs(request, response=list[MentorOutSchema]): return Program.objects.filter(mentor=request.user) When I start the server, I get the following error @router.get('/programs') ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/router.py", line 268, in decorator self.add_api_operation( File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/router.py", line 319, in add_api_operation path_view.add_operation( File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/operation.py", line 426, in add_operation operation = OperationClass( ^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/operation.py", line 331, in __init__ super().__init__(*args, **kwargs) File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/operation.py", line 82, in __init__ self.signature = ViewSignature(self.path, self.view_func) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/signature/details.py", line 87, in __init__ self.models: TModels = self._create_models() ^^^^^^^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/signature/details.py", line 171, in _create_models model_cls = type(cls_name, (base_cls,), attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/pydantic/_internal/_model_construction.py", line 219, in __new__ set_model_fields(cls, … -
Django Redirect followed by database lookup
I have an authenticated user that is signed into a webpage Page1.html on this page I want to create redirect the user to another page that matches a particular property that the user has in their user role. I managed to get the part working that redirects the user to that webpage, but I know I am going to be faced with having many users so it will take a while for searching each user that is why I want the second redirect to occur on the second html page. My thoughts are that I use the manipulation of the post to the redirect of the first page Page1.html, and have Page1.html have a please wait till redirected to the final page that they will be using. I was reading this question but it did not really answer my question: Django - show loading message during long processing -
Can't install R in Heroku deployment
I'm trying to install the R buildpack for rpy2 for my website built with Django and React, but I keep getting an error on deployment and I have no clue what's going on. I've checked my buildpacks a billion times to make sure it is in the order of Apt, Python, and R, and I have Aptfiles, init.R, and runtime.txt in my root directory. This is the error message. Help very much appreciated! Collecting rpy2~=3.5.16 (from -r requirements.txt (line 15)) remote: Downloading rpy2-3.5.17.tar.gz (220 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'error' remote: error: subprocess-exited-with-error remote: remote: × Getting requirements to build wheel did not run successfully. remote: │ exit code: 1 remote: ╰─> [34 lines of output] remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> remote: main() remote: File "/app/.heroku/python/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main remote: json_out['return_val'] = hook(**hook_input['kwargs']) remote: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ remote: File "/app/.heroku/python/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel remote: return hook(config_settings) remote: ^^^^^^^^^^^^^^^^^^^^^ remote: File "/tmp/pip-build-env-jhoy88xq/overlay/lib/python3.12/site-packages/setuptools/build_meta.py", line 334, in get_requires_for_build_wheel remote: return self._get_build_requires(config_settings, requirements=[]) remote: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ remote: File "/tmp/pip-build-env-jhoy88xq/overlay/lib/python3.12/site-packages/setuptools/build_meta.py", line 304, in … -
Writing Django Func() Expression with multiple parameters and specify the order
I'm using Func() Expressions to use this answer and compute the difference between two dates in business days: class BusinessDaysBetween(Func): """Implementation of a Postgres function to compute the working holidays between two fields.""" template = """ (SELECT COUNT(*) FROM generate_series(%(expressions)s, interval '1 day') s(day) WHERE EXTRACT(DOW FROM s.day) NOT IN (0, 6)) """ arity = 2 output_field = IntegerField() However, I am having problems with the formatting of Date and DateTime. So I want to call the functions mentioned in this answer. My edited code looked like this: class BusinessDaysBetween(Func): """Implementation of a Postgres function to compute the working holidays between two fields.""" template = """ ( SELECT COUNT(*) FROM generate_series( TO_CHAR(CAST(%(expressions)s AS DATE), 'YYYY-MM-DD'), TO_CHAR(CAST(%(expressions)s[1] AS DATE), 'YYYY-MM-DD'), interval '1 day' ) s(day) WHERE EXTRACT(DOW FROM s.day) NOT IN (0, 6) ) """ arity = 2 output_field = IntegerField() The problem is that I am putting both parameters in the first place, I don't know how to specify the order of the parameters in which they will appear. I already tried: With {0} and {1} and it says there is a syntax error. %(expressions)s and %(expressions)s[1] and nothing. With %s, it's raising the "not enough arguments for format string" … -
wrong password when social authentication in allauth
I have been struggling with this for days, I'm a beginner and I don't know how to implement social authentication (authentication by providers) neither in allauth nor in headless-allauth libraries, I have implemented a sign in with providers in reguler allauth, my settings.py SOCIALACCOUNT_PROVIDERS= { 'google': { 'SCOPE': [ 'profile', 'email' ], 'AUTH_PARAMS': {'access_type': 'online'}, 'APP': { 'client_id': '247133284916-r5pu7h3bnee0vbrbem7nhph5ffhkk5ob.apps.googleusercontent.com', 'secret': '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', 'key': '' } }, 'github' : { 'SCOPE': [ 'user' ], 'APP': { 'client_id': 'Ov23liT9Y3rQjzd25rZN', 'secret': '02f816d85ec879da6ddec85d2d169a019fa1084b', 'key': '' } }, 'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'} } html <a class="social-login Google-login" href="{% provider_login_url 'google' %}"> <span class="G-logo"></span> <span>Log in with Google</span> </a> when I try to sign up with a provider (google for instance) I am signed in and everything is ok, but when I try to reauthenticated in headless-allauth library by entering the password (I am using both) or I try to sign out then sign in by entering the email and password, I always keep getting (the password you specified is not correct.) when I am sure of my google account … -
Why am I unable to query the date from my database in django?
My database does have an item in the collection I want to query, and it returns the price correctly. from django.db import models # Create your models here. class Dollar_price(models.Model): price = models.FloatField() date = models.DateTimeField() def __str__(self): print(self.date) return str("success") The problem is that when I try printing self.date it says it's None. I don't know why this happens, nor how can I solve this. -
Do not monitor changes for field in django-simple-history
I am trying to monitor and display historical changes of my model. Problem is that every time user logins it saves it to historical model. I have tried to exclude this field like shown bellow, but it just saves new instance without field last_login. Model: class CustomUser(AbstractBaseUser, PermissionsMixin): ... history = HistoricalRecords(excluded_fields=['last_login']) View: def user_history(request, pk): user = get_object_or_404(CustomUser, pk=pk) history_records = user.history.all().order_by("-history_date") table = UserHistoryTable(history_records) return render(request, "history.html", { "name": user.username, "instance": user, "table": table, }) Table: class UserHistoryTable(tables.Table): history_date = tables.DateTimeColumn(verbose_name="Date", format="d.m.Y H:i") history_user = tables.Column(verbose_name="Modified By") history_type = tables.Column(verbose_name="Change Type", accessor="get_history_type_display") changes = tables.Column(empty_values=(), verbose_name="Changes") class Meta: model = CustomUser.history.model attrs = {"class": "table table-striped table-hover table-bordered shadow-sm"} template_name = "django_tables2/bootstrap4.html" fields = ("history_date", "history_user", "history_type") def render_changes(self, record): if record.prev_record: changes = [] for field in record.instance._meta.fields: field_name = field.name old_value = getattr(record.prev_record, field_name, None) new_value = getattr(record, field_name, None) if field_name == "password" and old_value != new_value: changes.append(f"<strong>{field.verbose_name}:</strong> {'*' * 7} → {'*' * 7}") elif old_value != new_value: changes.append(f"<strong>{field.verbose_name}:</strong> {old_value} → {new_value}") if changes: return format_html("<br>".join(changes)) else: return "No changes" return "No previous record" I need to display table with changes without empty entries My current solution was to filter table in view, but … -
django managers vs proxy models
I'm currently getting into proxy models and I actually cannot understand when we should give them respect. For me they look very similar to managers Is there some differences or we can implement the same things using proxy models and managers? -
How to update large amount of records in chunks?
I have models: class Partner(models.Model): sap_code = models.CharField(max_length=64, null=True, blank=True, verbose_name='sap id', default=uuid4) # another fields class DeficienciesAct(models.Model): partner = models.ForeignKey('partners.Partner', null=True, on_delete=models.CASCADE) sap_code = models.CharField(max_length=64, null=True) # another fields Data: Partner: id sap_code 1 123 2 124 ... ... DeficienciesAct: id partner_id sap_code 1 null 123 2 null 333 ... ... ... 500000 null 421 Let's imagine that in DeficienciesAct there are 500 000 records. Not all DeficienciesAct.sap_code can be in Partner.sap_code. So I need to update field DeficienciesAct.partner_id by DeficienciesAct.sap_code. DeficienciesAct.sap_code is equal to Partner.sap_code. For that I developed a script: DeficienciesAct.objects.filter( partner__isnull=True, sap_code__in=Subquery(Partner.objects.values_list("sap_code")) ).annotate( new_partner_id=Subquery( Partner.objects.filter( sap_code=OuterRef('sap_code') ).values('id')[:1] ) ).update(partner_id=F("new_partner_id")) Well that works. But I'm afraid that huge amount of records can affect a database (postgres). Is there any way to do the task in chunks? -
Why is bootstrap able to load the backdrop for one modal but not the other
so here's my issue im building a django project based off of tutorials ect and I found for user feedback modals to be a good idea. I didn't want to create a lot of different code pieces for modals so i decided to opt for a generic modal that i can use for all my cases. <div class="modal fade" id="{{ modal_id }}" tabindex="-1" role="dialog" aria-labelledby="{{ modal_id }}Label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="{{ modal_id }}Label">{{ title }}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <!-- Dynamic message --> <p id="modalMessage">{{ message }}</p> <!-- Conditional content based on context_type --> {% if context_type == "account_deletion" %} <form method="POST" action="{{ action_url }}"> {% csrf_token %} <div class="form-group"> <label for="password" style="margin-bottom:1rem;">Enter Your Password to Confirm:</label> <input type="password" id="password" name="password" class="form-control" required style="margin-bottom: 1rem;"> </div> <button type="submit" class="btn btn-danger">Delete Account</button> </form> {% elif context_type == "item_deletion" %} <p>Are you sure you want to delete this item?</p> {% endif %} </div> <div class="modal-footer"> {% if context_type == "item_deletion" %} <form method="POST" action="{{ action_url }}"> {% csrf_token %} <button type="submit" class="btn {{ submit_class }}">{{ submit_label }}</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> </form> {% endif %} </div> </div> </div> </div> in … -
Custom ASGI worker metrics with OpenTelemetry
Is it possible to create custom open telemetry metrics to calculate the average time a request stays queued in ASGI before execution and also the average queue size per worker? Or if it is not possible by worker just in general in the ASGI server. I tried searching on the internet but I didn't found any example of this use case. ChatGPT suugested me to create a middleware and do it like this: import time from starlette.middleware.base import BaseHTTPMiddleware from opentelemetry import metrics # Create a Meter meter = metrics.get_meter_provider().get_meter("asgi.queue") # Define a histogram for queue time queue_time_histogram = meter.create_histogram( name="asgi.queue_time", description="Time requests spend in the ASGI queue", unit="ms", ) class QueueTimeMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): request.state.queue_start_time = time.perf_counter() # Request received response = await call_next(request) queue_time = time.perf_counter() - request.state.queue_start_time queue_time_histogram.record(queue_time * 1000) # Convert to milliseconds return response However I am little suspicious about this snippet and don't know if this is exactly what we want. Does anyone have any advice on this case? -
django tag split failed
i want split whether "," or ";" so i setted, but it is not working well.. for example, when i input tags by text python, django; sky Hi, i want split whether "," or ";" so i setted, but it is not working well.. for example, when i input tags by text python, django; sky like this but result is from blog.models import Post ...: post = Post.objects.last() ...: print(post.tags.all()) # 태그 개별 저장 확인 <QuerySet [<Tag: python; django; sky tag>]> how can i fix it? i will give to you my part of models.py, views.py # models.py from django.db import models from django.contrib.auth.models import User import os class Tag(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=200, unique=True, allow_unicode=True) def __str__(self): return self.name def get_absolute_url(self): return f"/blog/tag/{self.slug}/" class Post(models.Model): title = models.CharField(max_length=30) # 후킹해주는 메세지 100글자 한도로 노출 hook_text = models.CharField(max_length=100, blank=True) content = models.TextField() # auto_now=True를 해주면, 추가로 입력해줄 것 없이, 해당되는 내용이 자동 등록 된다. # settings에 MEDIA_URL, MEDIA_ROOT로 넣어주었던 주소 뒤로 어떻게 해줄지를 말해준다. head_image = models.ImageField(upload_to="blog/images/%Y/%m/%d/", blank=True) file_upload = models.FileField(upload_to="blog/files/%Y/%m/%d/", blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # CASCADE는 연결되어있는 값도 같이 삭제 해준다는 뜻 # SET_NULL은 해당 값을 삭제해도, 해당 pk 값은 공백으로 두되, 나머지 데이터는 … -
Django-CKEditor5 Source Editing Feature Doesn't Work
I am using Django CKEditor5 in my admin panel. When I'm trying to insert a html code using "Source Edit" feature, it doesn't apply any style and transforms automatically after clicking "Source" button again into this: I already tried the GeneralHtmlSupport from documentation: https://ckeditor.com/docs/ckeditor5/latest/features/html/general-html-support.html My ckeditor config looks like this ClassicEditor.create( editorEl, config, { plugins: [GeneralHtmlSupport, SourceEditing, Undo, Alignment, Image, ImageResizeEditing, ImageResizeHandles], htmlSupport: { allow: [ { name: /.*/, attributes: true, classes: true, styles: true } ] }, image: { resizeUnit: "%", styles: { options: [ { name: 'Resize', title: 'Resize', className: 'Resize' }, ] }, }, htmlSupport: true, allowedContent: true } ).then(editor => { const textarea = document.querySelector(`#${editorEl.id}`); editor.model.document.on('change:data', () => { textarea.value = editor.getData(); }); if (editor.plugins.has('WordCount')) { const wordCountPlugin = editor.plugins.get('WordCount'); const wordCountWrapper = element.querySelector(`#${script_id}-word-count`); wordCountWrapper.innerHTML = ''; wordCountWrapper.appendChild(wordCountPlugin.wordCountContainer); } editors[editorEl.id] = editor; if (callbacks[editorEl.id]) { callbacks[editorEl.id](editor); } }).catch(error => { console.error((error)); }); editorEl.setAttribute('data-processed', '1'); }); window.editors = editors; -
Django: How to natural sort a QuerySet with Postgres and SQLite
I have the following model: from django.db import models class VersionInfo(models.Model): version = models.CharField("Version", max_length=16) # 3-digit version like "1.2.3". I have to natural sort the QuerySet by the 3 parts of "version" when rendering a django_tables2 table. I already tried things like this, but it doesn't sort like expected: from django.db.models import Func, IntegerField, Value from django.db.models.functions import Cast class SplitPart(Func): function = 'SUBSTR' template = "%(function)s(%(expressions)s)" def get_queryset(self): qs = super().get_queryset() qs = qs.annotate( major=Cast(SplitPart('version', 1, Func('version', Value('.'), function='INSTR') - 1), IntegerField()), minor=Cast( SplitPart( 'version', Func('version', Value('.'), function='INSTR') + 1, Func(SplitPart('version', Func('version', Value('.'), function='INSTR') + 1), Value('.'), function='INSTR') - 1, ), IntegerField(), ), patch=Cast( SplitPart( 'version', Func(SplitPart('version', Func('version', Value('.'), function='INSTR') + 1), Value('.'), function='INSTR') + Func('version', Value('.'), function='INSTR') + 1, ), IntegerField(), ), ).order_by('major', 'minor', 'patch') return qs Yes, it's very ugly, but should work in SQLite and Postgres (SQLite has no STRING_TO_ARRAY function), but it doesn't. Does anybody have an idea? May be there's a library providing this functionality? Thanks. -
Django + React: Can't get access to an endpoint
I have an endpoint that I made using djangorestframework. The view has a dispatch method for retrieving data from the request and sending it to post method. Endpoint: class Profile(APIView): permission_classes = [IsAuthenticated] data = None def dispatch(self, request, *args, **kwargs): if request.content_type == 'application/json': try: self.data = json.loads(request.body) except json.JSONDecodeError: return super().dispatch(request, *args, **kwargs) else: return super().dispatch(request, *args, **kwargs) I tested this endpoint with 'Authorization': 'Bearer ${token}' header using postman and rest file, and I am getting the data back with status 200. But when I do the same thing in React using axios.post method, the same user is unauthorized. Axios.post: useEffect(() => { axios.post('http://127.0.0.1:8000/user/profile/', { headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, body: { "username": "Caution1", "password": "Caution123" } }).then(response => {setData(response.data); console.log(data);}); }, []); I have CORS_ALLOW_ALL_ORIGINS and CORS_ALLOW_CREDENTIALS both to True. -
Django can't display html box of authentifiation
I have the problem that the google auth is not working properly. When I try access the site, then I get the error <a href="{% provider_login_url 'google' %}?next=/">Login with google</a> from this file <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Django Google signin</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> </head> <body> {% load socialaccount %} <h2>Google Login</h2> <a href="{% provider_login_url 'google' %}?next=/">Login with google</a> </body> </html> I tried to change in the settings the SITE_ID from 1 to 2 which doesn't solve the error. That's my settings.py """ Django settings for transcendence project. Generated by 'django-admin startproject' using Django 5.1.5. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ from pathlib import Path # 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/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-$$gm@ghswh(&c&$kq6oj-3rxf(2+5-zg$jwo0=&49pzgdi7@u2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition SITE_ID=1 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'auth_system', "django.contrib.sites", 'allauth', 'allauth.account', … -
What is meant with validation for django imagefield?
The ImageField docu states: Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. Yet any string is accepted class Foo(Model): pic = models.ImageField(upload_to='files') e.g. I can save this without error and nothing is uploaded to files (not even with a correct file) fooinstance.pic="bogus" fooinstance.save() fooinstance.pic.__dict__ {'_file': None, 'name': 'bogus', 'instance': <Foo:...>, 'field': <django.db.models.fields.files.ImageField: pic>, 'storage': <django.core.files.storage.filesystem.FileSystemStorage at 0x721add4903d0>, '_committed': True} Meanwhile the FileField works/uploads perfectly fine -
Securly passing authorization token from template to static javascript in Django
I am adding a custom admin page to the Django admin site where the logged in user can open a text file, it is then parsed, and the parsed data is added as a new record in a table using the user's assigned token. Is the below method secure? Is there a better strategy? I've added a custom template: {% extends "admin/change_form.html" %} {% load static %} {% block extrahead %} {{ block.super }} <script type="application/javascript" src="{% static 'js/add_cal_file.js' %}"></script> {% endblock extrahead %} {% block content %} <h1>Add cal file</h1> <div class="mb-3"> <input class="form-control" type="file" id="formFile" accept=".cal" token="{{ request.user.auth_token }}"> </div> {% endblock %} When the user selects a file the following parser in static 'js/add_cal_file.js is called: const parseCal = async (fileContents, token) => { // parses fileContents to postRequest here const response = await fetch("/api/add-calibration", { method: 'POST', headers: {"Content-Type": "application/json", "Authorization": "Token "+token }, body: JSON.stringify(postRequest) }) } The view at /api/add-calibration is protected using @permission_classes([IsAuthenticated]) limiting it to only requests that provide an authorization token