Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django: Unit Test Fixtures not loading in VSCode Debug Mode
I have written some unit tests with Django, with fixtures set up. I want to debug these tests and have a configuration on VSCode to do this... { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Django: Test Unit Case", "type": "debugpy", "request": "launch", "args": [ "test", "apps.students", "-v 2" ], "django": true, "autoStartBrowser": false, "program": "${workspaceFolder}\\server\\manage.py" }, ... ] } I have my FIXTURE_DIR configured correctly, as when I run the command py manage.py test apps.students, the fixtures load and give no error. However, when I try to run and debug, I get the following error... Found 6 test(s). Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')... Operations to perform: Synchronize unmigrated apps: corsheaders, django_extensions, messages, rest_framework, staticfiles Apply all migrations: admin, auth, ballots, contenttypes, election_count_strategies, polls, programme_groupings, programmes, sessions, students, token_blacklist, users, year_groups Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK ... System check identified no issues (0 silenced). setUpClass (apps.students.tests.YearRepresentiveTestCase) ... ERROR ====================================================================== ERROR: setUpClass (apps.students.tests.YearRepresentiveTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\fiona\AppData\Roaming\Python\Python312\site-packages\django\test\testcases.py", line 1389, … -
Why does django override css variable name from db?
I'm taking over a django+react project from a guy who left the company, but this is the first time I work with django so I'm somewhat clueless. The project is a status management page with calendar and stuff (sqlite3 as db). Possible statuses (like In Office, or Sick Leave) and their corresponding data is stored in db, including color for the status. The color was previously stored as a css hex string without the # (got prepended later by code). But the color values are used at multiple places, so they were copy-pasted many times. Since the colors might change, I wanted to get them all together, so I created css variables like '--in-office-color: rgb(whatever)', and changed db to contain the strings 'var(--in-office-color)' and so instead. Now when I want to return it in a view like this: class SomeView(APIView): def get(self, request): //... data = { /* other profile data here */ "statuses": {i.id: {"name":i.name, "color": i.color} for i in Statuses.objects.all()} } return Response(data) Then in the response some css variables are ok, and some got changed. The two problematic ones are "--in-office-color" which changes to "--in.office-color" and "--home-office-color" also changed to "--home.office-color" (whilst "--out-of-office-color" remains unchanged for example) … -
django category count, print can't filtered
i want to solve django category problem i want print out, counting as category data. for example python (3) html (2) but result python ({{ category.post_set.count }}) html ({{ category.post_set.count }}) how can i solve? i will send my codes # models.py from django.db import models from django.contrib.auth.models import User import os class Category(models.Model): name = models.CharField(max_length=50, unique=True) 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/category/{self.slug}/" # admin 단에서의 이름을 설정 class Meta: verbose_name_plural = "categories" 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 값은 공백으로 두되, 나머지 데이터는 살려두는 것 # blank=True를 해줘야 카테고리 미 추가시 오류가 뜨지 않는다. author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL) tags = models.ManyToManyField(Tag, blank=True) # 이걸로써, 관리자 단에서 내용을 보게 되면 작성된 텍스트로 표시된다. def __str__(self): return f"[{self.pk}]{self.title} :: {self.author}" def get_absolute_url(self): return … -
Better Web service framework [closed]
Which is the better framework between Django or Spring Boot in doing API calls especially where we require to convert SOAP request to JSON requests and vice versa. -
Hello sir, I am learning Django. The server was working fine till now but when I created the index.html file in the template, I am facing problem
My django server is not working properly. When I load my website it shows nothing. How can I fix this problem, I checked all my setting and views.py, and urls.py all are ok but when I save all these my server loads but when I go to the website and paste the url.. it shows nothing. I try all the things to fix this error but nothing happens. -
Forbidden (403) CSRF verification failed. Request aborted. while logging in in Label Studio
Once labelstudio is updated to version and run from commandline: LABEL_STUDIO_DISABLE_SIGNUP_WITHOUT_LINK=true CRYPTOGRAPHY_OPENSSL_NO_LEGACY=1 HOST='https://...' nohup label-studio -b --data-dir /label-studio/data/ -db /label-studio/db.sqlite --log-level INFO --internal-host localhost -p 8080 --host https://... --agree-fix-sqlite > label-studio.out 2> label-studio.err & On login attempt it results in an issue: Forbidden (403) CSRF verification failed. Request aborted. The setup is Python 3.11.11 with the following relevant modules: label-studio==1.15.0 label-studio-converter==0.0.59 label-studio-sdk==1.0.8 label-studio-tools==0.0.4 -
What is pytests equivalent to setUpTestData in Django?
I have seen TestCase.setUpTestData which improves test speed quite a bit in my case. I typically prefer pytest fixtures instead of the TestCase classes. However,when I make a session-scope fixture which does data preparation needed for all tests with the fixture, I get RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I followed https://stackoverflow.com/a/72261942/29412366, but that had no effect. How can I store and re-use a DB state within a Django application when testing using pytest? I use an in-memory sqlite3 DB. I tried https://stackoverflow.com/a/72261942/29412366 : @pytest.mark.django_db @pytest.fixture(scope='session') def thing(django_db_setup, django_db_blocker): del django_db_setup # Cannot be used with usefixtures(..) it won't work with django_db_blocker.unblock(): print('sleeping') Thing.objects.create(thing='hello') and expected the test to run successfully + save time. Instead, I got the RuntimeError mentioned above. (function-scoped fixtures work fine, but then I don't save any test execution time) -
Django NFC Writing Issue on Production - HID Omnikey 5422 - "Service not available" Error
I am developing a Django web application to write to an NFC card using the HID Omnikey 5422 reader. Everything works fine on localhost, but when I deploy it to the production server, I get the following error: Console Error: jquery.min.js:2 POST https://demo.infoidz.com/portal/write-to-nfc/ 500 (Internal Server Error) Django Server Error: Error writing link to NFC card: Failed to establish context: Service not available. (0x8010001D)