Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fail to load resource: the server responded with a status of 404. in the STATICFILES_DIRS setting does not exist
I'm trying to put image on my website with Django. But it always give an error 404, Tried many things, but it still be the problem. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] STATIC_URL = '/static/' {% load static %} <!DOCTYPE html> <html> <img src="{% static 'media/logo2.jpeg' %}" alt="photo" height="100" width="500"> <p>HEllo world</p> {% block content %} replace me {% endblock %} </html> Wanna to have image on the website! -
Celery crashing error: redis.exceptions.ResponseError: UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?)
I am using celery in my django project to run some tasks in async. But the celery on server is crashing repeatedly. Error message: Mar 20 10:47:51 QA celery[663]: chan.handlers[type]() Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/kombu/transport/redis.py", line 896, in _brpop_read Mar 20 10:47:51 QA celery[663]: dest__item = self.client.parse_response(self.client.connection, Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/redis/client.py", line 1192, in parse_response Mar 20 10:47:51 QA celery[663]: response = connection.read_response() Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/redis/connection.py", line 829, in read_response Mar 20 10:47:51 QA celery[663]: raise response Mar 20 10:47:51 QA celery[663]: redis.exceptions.ResponseError: UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?) Mar 20 10:47:51 QA systemd[1]: celery.service: Deactivated successfully. Mar 20 10:47:51 QA systemd[1]: celery.service: Consumed 2.439s CPU time. Can anyone help? Is there any was to prevent this error. -
Pytest-django does not seem to create a new database for each test
When I run a test that needs the database, it seems to use the existing database (when I change a database entry, the test error contains the changed database entry). But I expect that pytest-django creates a new database for each test (if not specified differently). When debugging it calls the custom django_db_setup and the pytest django_db_setup fixture. It also outputs in the log statement: "Running migrations: Applying ..." but the test fails when I manipulate the data in the existing database. Could it be that the problem is there because we use an in memory Sqlite database? Or do I need some other setting? Or is this a bug? Test: def test_should_show_the_city_name_in_city_select_dropdown(page: Page, django_db_setup): page.goto("/") city_select_button = page.get_by_text("Stadt auswählen") city_select_button.click() assert "Beispielstadt" in page.get_by_role("listitem").all_inner_texts() conftest.py import os import pytest from django.core.management import call_command from config.settings.base import BASE_DIR os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" @pytest.fixture(scope="session") def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command( "loaddata", os.path.join(BASE_DIR, "e2e_tests", "database", "test_database.json"), ) pyproject.toml [tool.poetry.dependencies] python = "^3.10" django = "^4.1.6" [tool.poetry.group.dev.dependencies] pytest = "^7.2.1" pytest-playwright = "^0.3.0" pytest-base-url = "^2.0.0" pytest-django = "^4.5.2" [tool.pytest.ini_options] base_url = "http://localhost" DJANGO_SETTINGS_MODULE = "config.settings.local-container" database settings DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": Path("/") / "db" / "db.sqlite3", } } -
Django UpdateView not working showing slug error
I'm having issues with my creating an update view to update aspects of a model. Below is the code urls from django.urls import path, include from . import views urlpatterns = [ path('', views.Tenant_selector.as_view(), name='Tenant_selector'), path('<slug:slug>/dashboard', views.Dashboard.as_view(), name='Dashboard'), path('<slug:slug>/updateTenant', views.EditTenant_View.as_view(), name='UpdateTenant'), path('createTenant', views.CreateTenant_View.as_view(), name='CreateTenant'), path('<slug:slug>/sync', views.sync_view.as_view(), name='Sync'), path('success', views.Success.as_view()), path('<slug:slug>/loading', views.sync_loading.as_view(), name='Loading'), path('createTenant', views.CreateTenant_View.as_view(), name='CreateTenant'), ] views from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView, UpdateView from django.views.generic import TemplateView, DetailView, ListView from account.forms import CreateTenant, EditTenant from account.models import Tenant, staff_sync_model, student_sync_model from main.forms import RegisterForm, EditUser from main.models import NewUser from django.http import HttpResponse from datetime import date from . import Sync class Dashboard(TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.data = Tenant.objects.get(slug=self.request.path.split("/")[2]) context['total'] = self.data.staff.count() + self.data.student.count() context['staff'] = self.data.staff.count() context['student'] = self.data.student.count() context['slug'] = self.request.path.split("/")[2] return context class CreateTenant_View(CreateView): model = Tenant form_class = CreateTenant template_name='CreateTenant.html' success_url='/account/success' def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return redirect('/account/success') class EditTenant_View(UpdateView): model = Tenant form_class = EditTenant template_name='UpdateTenant.html' success_url='/account/success' def form_valid(self, form): form.save return redirect('/account/success') class Success(TemplateView): template_name='success.html' class Tenant_selector(ListView): model = Tenant template_name = 'Tenant_selector.html' def get(self, request, *args, **kwargs): if self.request.user.is_authenticated: data = self.request.user.tenant_set.all() if len(data) … -
Cannot parse data into {% include %} tag - Django
i have forum.html template inside templates/forum directory <div style="height:50px; width:100%">welcome to forum {{ obj.forum_name }}</div> i want to include this template into my topic.html template which is inside same directory. and i want to pass data using with {% include 'forum/forum.html' with obj.forum_name="windmaker" %} However it does not work as expected. It gives me "with" in 'include' tag needs at least one keyword argument. error. What can i do? As far as i understood the problem arise from dot(.) operator. I tried not to using it and suddenly it renders the page correctly here i get rid of .forum_name inside forum.html <div style="height:50px; width:100%">welco to forum {{ obj }}</div> and here i passed data inside topic.html {% include 'forum/forum.html' with obj="windmaker" %} and suddenly it works! -
from django.contrib.auth.models import User error in class Meta:
I'm having a problem to create a User inside class Meta I saw some things related to the same problem but could not solve with the solutions they gave. Here the problem: enter image description here I had this same problem in models.py but looking a little on the internet I could find how to fix and had to import the settings and create the user with this AUTH_USER_MODEL enter image description here I tried to do the same thing on the form but I got these two errors. enter image description here enter image description here And when trying to put only the settings.AUTH_USER_MODEL I can not put the server to run because it gives me this error in the Meta class and when I replace for example an empty string it runs normally but then I will not be creating the user. enter image description here enter image description here -
How do i limit choices for a field in a django model with respect to the data in previous field using foreignkey and limit_choices_to attribute?
class Property(models.Model): property_name = models.CharField(max_length=100) unit_name = models.CharField(max_length=100) class Tenant(models.Model): tenant_name = models.CharField(max_length=100) rent_unit = models.ForeignKey(Property, on_delete=models.SET_NULL) class Payment(models.Model): payment_name = models.ForeignKey(Tenant, on_delete=models.SET_NULL) payment_property = models.ForeignKey(Property, on_delete=models.SET_NULL, limit_choices_to={ 'pk__in': Property.objects.filter(unit_name=models.OuterRef('payment_name__rent_unit__unit_name')) }) I'am trying to limit the choices for the payment_property field in the Payment model based on the selected rent_unit in the Tenant model using Django's ForeignKey.limit_choices_to attribute with a subquery. But am getting this error when trying to execute makemigrations. ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. i was expecting to get a single choice for payment_property whenever i create a new Payment object and select a Tenant object, the available choices for the payment_property field should be limited to Property objects that have the same unit_name as the rent_unit of the selected Tenant object. -
I have got error when ı add trying to add column in my sqlite database in django
ı have trying to change my database to postgreSQL but but whenever ı have trying to makemigrations ı got an Error which attached on bellow: Traceback (most recent call last): File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: no such column: Projects_project.abbr The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\manage.py", line 21, in <module> main() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\core\management_init_.py", line 395, in execute django.setup() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\contrib\admin_init_.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\env\Lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\cukad\AppData\Local\Programs\Python\Python311\Lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\cukad\OneDrive\Masaüstü\Rekrom\ERPV3\Projects\admin.py", line 24, in <module> class ProjectListFilter(admin.SimpleListFilter): … -
Django User Model Optimization
UserModel has many entries on it. The 3 UserModel queries run very slow. How to make needed changes and optimizations to UserModel to make the 3 queries run faster? class UserModel(models.Model): username = CharField(max_length=255) role = JSONField() # format of ['admin', 'operator'] UserModel.objects.filter(username='john').first() UserModel.objects.filter(username__contains='doe').first() UserModel.objects.filter(role__contains='operator').first() -
Django manual reset password handling
Our system based without physical templates. All templates stored in database. Template render with HttpResponse and Template classes. I cant use django built-in GenereicViews. How can i manualy handle forgot password and reset password logic, email sending with a unique link? -
get user group name from a specific text in django
In django, user posts in a simple HTML form. In form, there is a field which called "technician_name". I'm getting the post with "name attribute" and write it to database. I want additional thing: after I take the name attribute, I want to check the group of technician. Simply: I want to check user's group according to specific text. For example: user posted the "John Doe". if request.method == 'POST' action_man = request.POST.get('technician_name') Output: action_man = "John Doe" I need this action_man's user group. The action_man's name same with username, so I can query in django auth. Note: I don't need the logged in user's group. I need action man's group. -
Avoid CSRF_TRUSTED_ORIGINS in Django 4.1
I've a dockerized Django project which I access through NGINX. I just upgraded to Django 4.1 and now it seems that it's mandatory to define a CSRF_TRUSTED_ORIGINS listing, I would like to know if there is a way to allow POST requests from any source. I've tried installing https://github.com/ottoyiu/django-cors-headers and setting CORS_ALLOW_ALL_ORIGINS to TRUE but it didn't work :/ Also I tried setting CSRF_TRUSTED_ORIGINS = ['*'] as I have in ALLOWED_HOSTS but it doesn't work... Thank you so much! -
How to use load static (django) in css file for background webkit
How to use {% load static%} in css file for background webkit ? What should i do to get this ? I've tried using {%load static%} in css file but that doesn't work. -
TypeError: 'WSGIRequest' object is not callable
Intento mostrar el modelo de detección de señas en las vistas de django. Pero tengo ese mensaje de error y no me carga la cámara. Estos son mis códigos from django.shortcuts import render from django.http.response import StreamingHttpResponse from PROTOTIPO.step_5_camera import main, center_crop # Create your views here. def home(request): return render(request,'home.html',{}) def sistema(request): return render(request,'Sistema.html',{}) def gen(center_crop): while True: frame=center_crop.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(main): return StreamingHttpResponse(gen(main()), content_type='multipart/x-mixed-replace; boundary=frame') import cv2 import numpy as np import onnxruntime as ort def center_crop(frame): h, w, _ = frame.shape start = abs(h - w) // 2 if h > w: return frame[start: start + w] return frame[:, start: start + h] def main(): # constantes index_to_letter = list('ABCDEFGHIKLMNOPQRSTUVWXY') mean = 0.485 * 255. std = 0.229 * 255. # se crea una sesión ejecutable con el modelo exportado ort_session = ort.InferenceSession("signlanguage.onnx") cap = cv2.VideoCapture(0) while True: # Captura de cuadro por cuadro ret, frame = cap.read() # preprocesamiento de los datos frame = center_crop(frame) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) x = cv2.resize(frame, (28, 28)) x = (x - mean) / std x = x.reshape(1, 1, 28, 28).astype(np.float32) y = ort_session.run(None, {'input': x})[0] index = np.argmax(y, axis=1) letter = index_to_letter[int(index)] cv2.putText(frame, … -
how to deploy django with nginx,guniorn and postgresql
Can anyone please give reference document for deployment process django with nginx gunicorn and postgresql on windows machine Can anyone please give reference document for deployment process django with nginx gunicorn and postgresql on windows machine -
Level of logger in django project app view is undefined
When i initialize the logger in the views.py of my app in my django project, the loglevel is undefined althoug i defined it as INFO in the settings.py. I pass the loglevel as a environment variable (I also checked that it is correctly set to INFO by debugging it). When I check the level of the logger in the views.py it always is 0 which means undefined. I also tried to add a root block to the settings and change the name variable to "django" to load the logger both didn't worked. Maybe anyone can tell me what I am missing? Logging config in settings.py: LOGGING_CONFIG = None LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { # Use JSON formatter as default 'default': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', }, 'django.server': DEFAULT_LOGGING['formatters']['django.server'], }, 'handlers': { # Route console logs to stdout 'console': { 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'django.server': DEFAULT_LOGGING['handlers']['django.server'], }, 'loggers': { # Default logger for all modules '': { 'level': LOGLEVEL, 'handlers': ['console', ], }, # Default runserver request logging 'django.server': DEFAULT_LOGGING['loggers']['django.server'], } } views.py: logger = logging.getLogger(__name__) def teams_overview(request): try: logger.error("error") logger.warning("warning") logger.critical("critical") logger.info("info") logger.debug("debug") output: loglevel of logger: 0 error warning critical Project Strucutre: … -
Django ['“” value has an invalid date format. It must be in YYYY-MM-DD format.']
I have a usecase model, I'm trying to update the fields in the model. I have delivery date and estimated delivery date. It seems that delivery date is not able to update alone. If I update estimated delivery along with delivery date it gets updated. otherwise it shows an error: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] my model: class Usecase(models.Model): usecase_id = models.CharField(primary_key=True, max_length=20) usecase_name = models.CharField(max_length=256) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_type = models.ForeignKey('UsecaseType', models.DO_NOTHING) kpi = models.ForeignKey(Kpi, models.DO_NOTHING) usecase_description = models.CharField(max_length=5000) delivery_date = models.DateField() my views: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) context = {"usecase_details":usecase_details[0], "usecase_types": UsecaseType.objects.all(), "usecase_kpis": Kpi.objects.all()} if request.method == "POST": usecase_type = request.POST['usecase_type'] kpi = request.POST['kpi'] estimated_date = request.POST['estimated_date'] delivery_date = request.POST['delivery_date'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.usecase_type_id=usecase_type usecase_details.kpi_id=kpi usecase_details.estimated_date=estimated_date usecase_details.delivery_date=delivery_date usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) return render(request, 'UpdateUsecase.html', context) except Exception as e: print(e) messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) my template: <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="project-name">Usecase Type:</label> <select name="usecase_type" class="custom-select my-1 mr-sm-2" id="usecase_type"> {% for usecase_type in usecase_types %} … -
it is possible to preview template html file before saving it using the Django admin app?
it is possible to preview template Html file before saving it using the Django admin app?? I am try to make overriding template preview button on admin panel but i can't make this I am try to image preview button -
I want to use "if and elif" Inside the Send_mail function in Django
What I want to achieve is I want to use "if and elif" Inside the Send_mail function in Django but an error occurs and I don't know how to fix it... Error message potential arugment cannot appear after keyword aurgument send_mail( subject='New message', message='Access to http://localhost:3000/messagerooms', from_email=settings.EMAIL_HOST_USER, if inquiry_user == self.request.user: recipient_list = post.user.email elif post.user == self.request.user: recipient_list = inquiry_user.email ) -
I am trying to read TID of RFID tag from Chafon CF-RU 5102 in python, i am getting EPC rather than TID
i am following this link, https://github.com/wabson/chafon-rfid, and getting EPC not TID which is a universally unique Tag ID. i am getting 000000000000000000000000 as EPC, whereas E280F336200060000065DDBE is some what expected to be read -
Why isinstance(Test(), MyAbstractClass) return False even if I implement all abstract methods in Test class
From some book, it says when we define a class and implement all abstract methods, even if the class is not inherited from abstract class, the isinstance() check will return True. I try it on my local: from collections import abc class Test: def __len__(self): return 0 print(isinstance(Test(), abc.Sized)) Because there is only one abstract method in abc.Sized class:_len_, the output is True as expected. But when I try to define my own abstract class, it fails: from abc import abstractmethod, ABCMeta Class MyAbstractClass(metaclass=ABCMeta): @abstractmethod def get_size(self):pass class Test: def get_size(self): return 0 print(isinstance(Test(), MyAbstractClass)) The output is False. I need to register it if I want it to be True: MyAbstractClass.register(Test) Why? Why I check it with abs.Sized I don't need to register it but with my own defined abstract class, I have to register it? -
User Roles In Django
I was able to build a Web app that can restrict access to certain pages for authenticated using Django permissionmixedin But I want to divide authenticated users into groups that can be able to access only certain pages. That is even if you are authenticated you can't access all the pages, but can only access the pages that your group fall into. I thought I could set that up when I log into Django admin panel as a super user, but it did not work. Please I need a comprehensive guide on how to do that, both on the user model, views.py and any other file. Because am completely new to this. Am using class based views because am not conversant with function based views. -
loop through two lists of lists and extract elements
I have two lists: list_a contains the number of questions and types I want. There are three types 1* 2* 3* list_b contain all the questions and the types eg 'Q1:1*' and 'Q1 is of type 1*' is considered one question.. So far I have managed to write a code that loops through and randomly selects the number of questions and the type I want. import random list_a = [[1, 1, 1]] # Read this as i want 1 question of type 1*, 1 question of type 2* and 1 question of type 3* list_b = [['Q1:1*','Q1 is of type 1*', 'Q2:1*', 'Q2 is of type 1*', 'Q3:2*', 'Q3 is of type 2*', 'Q4:2*','Q4 is of type 2*', 'Q5:3*', 'Q5 is of type 3*', 'Q6:3*', 'Q6 is of type 3*']] result = [] # Iterate over each type of question in list_a for i in range(len(list_a[0])): # Determine the number of questions required for this type num_questions = list_a[0][i] # Create a list of the indices of questions in list_b that match this type question_indices = [idx for idx, q in enumerate(list_b[0]) if f":{i+1}*" in q] # Randomly select the required number of questions and their corresponding elements selected_indices = … -
Use xml.etree.elementtree to process xml with xmlns="http://www.w3.org/2005/Atom"
I'm trying to process the data extracted from the web. The decoded raw data was bytes of xml file. I had some old code that just magically worked. However, I'm not sure what they were doing since it's been a while. import urllib, urllib.request url = 'http://export.arxiv.org/api/query?search_query=all:electron+OR+query?id_list=hep-th/9112001&start=0&max_results=2' data = urllib.request.urlopen(url) which could be decoded with data.read().decode('utf-8') which had a file of the form <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <link href="http://arxiv.org/api/query?search_query%3Dall%3Aelectron%20OR%20query%3Fid_list%3Dhep-th%2F9112001%26id_list%3D%26start%3D0%26max_results%3D2" rel="self" type="application/atom+xml"/> <title type="html">ArXiv Query: search_query=all:electron OR query?id_list=hep-th/9112001&amp;id_list=&amp;start=0&amp;max_results=2</title> <id>http://arxiv.org/api/hNIXPXLfJXds3VmSJQ2mnDpmElY</id> <updated>2023-03-20T00:00:00-04:00</updated> <opensearch:totalResults xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">194139</opensearch:totalResults> <opensearch:startIndex xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">0</opensearch:startIndex> <opensearch:itemsPerPage xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">2</opensearch:itemsPerPage> <entry> <id>http://arxiv.org/abs/cond-mat/0102536v1</id> <updated>2001-02-28T20:12:09Z</updated> <published>2001-02-28T20:12:09Z</published> <title>Impact of Electron-Electron Cusp on Configuration Interaction Energies</title> <summary> The effect of the electron-electron cusp on the convergence of configuration interaction (CI) wave functions is examined. By analogy with the pseudopotential approach for electron-ion interactions, an effective electron-electron interaction is developed which closely reproduces the scattering of the Coulomb interaction but is smooth and finite at zero electron-electron separation. The exact many-electron wave function for this smooth effective interaction has no cusp at zero electron-electron separation. We perform CI and quantum Monte Carlo calculations for He and Be atoms, both with the Coulomb electron-electron interaction and with the smooth effective electron-electron interaction. We find that convergence of the CI expansion … -
How to create upload method with authentication FastAPI Users
router = APIRouter( prefix='/reglaments', include_in_schema=True ) router.include_router(reglament_router, dependencies=[Depends(current_user)]) In the route I added dependencies to authentication from FastAPI Users from fastapi_users import FastAPIUsers ... ... ... current_user = fastapi_users.current_user() Below example of how implemented my method @router.post('/{id}/upload', status_code=status.HTTP_200_OK) async def upload_files( relgament_id: int = Path(alias='id'), files: List[UploadFile] = File(description='Reglament documents (pdf, word, excel, etc.)')): '''Upload Reglament Files''' PATH = './static/reglaments' if not os.path.exists(f'{PATH}/{relgament_id}'): path = os.path.join(f'{PATH}/', f'{relgament_id}') try: os.mkdir(path) print(f'[+] Created new directory {relgament_id}, by path {PATH}') except: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Can't create new directory by path {path}") for file in files: try: async with aiofiles.open(f'{PATH}/{relgament_id}/{file.filename}', 'wb') as f: while content := await file.read(1024 * 1024): f.write(content) except: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='There was an error uploading the file') finally: file.file.close() return {"message": "Successfully uploaded"} but when run this method gives 422 error { "detail": [ { "loc": [ "body", "files" ], "msg": "field required", "type": "value_error.missing" } ] } How to implement upload method with authenctication dependecies from FastAPI Users module