Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels Config - Django / Docker / Gunicorn / Daphne / Nginx
I have deployed an app, pypilot.app using django / nginx / docker / daphne / gunicorn on a digital ocean droplet. Daphne is for Django Channels which works no problem in development to display messages in a user's console via websocket. I'm also able to connect to the websocket successfully when navigating to my droplet's IP address over http. When I try to connect to websocket via https at pypilot.app, however, I run into issues. I suspect something is wrong with my ssl setup perhaps? Please let me know if you spot any obvious issues in my setup below. docker compose version: '3' services: web: build: . command: gunicorn unicorn_python.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/code - .:/usr/src/app - /var/run/docker.sock:/var/run/docker.sock ports: - "8000:8000" daphne: build: . volumes: - .:/usr/src/app - .:/code ports: - "8001:8001" command: daphne -b 0.0.0.0 -p 8001 unicorn_python.asgi:application nginx: image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./config/nginx:/etc/nginx/conf.d - /etc/letsencrypt:/etc/letsencrypt:ro - ./static:/usr/src/app/static # Host path to static files mounted inside the container - ./media:/usr/src/app/media # Host path to static files mounted inside the container depends_on: - web - daphne # If Nginx is set to proxy to Daphne as well celery: build: . command: celery -A unicorn_python … -
Django request.user isn't using the custom backend at all
I'm coding with a custom user model and a custom backend in Django 5.0 to login with an email. Here is the backend : class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("authenticate called") try: user = User.objects.get(email=username) except User.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): try: print(user_id) print("get_user called") return User.objects.get(pk=user_id) except User.DoesNotExist: return None It's correctly registered in AUTHENTICATION_BACKENDS, and the user model just have an email field. The backend works perfectly in my register view using authenticate(request, username=email, password=password), and the login(request, user) works too. However, if in another view, after a login I try to use request.user, it will always return AnonymousUser. If I do request.session.values, the user ID is correct. I can't find anyone having the same issue online, so I hope someone can help me troubleshoot it. I tried to use request.user with the custom backend, but it's never called. I also tried to use request.session.values and this time the user ID was correct. The request.user was supposed to return the current user with my custom model, but it always return AnonymousUser -
Detect if a Django related object has been prefetched via select_related
Let's say I have the following models: class Product: name = models.CharField(max_length=128) class ProductVersion: name = models.CharField(max_length=128) product = models.ForeignKey(Product, on_delete=models.CASCADE) For a given ProductVersion object, is there anyway to detect if the Product object was prefetched via select_related? For example: # Yes, "product" was prefetched ProductVersion.objects.select_related("product").first() # No, "product" was NOT prefetched ProductVersion.objects.first() Looks like there's a way to do this was prefetch_related (see here) but I need it for selected_related. -
Django / Celery : How a task can constantly do something ? Is it possible to set an infinite loop for a task?
I'm currently learning Django and Celery. So I have to do a feature to a Django projet, and I use Celery for that : I need to constantly check a list in my Redis server. And for that, I use Celery but I don't know how I can implement correctly that and I opted for a while True:. After the launching of my task with celery -A <my_project> worker -l INFO, it's impossible to kill the task (the CTRL + C doesn't work), or I don't found how I can. I conclude it's not a good method for doing what I want. One more thing : I know the extension django-celery-beat exists but I think it's "weird" to open another terminal for launch this extension. Already I have to launch my django server, then my worker (with celery) on two different terminals, I have to open a third to launch my scheduled task, I don't know if this is really weird to do that, but... I don't know, I think it's weird to do that but I don't know if it really is. Here's my (unique) task in an app in my django project : from celery import shared_task import … -
Rewrite User logic in Django
I need to completely rewrite the user logic in Django. I would like to store only 2 parameters in the database: phone number and telegram_id. The user could login and register with both of these parameters from one page. So I need to rewrite the model and write custom views and urls. The main question is how do I write a user model from scratch, replacing the standard django one. However, I wouldn't want to completely remove the user block and write it from scratch. Just models and some views and urls Search the internet. -
Issue running python3 manage.py makemigrations
(C7M5L1-6 Lab Initial) kennyc@Kennys-MacBook-Pro C7M5L1-6 Lab Initial % brew install mysql-client ==> Downloading https://formulae.brew.sh/api/formula.jws.json ############################################################################################# 100.0% ==> Downloading https://formulae.brew.sh/api/cask.jws.json ############################################################################################# 100.0% Warning: mysql-client 8.3.0 is already installed and up-to-date. To reinstall 8.3.0, run: brew reinstall mysql-client (C7M5L1-6 Lab Initial) kennyc@Kennys-MacBook-Pro C7M5L1-6 Lab Initial % python3 manage.py makemigrat ions Traceback (most recent call last): File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/MySQLdb/__init__.py", line 17, in <module> from . import _mysql ImportError: dlopen(/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/kennyc/Desktop/C7M5L1-6 Lab Initial/manage.py", line 22, in <module> main() File "/Users/kennyc/Desktop/C7M5L1-6 Lab Initial/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File … -
OpenAI API Integration in Django: Request Getting Lost on Server
I have integrated the OpenAI API into my Django project for generating dynamic descriptions for tables generated in my application. The workflow involves processing user input, generating tables, and then passing these tables to the OpenAI API one by one using client.chat.completions.create. While this works smoothly on my local system, when deployed on the server, the request sometimes seems to get lost at the point of calling client.chat.completions.create. It returns the response processed until that stage, rather than waiting for the completion response from the OpenAI API. try: chat_completion = client.chat.completions.create( messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}, ], model="gpt-3.5-turbo", temperature=0.5, max_tokens=1024 ) logger.info('---- GPT4') logger.info("chat completion",chat_completion.choices[0].message.content) response_content = chat_completion.choices[0].message.content logger.info('---- GPT5') except Exception as e: logger.info('---- Error in chat gpt "',str(e)) pass Upon debugging, it seems that the request doesn't wait for the response from client.chat.completions.create, causing it to return incomplete responses on the server. What could be causing this behavior, and how can I ensure that the request waits for the completion response from the OpenAI API before proceeding further? Any insights or suggestions would be greatly appreciated. Thank you! -
Heroku app unable to import Django, using requirements/Aptfile/Procfile
I have a django server that works locally but I am having a really tough go of trying to get Heroku to deploy it. The error I constantly get no matter what I try is Traceback (most recent call last): File "/app/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 21, in <module> main() File "/app/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? After reading various similar questions around here, I decided to try setting PYTHONPATH to '/app' (after first reducing manage.py to a 'hello world' so heroku would let me change config vars) so I got that set up and then restored manage.py, only to receive the same error. Build always succeeds, release always fails. manage.py, requirements.txt, runtime.txt, Procfile and Aptfile are all on the root directory. manage.py is unmodified from the default. The contents of the other files: requirements.txt: asgiref==3.7.2 certifi==2023.7.22 distlib==0.3.8 django==5.0 django-cors-headers==4.3.1 djangorestframework==3.14.0 djangorestframework-simplejwt==5.3.1 filelock==3.13.1 mysqlclient==2.2.1 platformdirs==4.1.0 protobuf==4.24.4 PyAudio==0.2.14 … -
Exception Value: Field 'id' expected a number but got 'count'
ValueError at /cart/LFzsWGDl13fxCZP/ Field 'id' expected a number but got 'count'. Request Method: POST Request URL: http://127.0.0.1:8000/cart/LFzsWGDl13fxCZP/ Django Version: 5.0.4 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'count'. Exception Location: C:\Users\Next Nout\Documents\NT\Najot talim vazifa\7-oy\8-dars\shop\env\Lib\site-packages\django\db\models\fields_init_.py, line 2119, in get_prep_value Raised during: main.front.views.cart_detail Python Executable: C:\Users\Next Nout\Documents\NT\Najot talim vazifa\7-oy\8-dars\shop\env\scripts\python.exe Python Version: 3.12.0 Python Path: ['C:\Users\Next Nout\Documents\NT\Najot talim vazifa\7-oy\8-dars\shop', 'C:\Users\Next ' 'Nout\AppData\Local\Programs\Python\Python312\python312.zip', 'C:\Users\Next Nout\AppData\Local\Programs\Python\Python312\DLLs', 'C:\Users\Next Nout\AppData\Local\Programs\Python\Python312\Lib', 'C:\Users\Next Nout\AppData\Local\Programs\Python\Python312', 'C:\Users\Next Nout\Documents\NT\Najot talim ' 'vazifa\7-oy\8-dars\shop\env', 'C:\Users\Next Nout\Documents\NT\Najot talim ' 'vazifa\7-oy\8-dars\shop\env\Lib\site-packages'] Server time: Sun, 07 Apr 2024 18:16:06 +0000 **@login_required(login_url='auth:login') def cart_detail(request, code): cart = models.Cart.objects.get(code=code) queryset = models.CartProduct.objects.filter(cart=cart) if request.method == 'POST': data = list(request.POST.items())[1::] for id,value in data: cart_product = models.CartProduct.objects.get(id=id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … cart_product.count = value cart_product.product.quantity -= int(value) cart.status = 2 cart_product.product.save() cart.save() cart_product.save()** -
How not to save data from Inline Django Model?
I'm trying to implement the ability to view users' locations in a task through the inline Geoposition model. Geoposition stores latitude and longitude, then thanks to changing the tabular.html template I display the map When I try to save the model, I get an error: The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS, because data from this Geoposition inline trying to POST. I would not like to change this setting. In this case, the inline model class looks like this class TaskTransitInline(admin.TabularInline): template = "admin/gis/tabular_override.html" model = Geoposition extra = 0 max_num = 0 can_delete = False fields = ( "id", "task", "created_at", "longitude", "latitude", "speed", ) readonly_fields = ["id", "task", "created_at", "longitude", "latitude", "speed"] Why do I then see ID and task in the data POST? Maybe someone can help me -
Problem with pip install (FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt')
I wanted to use contributions graph in my Django project, so after quick research I decided to use 'contributions-django' library. But when I tried to install it, I got stuck with this error:: FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I am no pip expert, but I can see that requirements.txt file exists in this repository (altough it's empty). How to fix this? Can I install the libary manually? How? Thanks for help in advance. -
Django QuerySet: how to aggregate repeated elements and add quantity field to it?
I have a feeling the solution to this is very simple, but as new to Django I am not able to figure it out... Given the following QuerySet: <QuerySet [ {'id': 2, 'prodclassQuery_id': 1, 'prodDescription': 'Hofbräu Kellerbier 500 ml', 'prodPrice': Decimal('6.50')}, {'id': 1, 'prodclassQuery_id': 1, 'prodDescription': 'Tonic Water 300 ml', 'prodPrice': Decimal('4.50')}, {'id': 3, 'prodclassQuery_id': 2, 'prodDescription': 'Coxinha 6 unidades', 'prodPrice': Decimal('8.00')}, {'id': 3, 'prodclassQuery_id': 2, 'prodDescription': 'Coxinha 6 unidades', 'prodPrice': Decimal('8.00')}]> I want to aggregate the repeated elements (based on id) e produce the following QuerySet, adding the field poQty_ to represent the quantity of repeated elements (products in my case...): <QuerySet [ {'id': 2, 'prodclassQuery_id': 1, 'prodDescription': 'Hofbräu Kellerbier 500 ml', 'prodPrice': Decimal('6.50'), 'poQty_': 1}, {'id': 1, 'prodclassQuery_id': 1, 'prodDescription': 'Tonic Water 300 ml', 'prodPrice': Decimal('4.50'), 'poQty_': 1}, {'id': 3, 'prodclassQuery_id': 2, 'prodDescription': 'Coxinha 6 unidades', 'prodPrice': Decimal('8.00'), 'poQty_': 2}]> What I tried so far with annotate() in views.py is not working, and the results of orders_aggris the same original QuerySet: def display_orders(request): orders = Order.objects.all().order_by('id', 'orderTable', 'menuQuery') for j in orders: print(j.prodQuery.values(),) # original QuerySet orders_aggr = Order.objects.annotate(poQty_=Count('prodQuery__id')).order_by('id', 'orderTable', 'menuQuery') for j in orders_aggr: print(j.prodQuery.values(),) context = { 'orders': orders, 'orders_aggr': orders_aggr } return render(request, 'orders.html', context) … -
Saving form data failed:TypeError: fromisoformat: argument must be str
# views.py: class CommentAddView(LoginRequiredMixin, CreateView): form_class = CommentForm model = Comment def form_valid(self, form): comment = form.save(commit=False) comment.article_id = self.kwargs['pk'] print(type(comment.article_id)) comment.user = self.request.user import pdb pdb.set_trace() form.save() return super().form_valid(form) def get_success_url(self): return reverse('article:detail',args=[self.kwargs['pk']]) # forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] #models.py: article = models.ForeignKey(Article, on_delete=models.CASCADE) user = models.ForeignKey('user.User', on_delete=models.CASCADE) body = models.TextField('content', help_text='content') parent = models.OneToOneField('self', on_delete=models.CASCADE,null=True) #article_detail.html: <v-form action="{% url 'article:comment_add' article.id %}" method="post"> {% csrf_token %} <v-textarea height="100px" class="mx-2" name="body" placeholder="Please enter" > </v-textarea> <div class="d-flex justify-end"> <v-btn color="primary" small type="submit" class="mr-7 mb-2" >Get it!</v-btn> </div> </v-form> This is article details page similar to blog, I want add a comment function, but is will report a different error. I'm trying to write - comment_form.html, but It's not written in the video tutorial. I also tried adding a 'user' to the field list. But is doesn't work, you can't save the comment data like in the video. -
django constraint in multi-tenant application
I have a multi-tenant application where we use multi-currency. The simplified models looks like: class Currency(models.Model): multi_tenant_company = models.ForeignKey(MultiTenantCompany, on_delete=models.CASCADE) is_default_currency = models.BooleanField(default=False) Now I want to add a unique db constraint on this model where every multi_tenant_company can only have 1 default currency. My current approach, which fails is: class Meta: constraints = [ models.UniqueConstraint( fields=['is_default_currency', 'multi_tenant_company'], condition=Q(is_default_currency=True), name='unique_is_default_currency') ] What am I missing? -
Dynamically load content from SSR into vanilla JS
I have a project based on Django, which provides different pages rendered by django itself. I want to make this a single page application, so django only serves an index with a full HTML page, and then I use other endpoints for rendering the body, and I inject the content into the index page using JavaScript. This is the index page: {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> <script type="module" src={% static "js/index.js" %}></script> </head> <body> <div id="root"></div> <!-- index.js has a function that overwrites the contents of this element with the retrieved page --> </body> </html> And an example of a page: {% load static %} <script type="module" src={% static "js/page.js" %}></scrip> <button onclick="helloworld()"> Click me! </button> The page.js file would have functions like this: function helloworld() { alert("Hello world!"); } This works well enough for loading HTML and CSS content, but not so much for anything related to JavaScript. Using this method, any JS that comes in the SSR response won't be loaded, and the injected HTML won't be able to access any of the JS functions loaded along with the index page unless I assign them to a global object like window or document. … -
Python & Django web app - auto emails not sending - troubleshooting Cron
I have a webapp running on an ubunti vps. Cron is scheduled to run a task evry sunday morning, however, I found it ran once and not again the next week. I have been reading about cron and how to troubleshoot but need help understanding what is shown when I run sudo systemctl status cron. Please describe what the lines below are telling me. Is there a reason it only ran my script once? sudo systemctl status cron ● cron.service - Regular background program processing daemon Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2024-04-04 19:50:25 UTC; 2 days ago Docs: man:cron(8) Main PID: 605 (cron) Tasks: 1 (limit: 4647) Memory: 1016.0K CPU: 3.943s CGroup: /system.slice/cron.service └─605 /usr/sbin/cron -f -P Apr 07 11:17:01 Software CRON[12453]: pam_unix(cron:session): session closed for user root Apr 07 12:00:01 Software CRON[12521]: pam_unix(cron:session): session opened for user root(uid=0) by (uid=0) Apr 07 12:00:01 Software CRON[12522]: (root) CMD (test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q r> Apr 07 12:00:01 Software CRON[12521]: pam_unix(cron:session): session closed for user root Apr 07 12:17:01 Software CRON[12528]: pam_unix(cron:session): session opened for user root(uid=0) by (uid=0) Apr 07 12:17:01 Software CRON[12529]: … -
AttributeError: 'set' object has no attribute 'decode'
I started learning Django for a school project and I'm doing a chat project using websocket server, but when reloading the app I get this error even tho I'm not calling decode() anywhere. I'm using Django Channels with Daphne. here is my consumers.py from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, code): pass here is my routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ # path('chat/', consumers.ChatConsumer.as_asgi()) path('chat/', consumers.ChatConsumer.as_asgi()) ] here is my asgi.py import chat.routing import os from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( JWTAuthMiddlewareStack( URLRouter(chat.routing.websocket_urlpatterns) ) ) }) I received this traceback WebSocket HANDSHAKING /chat/ [127.0.0.1:49878] WebSocket CONNECT /chat/ [127.0.0.1:49878] Exception inside application: 'set' object has no attribute 'decode' Traceback (most recent call last): File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__ return await self.application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/channels/security/websocket.py", line 37, in __call__ return await self.application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/django_channels_jwt_auth_middleware/auth.py", line 36, in __call__ return await self.app(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/macbook/programacao/pap/env/lib/python3.12/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), … -
why i cannot login with new registered users in django while i can login with previous users
in django i create a user then click the activation link to activate the account, after it is activated, I cannot login, i get DoesNotExist at / error class VerificationView(View): def get(self, request, uidb64, token): try: # ! fixed force_text to force_str as it has been removed from later Django Versions id = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=id) if not token_generator.check_token(user, token): return redirect("login"+"?message"+"User already activated") if user.is_active: return redirect("login") user.is_active = True user.save() messages.success(request, "Account activated successfully") return redirect("login") except Exception as ex: pass return redirect("login") class LoginView(View): def get(self, request): return render(request, "authentication/login.html") def post(self, request): username = request.POST["username"] password = request.POST["password"] if username and password: user = auth.authenticate(username=username, password=password) if user: if user.is_active: auth.login(request, user) messages.success( request, "Welcome, "+user.username+" you are now logged in to your account") return redirect("expenses") else: messages.error( request, "Account is not active, please check your email!") return render(request, "authentication/login.html") else: messages.error(request, "Invalid credentials, try again") return render(request, "authentication/login.html") else: messages.error( request, "Please provide both username and password.") return render(request, "authentication/login.html") with previous logins all is fine, only new registered users are getting this error -
Webapp in pure Pyton resp. without JS?
I search a Language and / or Framework to develop a professional Webapp in (for example) pure Python. My prefered language is python, but i could also use somethin other. The point is, that I don't want to use JavaScript, because i probably hate that shit. (sorry for that statement). I was flirting with Django and recently read about Reflex. But I'm not sure if I can develop a really stunning frontend with Django (without a JS framework) and Reflex perhaps seems to be a bit immature (I'm not sure about this...). So the goal is to develop a whole Webapp (but more or less small and simple) without using JS, and ideally with python. Since i perhaps wanna do some numerical calculations or data science stuff in the backend / background, i think python would be easy and straight forward. Constraints: I don't want to use the Microsoft dotnet stuff. It's important, that i can use nearly any database in the background. Perhaps I wanna use a Graph-Database at the end. But i'ts open now. (... open arch, freedom to choose...) Optional: I could also use some other langauge? (sic!) It should be fully OpenSource to use, perhaps with … -
Unable to create UserProfile object for User
I have a User model and a UserProfile model with a one-to-one relationship. I'm using a serializer to create users, and I want to automatically create a corresponding UserProfile object for each user upon creation. However, I'm encountering an issue where the UserProfile object is not getting created when I create a new user. Despite setting up the UserProfile model with a OneToOneField relationship to the User model and specifying the related name as "userprofile", I keep getting an error stating that there is no related object. Additionally, when I retrieve user data using the GET method with this serializer, the userprofile field shows as null, even though I expect it to contain the related UserProfile object. Here's my UserSerializer: class UserSerializer(serializers.ModelSerializer): userprofile = UserProfileSerializer(read_only=True) profile_data = serializers.JSONField(write_only=True) class Meta: model = account_models.User fields = ( "id", "username", "password", "email", "is_premium", "premium_time", "userprofile", "profile_data" ) extra_kwargs = { "password": {"write_only": True}, } def create(self, validated_data): profile_data = validated_data.pop('profile_data') image_path = profile_data.pop("image_path", None) password = validated_data.pop("password") user = account_models.User.objects.create(**validated_data) user.set_password(password) user.save() userprofile = profile_models.UserProfile.objects.create(user=user, **profile_data) if image_path: save_image(instance=userprofile, image_path=image_path) send_notification(user=user, action="CREATE_ACCOUNT") return user And here's the relevant part of my UserProfile model: class UserProfile(models.Model): def image_path(self, filename): return f"Users/user_{self.user.id}/{filename}" user = … -
Display a field form a foreign key onto a template
class Product(models.Model): model=models.CharField(max_length=50, null=True) serial=models.CharField(max_length=50, null=True) hd_size=models.CharField(max_length=50,null=True) ram=models.CharField(max_length=50, null=True) processor=models.CharField(max_length=50, null=True) product_type = models.CharField(max_length=10, null=True) date_purchased = models.DateField(null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) employee = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) I am trying to display the data from this model but the foreign key column "employee" is not showing on the template -
Facing this error "TypeError: Completions.create() got an unexpected keyword argument 'headers'"
Code was running fine previously , but dont know what happened now. I tried upgrading my langchain versions , but still got this error. Code is breaking on the line "response=chain.invoke({"question":question, "table_info":self.db.get_table_info()})". Previous langchain versions were supporting chain.invoke , but i guess they have changed something now . please check and help me resolve this problem. from langchain import OpenAI, SQLDatabase from langchain.chains import create_sql_query_chain from dotenv import load_dotenv import os from urllib.parse import quote_plus from langchain.chat_models import AzureChatOpenAI from langchain.prompts import ChatPromptTemplate import re class CventDemo: def __init__(self): load_dotenv() try: azure_openai_endpoint = os.getenv('OPENAI_API_BASE') os.environ["OPENAI_API_TYPE"] = os.getenv('OPENAI_API_TYPE') os.environ["OPENAI_API_VERSION"] = os.getenv('OPENAI_API_VERSION') os.environ["OPENAI_API_BASE"] = azure_openai_endpoint[:-1] if azure_openai_endpoint.endswith('/') else azure_openai_endpoint os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY') self.deployment_name = os.getenv('DEPLOYMENT_NAME') self.llm = AzureChatOpenAI( model_kwargs={ "headers": {"User-Id": os.getenv("USER_ID")} }, deployment_name=self.deployment_name, model=os.getenv('MODEL_NAME'), temperature=0.0, ) self.username= os.getenv('username') self.password=os.getenv('password') self.host= os.getenv('host') self.database=os.getenv('database') self.encoded_password=quote_plus(self.password) self.mysql_uri = f"mysql+mysqlconnector://{self.username}:{self.encoded_password}@{self.host}/{self.database}" self.db = SQLDatabase.from_uri(self.mysql_uri) except Exception as e: print("An error occurred during initialization:", str(e)) exit() def run_query(self, question): try: template=""""Write a SQL query for the given task by following the listed steps: Task: {question} Follow these steps: First, create your definition of the problem. And the understood meaning. Then, prepare the logic that you will be using to solve the task using SQL. Do not make … -
Issue with Django CMS Icon Module: Missing Static Path and Extra Class in Generated Markup
I am attempting to utilize the djangocms-icon module to incorporate my own SVG icons into my Django CMS project. Following the documentation, I have successfully added Material Design icons. However, I encounter issues when adding my custom SVG icons. In my settings.py, I added the following code: with open('iconset.json') as fh: ICONSET = fh.read() DJANGOCMS_ICON_SETS = [ ('fontawesome5regular', 'far', 'Font Awesome 5 Regular', 'latest'), ('fontawesome5solid', 'fas', 'Font Awesome 5 Solid', 'latest'), ('fontawesome5brands', 'fab', 'Font Awesome 5 Brands', 'latest'), ('materialdesign', 'zmdi', 'Material Design'), (ICONSET, 'svg-icon', 'My Icons'), ] DJANGOCMS_ICON_TEMPLATES = [ ('svg', 'SVG template'), ] I have created an iconset.json file at the root of my project: { "svg": true, "spritePath": "sprites/icons.svg", "iconClass": "svg-icon", "iconClassFix": "svg-icon-", "icons": [ "svg-icon-card", "svg-icon-card-add" ] } I have also created my icons.svg file in static/sprites/icons.svg: <svg width="0" height="0" class="hidden"> <symbol xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" id="svg-icon-card"> <!-- path data --> </symbol> <symbol xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" id="svg-icon-card-add"> <!-- path data --> </symbol> </svg> Additionally, I created templates/djangocms_icon/svg/icon.html: {% load cms_tags static %} <span class="icon {{ instance.attributes.class }}"> <svg role="presentation"> <use xlink:href="{% static 'sprites/icons.svg' %}#{{ instance.icon }}"></use> </svg> </span> The issue arises in the generated markup. In the icon addition widget inspection, there … -
Websocket secure connection error in browser
can anyone tell me why the websocket connection showing error? How to fix this? //script.js Code snippet error in browser: WebSocket connection to 'wss://pdfsahakari.online:8443/sahakari/landing/ws/document-uploader/' failed: uploadFile @ script.js:16 onclick @ landing/:36 script.js:33 how to fix the issue ? -
How to send confirmation emails and scheduled emails in Django
I'm working on a Django project involving a custom user registration form. My goal is to implement a two-step email notification process upon form submission: Immediate Email Confirmation: Automatically send a customized email to the user immediately after they submit the form. Scheduled Email Notification: Send a second customized email at a later date, which is determined by the information provided when the form is created (e.g., a specific date for event reminders). The scheduling of the second email needs to be dynamic, allowing for different dates based on the form's context, such as varying event dates. How can I achieve this with Django? especially for scheduling emails to be dispatched at a future date. Note that I expect a volume of 1000 submissions per month. Thanks for your help in advance.