Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
consist connection with multi websocket in django
In my django project i must interact with several server throw websocket and it needs constant connection with them. how can i define a management command to connect to all servers and then i my api i call each one of them that i want with their url I wrote an async manager and management command to creat connection to all of them: # servers/websocket_manager.py import asyncio class WebSocketManager: def __init__(self): self.clients = {} async def add_client(self, url): client = WebSocketClient(url) await client.connect() self.clients[url] = client def get_client(self, url): return self.clients.get(url) async def close_all_clients(self): await asyncio.gather(*[client.close() for client in self.clients.values()]) self.clients.clear() class WebSocketClient: def __init__(self, url): self.url = url self.connection = None async def connect(self): # Logic to establish the WebSocket connection pass async def close(self): # Logic to close the WebSocket connection if self.connection: await self.connection.close() # management/commands/init_websockets.py from django.core.management.base import BaseCommand from servers.websocket_manager import WebSocketManager from servers.models import Server # Ensure this is the correct path to your Server model import asyncio from multiprocessing import Process class Command(BaseCommand): help = 'Initializes WebSocket connections to specified URLs' def handle(self, *args, **options): manager = WebSocketManager() servers = Server.objects.all() urls = [server.url for server in servers] process = Process(target=self.run_event_loop, args=(manager, urls)) … -
Issue Running Unittests on GitHub Actions - ImportError
I’m encountering an issue running unit tests for my Django project on GitHub Actions. The tests run fine on my local machine using Docker containers, but I’m facing errors when running tests on GitHub Actions. Issue Description: In my CI/CD configuration file (GitHub Actions), I encounter an error when attempting to run tests. Here is a snippet of the error I’m receiving: ====================================================================== ERROR: AHC_app.AHC_app (unittest.loader._FailedTest.AHC_app.AHC_app) ---------------------------------------------------------------------- ImportError: Failed to import test module: AHC_app.AHC_app Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.12.4/x64/lib/python3.12/unittest/loader.py", line 429, in _find_test_path package = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.12.4/x64/lib/python3.12/unittest/loader.py", line 339, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'AHC_app.AHC_app' What I’ve Tried: 1. Setting PYTHONPATH: I’ve experimented with different configurations for the PYTHONPATH environment variable to point to the module locations, but I encounter the same error. Below are some examples of configurations I’ve tried: 2. _init_.py Files: I verified that all necessary _init_.py files are present, confirming the project structure is correct. What I Need Help With: Has anyone experienced similar issues with importing modules when running tests on GitHub Actions? What could be causing the ModuleNotFoundError, and what are best practices for configuring PYTHONPATH in the context of GitHub Actions? Additional Context: I am using Docker … -
django AttributeError at /signup/ 'dict' object has no attribute 'error'
enter image description here it was working just fine but suddenly when some tries to signup it shows this error. please note that messages at messages.error(request, "Invalid reCAPTCHA. Please try again.") is from pyexpat.errors import messages from django.contrib import messages instead of from pyexpat.errors import messages -
Django ViewFlow - Add dropdown selector to BPMN process step
Have a basic ViewFlow BPMN Process Flow set up. How can i add a dropdown selector to a step in the BPMN process with for instance a dropdown list of selections e.g. Users or Companies that needs to be selected as part of the step? the jsonstore proxy class does not have a dropdown option. Can i use the Forms and embed in the step somehow? thanks -
configure the nginx server
When I run the Docker container, I can see that Django correctly specifies the paths to the static and media files, but Nginx still can't find them. This causes a 404 error when trying to access files like bootstrap.min.css. Django settings: STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") # NOQA # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "static"), # NOQA F405 # ] MEDIA_URL = "media/" MEDIA_ROOT = BASE_DIR / "media/" # NOQA print(os.path.join(BASE_DIR, 'static')) # I wanted to see what the path would be print(os.path.join(BASE_DIR, 'media')) the console displays this path: /shop/src/static /shop/src/media Nginx configuration: server { listen 80 default_server; listen 443 default_server; server_name shop; location /static/ { alias /shop/src/static/; } location /media/ { alias /shop/src/media/; } location / { proxy_set_header Host $host; proxy_pass http://backend:8010; } } In the Nginx logs, I get: 2024/07/30 07:53:31 [error] 30#30: *1 open() '/shop/src/static/css/bootstrap.min.css' failed (2: No such file or directory), client: 172.18.0.1, server: shop, request: 'GET /static/css/bootstrap.min.css HTTP/1.1', host: 'localhost' -
Swapping images in Django(Using javascript/js)
This is the block of HTML code which contains one Main image and other additional images. If the user clicks on any additional images, the image should get replaced by the Main image. The logic works fine until I click the same image twice. After that the main image is lost <img id="mainThumbnail" class="card-img-top mb-5 mb-md-0 rounded" src="{{ product.image.url }}" alt="{{ product.name }}" /> <!-- Additional Images --> {% if additional_images %} <div class="additional-images mt-4"> <div class="row"> {% for image in additional_images %} <div class="col-2"> <img class="img-fluid rounded cursor-pointer thumbnail-image" src="{{ image.image.url }}" alt="Additional image for {{ product.name }}" onclick="swapImages('{{ image.image.url }}', this)" /> </div> {% endfor %} </div> </div> {% endif %} This is my javascript function function swapImages(newImageUrl, clickedElement) { console.log(this); // Get the current main image URL const currentThumbnailUrl = document.getElementById('mainThumbnail').src; // Update the main thumbnail image with the new image URL document.getElementById('mainThumbnail').src = newImageUrl; // Update the clicked image with the previous main thumbnail image URL clickedElement.src = currentThumbnailUrl; // Remove 'selected' class from all thumbnail images document.querySelectorAll('.thumbnail-image').forEach(img => img.classList.remove('selected')); // Add 'selected' class to the clicked thumbnail image clickedElement.classList.add('selected'); } document.querySelectorAll('.cursor-pointer').forEach(el => el.style.cursor = 'pointer'); I don't wanted to use the javascript but that's the … -
How to Load Templates in Django for specific application?
So I am Learning Django at in advanced level, I Already know how to include templates from BASE_DIR where manage.py is located. However I wanted to know how to locate templates in the specific app in Django. For Example, I have a project named 'mysite' and an app called polls. Now, I Added Templates in settings.py DIRS=[os.path.join(BASE_DIR, "templates")]. but, how to add templates specific to polls app in polls app directory? . ├── db.sqlite3 ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── static │ │ ├── images │ │ ├── scripts.js │ │ └── style.css │ ├── tests.py │ ├── urls.py │ └── views.py └── templates ├── polls │ └── index.html └── static ├── images ├── scripts.js └── style.css Before, I Wanted it to look like this. . ├── db.sqlite3 ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── … -
Django & rest_framework - method get_queryset being called twice, is there any other better solution?
Currently I have a project using django and rest_framework to get some basic APIs on the run. The problem is, when i make a view using the generic lib on rest_framework and DjangoModelPermissions, my method get_queryset is being called twice My Permission Class class DefaultModelPermissions(DjangoModelPermissions): """ The request is authenticated using `django.contrib.auth` permissions. See: https://docs.djangoproject.com/en/dev/topics/auth/#permissions It ensures that the user is authenticated, and has the appropriate `view`/`add`/`change`/`delete` permissions on the model. This permission can only be applied against view classes that provide a `.queryset` attribute. """ perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class DefaultModelViewPermissions: permission_classes = (DefaultModelPermissions,) My View class AgentListCreateView(DefaultModelViewPermissions, generics.ListCreateAPIView): serializer_class = serializers.AgentSerializer def get_queryset(self): print('get_queryset') return models.Agent.objects.all() Debbuging the app, I found out that the permission also call the get_queryset to retrieve the model to validate the django's user's permissions. permission_calling_get_queryset From my point of view, this is an unecessary operation. Deppending on the size of the DB table, this could be a major performance problem, and leed many other app issues. My solution was to override this "has_permission" method. So my class got like class DefaultModelPermissions(DjangoModelPermissions): """ The request is authenticated using `django.contrib.auth` permissions. … -
Unable to display a Message immediately while adding to wishlist url by clicking the wishlist button from the product card
this is the views.py function for the backend from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from .models import Product, Wishlist @csrf_exempt @login_required def add_to_wishlist(request): product_id = request.GET.get('id') product = Product.objects.get(id=product_id) wishlist_count = Wishlist.objects.filter(product=product, user=request.user).count() if wishlist_count > 0: msg = "Product already exists in wishlist" else: Wishlist.objects.create(product=product, user=request.user) msg = "Product added to wishlist" wishlist_count = Wishlist.objects.filter(user=request.user).count() request.session['wishlist_count'] = wishlist_count return JsonResponse({"bool": wishlist_count > 0, 'totalwishlistitems': wishlist_count, 'msg': msg}) this is my functions.js ajax call to sent to the backend $(document).ready(function () { $(document).on('click', '.add-to-wishlist', function (event) { event.preventDefault(); event.stopPropagation(); console.log('Button clicked'); let product_id = $(this).data("product-item"); console.log("Product ID is", product_id); let this_val = $(this); $.ajax({ url: "/add-to-wishlist", data: { "id": product_id }, dataType: "json", beforeSend: function () { console.log('Before sending AJAX'); this_val.css("color", "red"); }, success: function (response) { console.log('AJAX success', response); this_val.toggleClass("wishlist-added", response.bool); $(".wishlist-items-count").text(response.totalwishlistitems); if (response.msg) { console.log('Message from server:', response.msg); // Create the message element const message = $('<div class="wishlist-message">' + response.msg + '</div>'); console.log('Message element created:', message); // Append the message element to the page $('body').append(message); console.log('Message element appended to body'); // Show the message element message.fadeIn(); console.log('Message element faded in'); // Hide the message element after 3 seconds setTimeout(function () { message.fadeOut(function … -
Module is suddenly not found, and can't install it either with pip
Yesterday I was working on my project. Today, when I opened it, two modules aren't found. Yesterday they were, so that is pretty strange already. When I try to install using pip, it says 'Requirement already satisfied'. The modules I need to install are these: from decouple import config from celery.schedules import crontab I already surfed around the internet trying random things, since I am new and learning django and python I find my problem very hard to understand. -
How can I grant permissions to a client that is not a User in Django?
I have a Django Rest Framework application that has been working well with OIDC auth and human interactions using django-oauth-toolkit. Now I want to add a couple of service accounts so that some external automation can make some requests and create some objects. According to django-oauth-toolkit, The Client Credential grant is suitable for machine-to-machine authentication. So I've implemented this grant type and tested it out with the below script: client_id='axXSSBVuvOyGVzh4PurvKaq5MHXMm7FtrHgDMi4u' secret='hun***2' credential="${client_id}:${secret}" CREDENTIAL=$(printf '%s' "$credential" | base64) export CREDENTIAL ( set -x r=$( curl "http://[::1]:8080/o/token/" \ -H "Authorization: Basic ${CREDENTIAL}" \ -H "Cache-Control: no-cache" \ -H "Content-Type: application/x-www-form-urlencoded" \ -X POST \ -d "grant_type=client_credentials" \ -d 'user=2' ) access_token=$(jq -r '.access_token' <<< "$r") curl -H "Authorization: Bearer ${access_token}" -H "Cache-Control: no-cache" 'http://[::1]:8080/notify/riskimpacts/' ) and the response is an HTTP 403: {"detail":"You do not have permission to perform this action."} It authenticates, but does not authorize any access to any views, because there is no user associated with these credentials. In fact, django-oauth-toolkit removes the user from the request even if there should be one, so there really cannot ever be a user associated with the access token created here. Yet, all but the most open (practically anonymous) django-rest-framework permissions require … -
Best Practices for Deploying Permanently Running Applications on Windows Server
I'm currently managing several projects deployed on a Windows Server, including: A Django backend, Celery for background tasks, React frontends Due to coorperate constraints, we can't use a Linux server, where solutions for these needs are more straightforward. I'm looking for the best practices or tools that can help in deploying these applications on a Windows environment, ensuring they run reliably over time. Specifically: Django Backend: What are the recommended ways to deploy Django on Windows? Celery: What are the best practices for running Celery workers and the beat scheduler on Windows? How can I ensure they are automatically restarted in case of a failure? React Frontend: What are the best deployment strategies for React applications on a Windows server? Additionally, I'd appreciate any advice on: Setting up a robust logging system. Monitoring the health and performance of these services. Ensuring automatic startup and recovery after server reboots or failures. Any guidance or resources would be greatly appreciated! Thank you in advance. I have looked into using NSSM (Non-Sucking Service Manager) for managing services, but it seems to be a dead project with no recent updates or active maintenance. Currently, we are using Windows Task Scheduler, but it appears ill-suited … -
Creating a reusbale form in Django SOLVED
Right, trying to create a reusable form into my Django website. For some reason, it's just not displaying the form fields. It's displaying the submit button, but despite correctly setting out the fields, and passing them to my template, the template is refusing the display the form fields. Trying to set up the form on the privacy-statement page and would also just love to reuse this i my cookie-statement page as well. The privacy-statement already exists, the form is new and I want this to be reusable. Here is my setup, including the file paths of each file: Update: this has been solved. See altered working below: #PROJECT-NAME/legal/forms.py from django import forms class TicketForm(forms.Form): subject = forms.CharField(max_length=255) description = forms.CharField(widget=forms.Textarea) email = forms.EmailField() #PROJECT-NAME/legal/views.py from django.shortcuts import render, redirect from django.http import HttpResponse from . forms import TicketForm from django.core.mail import send_mail, BadHeaderError from django.template import loader from blauwestadtech import utils from django.conf import settings import requests def legal__privacy_statement(request): form = TicketForm() context = { 'form' : form } return render (request, 'privacy-statement.html', context) #PROJECT-NAME/legal/urls from django.contrib import admin from django.urls import path, include from . import views from .views import create_ticket urlpatterns = [ path( 'privacy/', include( [ path('cookie-statement', … -
How to redirect oauth callback with GET parameters to another view in Django
I am trying to handle a Google oauth2 callback for my app which uses subdomains for each customer. The user makes the authorization request from customer1.example.com/login, but Google requires a single callback page like www.example.com/callback for all possible subdomains. I encode the customer1 subdomain in the oauth state parameter. What I want to do is read the subdomain in one view and then redirect the entire callback, parameters and all, to a new page within the subdomain like customer1.example.com/callback. Here's how I'm accomplishing that now: urls.py urlpatterns = [ ... path('callback/', views.gcallback, name='g_callback') ... ] views.py from subdomains import reverse #like reverse(), but supports subdomains from django.shortcuts import redirect from django.utils.http import url encode def gcallback(request): state = request.GET.get('state') subdom = state.split('%')[0] scope = request.GET.get('scope') code = request.GET.get('code') redir_url = reverse('users:g_callback', subdomain=subdom) #reappending GET parameters to URL param_string = urlencode(f'{state}&{code}&{scope}') redir_url = f'{redir_url}?{param_string}' return redirect(redir_url) While this works, is there a way to effect the redirect simply to the new page with the original parameters? Something like: def gcallback(request): subdom = request.GET.get('state').split('%')[0] redir_url = reverse('users:g_callback', subdomain = subdom) return redirect(redir_url, request) I'm just trying to eliminate having to recreate the parameter string - especially considering Google could add parameters to … -
Python Django urls.py do not remove part of the address
I have urls.py as is. If I go to /catalog/product/"path" then on this page I can't specify a URL that won't include /catalog/product/"path". Please tell me how to change urls.py so that in the html template I can call values different from /catalog/product/"path" My template <div class="PD-local"> <a href="/">Главная</a> &emsp;&gt;&emsp; <a href="{{ index.category.slug }}">{{ product.category.name }}</a> &emsp;&gt;&emsp; <a href="{{ category.slug }}">{{ product.name }}</a> </div> My urls.py urlpatterns = [ path('search/', views.catalog, name='search'), path('<slug:category_slug>/', views.catalog, name='index'), path('product/<slug:product_slug>/', views.product, name='product'), path('product/model/<slug:model_slug>', views.model, name='model'), ] -
Integrating DBT Semantic Layer to LLM
I’m working on a Django application where I want to enable natural language querying capabilities using an OpenAI language model (LLM) like GPT-3. To structure and simplify the database access, I plan to use a DBT (Data Build Tool) semantic layer. My goal is to allow users to ask questions in natural language, which are then translated into SQL queries through the LLM, utilizing the semantic definitions provided by DBT. This setup should ideally support complex queries across multiple tables, leveraging the relationships and dimensions defined in the semantic layer. Here’s a brief outline of the setup: 1. Django Application: Serves the frontend and backend, managing user requests. 2. DBT Semantic Layer: Defines the data models, metrics, and relationships. 3. OpenAI LLM (e.g., GPT-3): Used for interpreting natural language inputs and generating SQL queries. 4. PostgreSQL Database: The source of data queried and managed via DBT. Specific Questions: 1. How should I integrate the DBT semantic layer within the Django app? Should the semantic layer be exposed via an API, or is there a more integrated approach? 2. What are the best practices for using an LLM to generate SQL queries from natural language, especially using the constructs defined in … -
I have some problem in the get number of whishlist and show this?
In the following this error... I have problems getting the number of likes for products and removing likes from the list of favorites. like correctly in the database (add to favorite) but I don't know how to get their number and make it dynamic in JavaScript codes by Ajax. Can you look at my codes and give me the necessary guidance, what should I add or remove? thank you! favorite.py from apps.comment_scoring_favorites.models import Favorite class favoriteProduct: def __init__(self,request) -> None: self.session=request.session favorite_product=self.session.get('favorite_product') if not favorite_product: favorite_product=self.session['favorite_product']=[] self.favorite_product=favorite_product self.count=Favorite.count_favorites_by_session() def __iter__(self): favorite_product=self.favorite_product.copy() for item in favorite_product: yield item def add_to_favorite_product(self,productId): productId=int(productId) if productId not in self.favorite_product: self.favorite_product.append(productId) self.count=Favorite.count_favorites_by_session() self.session.modified=True def delete_from_favorite_product(self, productId): productId=int(productId) self.favorite_product.remove(productId) self.count=Favorite.count_favorites_by_session() self.session.modified=True middleware.py import threading class RequestMiddleware: def __init__(self,get_response,thread_local=threading.local()): self.get_response=get_response self.thread_local=thread_local def __call__(self,request): self.thread_local.current_request=request response=self.get_response(request) return response models.py from middlewares.middleware import RequestMiddleware class Favorite(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE,related_name='favorite_product',verbose_name='کالا') favorite_user=models.ForeignKey(CustomUser, on_delete=models.CASCADE,related_name='favorite_user1',verbose_name='کاربر علاقه مند') register_date=models.DateTimeField(auto_now_add=True,verbose_name='تاریخ درج') def __str__(self) -> str: return f"{self.product} - {self.favorite_user}" class Meta: verbose_name='علاقه' verbose_name_plural='علایق' def count_favorites_by_session(self): request=RequestMiddleware(get_response=None) request=request.thread_local.current_reques session=request.session favorite_product_ids =session.get('favorite_product') return self.objects.filter(product__id__in=favorite_product_ids).count() views.py class ShowFavoriteListView(View): def get(self,request,*args,**kwargs): favorite_list=favoriteProduct(request) context={ 'favorite_list':favorite_list, } return render(request,'csf_app/partials/create_favorites.html',context) def statuse_of_favorite_list(request): favoriteList=favoriteProduct(request) return HttpResponse(favoriteList.count) def add_to_favorite(request): productId=request.GET.get('productId') product=Product.objects.get(id=productId) flag=Favorite.objects.filter( Q(favorite_user_id=request.user.id) & Q(product_id=productId)).exists() if(not flag): Favorite.objects.create( product=product, favorite_user=request.user, ) return HttpResponse('added to favorite lists') … -
Migrate a standalone SQLite 3.12.x database with Django configuration
I'm evaluating the use of django for the migration of a SQLite database to Postgres. The database was not created as a django project, but instead used for other applications. I'm attempting to configure django to do routine migrations of various development SQLite databases to Postgres. I continue to fail with regard django creating the json exports from SQLite. I receive the following error: CommandError: Unable to serialize database: no such table: django_admin_log I have configured my database in settings.py I have run python manage.py inspectdb > models.py for migration tips etc.. Perhaps I'm missing the preconfiguration steps etc...and looking for help. -
Unable to update user profile using PUT method (Django DRF)
I am currently working on a mentor-mentee matching service using Django DRF. I have made a 'users' app and have completed creating users&logging in. But I can't edit user info using PUT method. Here are my project files (models.py, serializers.py, views.py, urls.py, settings.py) 1. models.py # users/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator class User(AbstractUser): is_mentor = models.BooleanField(default=False) profile_pic = models.ImageField(upload_to='profile_pics/', default = 'default.png') # profile_pic dir 만들기, default이미지 업로드하기, 사진 첨부 루트 만들기 name = models.CharField(max_length=50, verbose_name= ("이름")) birth_date = models.DateField(verbose_name= ("생년월일"), null=True, blank=True) agreed_to_terms = models.BooleanField(default=False, verbose_name= ("이용약관 동의")) @property def role(self): return "Mentor" if self.is_mentor else "Mentee" class Interest(models.Model): INTEREST_CHOICES = ( ('belief', '가치관'), ('finance', '재테크'), ('love', '사랑'), ('daily', '생활 지식'), ('relationship', '인간 관계'), ('career', '진로'), ) name = models.CharField(max_length=20, choices=INTEREST_CHOICES, unique=True) def __str__(self): return self.get_name_display() class Mentor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='mentor') interests = models.ManyToManyField(Interest, through='MentorInterest') rating = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)]) total_ratings = models.PositiveIntegerField(default=0) def clean(self): super().clean() if self.interests.count() > 3: raise ValidationError("mentors can choose under 3 interest.") def update_rating(self, new_rating): self.rating = ((self.rating * self.total_ratings) + new_rating) / (self.total_ratings + 1) self.total_ratings += 1 self.save() class MentorInterest(models.Model): mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE) interest = models.ForeignKey(Interest, … -
Django date input format seems not to be accepted
I put a DateField inside a ModelForm, which seems to work fine, if I add new entries to my database. Then I added a page, where I can edit one of those entries. Of course, I am passing the date of the desired entry to the HTML, but the date format is not set as expected. # models.py class SomeModel(models.Model): someDate = models.DateField() description = models.CharField(max_length=100) # forms.py class SomeForm(forms.ModelForm): someDate = forms.DateField(input_formats=["%d.%m.%y"], label="Some Date") class Meta: model = SomeModel widgets = { "someDate": forms.DateInput(format=("%d.%m.%y")) } # views.py def someModel_edit(request: HttpRequest, id: int): # ... query = SomeModel.objects.get(id=id) form = SomeForm(instance=query) args = { 'form': form } return render(request, 'SomeHtml.html', args) {% extends 'base.html' %} {% block content %} <h2>Edit Model</h2> <form action="{% url 'someModel_edit' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" name="edit-someModel" value="Edit"> </form> {% endblock %} I expect the format of the date in the edit page to be as I configured in the forms.py file (e.g. 12.08.2024). Sadly it always looks like this: And even worse, if I edit the description of the model entry and hit save, the software tells me, that I use the wrong date format. -
How to automatically create a user in django
I'm trying to create an application form so that people who would like to work for us can apply to our organization. I had a conversation with my client and he doesn't want new employees to create their own user login info. Instead, he wants me to create an admin page where he'll accept or decline applicants. If he accepts an applicant, it'll automatically create user login info, and email that applicant their login info. The user will of course be able to change their login info once they enter their account. How can this be done? I tried to create a signup sheet, but that ended up creating a user before the admin accepted the applicant. User = get_user_model() class InterpreterCreationForm(UserCreationForm): address = forms.CharField(widget=forms.Textarea) phone_number = forms.CharField(max_length=15) ssn = forms.CharField(max_length=15, required=False) languages = forms.ModelMultipleChoiceField(queryset=Language.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.is_interpreter = True if commit: user.save() interpreter = Interpreter( user=user, address=self.cleaned_data['address'], phone_number=self.cleaned_data['phone_number'], ) interpreter.save() interpreter.languages.set(self.cleaned_data['languages']) return user -
How to connect to PostgreSQL DB on PythonAnywhere?
I uploaded a site that is the basic Django "Hello World" site with a few changes. For one thing, the DB is configured to use Postgres. This works fine locally but I am having trouble understanding how to complete the setup on PythonAnywhere. On PA the DB was set up using psql as follows: CREATE DATABASE domain_db; CREATE USER domain_admin WITH PASSWORD '123456789'; \connect domain_db; CREATE SCHEMA domain_schema AUTHORIZATION domain_admin; -- Settings recommended by Django documentation ALTER ROLE domain_admin SET client_encoding TO 'utf8'; ALTER ROLE domain_admin SET default_transaction_isolation TO 'read committed'; ALTER ROLE domain_admin SET timezone TO 'UTC'; Note that this approach is based on recommendations due to changes to Postgres permissions changes with v15 (which is what we are using locally). I am assuming that this works with v12, which is what I think PA is using. Could be wrong on that. https://gist.github.com/axelbdt/74898d80ceee51b69a16b575345e8457 https://www.cybertec-postgresql.com/en/error-permission-denied-schema-public/ The project directory structure looks like this: domain/ site/ _config/ settings/ base.py Settings common to local and production local.py Local development settings production.py Production server settings asgi.py urls.py wsgi.py staticfiles/ manage.py venv .env In base.py I configure the database using environment variables loaded from the .env file. I have confirmed that the .env file is … -
Running a django app on an apache server with Xampp
I am a junior dev and have landed my first role but have no one here to ask questions to. I have been tasked with migrating our company app from the current server to a new server. I have been doing some research and looking through our code to orient myself with their system design. They are currently running their app directly from their server. I know nothing about server config. From my research i found the mod_wsgi is used and have found the httpd.conf file and saw that it is point to the project folder on the C:/. Can anyone walk me through the process of setting up a new server and what files i need to configure? Currently they have it setup on an apache server which is controlled by xampp (all new to me). I haven't toyed around with things too much because i changed branches the other day and their entire program companywide stopped working. So i dont want to start breaking things until i am sure i can recover it. -
KQL Query Formatting/Prettify Library
I am running a Django web app and would like to show some KQL query to the user. However, the query is in a single line, and I would like to format/prettify it. How can it be done? Do I really have to run a separate server running Node.js that than can prettify the code? Can I use the js files in @kusto/monaco-kusto or @kusto/language-service-next to prettify and syntax highlight the KQL queries on my web app? -
Can't load page..... page not found error?
When I load the pages in my project Django keeps showing me a page not found error. I have already written the views and their corresponding urls in the views.py and urls.py files and it is still saying that the page is not found when I load it. My index file is not affected by this error, but when I want to access other files the error popes up I ran manage.py runserver to load the index page but when I want to access the other pages through the nav-bar the error pops up