Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configuration files error after trying to deploy a Django App on AWS Elastic Beanstalk
I have a simple (no database) website made with Django that i'm trying to deploy on AWS Elastic Beanstalk. I got a WARN error : "Configuration files cannot be extracted from the application version toulouse-psy-emdr-v2. Check that the application version is a valid zip or war file." I don't find any explanation about it. I followed a tutorial for the .ebextensions file, my zip file is valid. The rest is successful. The application doesn't work and I get a 502 Bad Gateway error. I found people talking about it, but no clear solution. Does anybody have ever had that error ? What can I do ? I ckecked my .ebextensions file and the django.config inside. It looks like this : option_settings: aws:elasticbeanstalk:container:python: WSGIPath: cabinet_psycho.wsgi:application -
Django test fails to create correct test DB, even main DB works fine
I have app "Invoice" with two models "Invoice" and "InvoicePDFTemplate". I wanted to add fields "terms" on both of them. With model Invoice everything went good, but I have problems with PDFTemplates: makemigrations and migrate worked fine - new column was created in DB, I successfully developed code needed. but when i ran test invoice - it failed as it seems that tests DB does not apply correctly migrations: Using existing test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column invoice_invoicepdftemplate.terms does not exist LINE 1: ...fault", "invoice_invoicepdftemplate"."is_active", "invoice_i... I've tried to change fields, delete migrations and recreate it. It does not solve the problem. I cannot understand why one model works fine and other does not. And I cannot skip test as it is a part of CI/CD. could you suggest any solution? -
I have created an html form but I want to make my website automatically create a dashboard from the inputted data from the form [closed]
Please how someone should kindly help me with the source code I've created the html form and need to create a dashboard from the inputted data from the form I would be so grateful if someone could put me through and send the source code -
Django time data '2024-02-15' does not match format '%Y/%m/%d '
I'm having problems to strip a date: pFecha = datetime.strptime(pFechaDesde, '%Y/%m/%d') Where: pFechaDesde = '2024-02-15' The date was got from a input type date Thanks. -
Getting 403 error when sending a POST request Angular
I am getting status code 403 error when sending post requset to server in django, the server is runing on locallhost, in postman the post request is working, What is the reason of occuring error My auth.service.ts file getUser():Observable<any>{ const token = localStorage.getItem('jwt'); if(!token){ return throwError('Unauthorized') } const headers = new HttpHeaders({ 'Content-Type':'application/json', 'Authorization': 'Bearer' + token }); return this.http.get<any>(this.apiUrl_User, {headers}) } Backend part in django class UserView(APIView): def get(self,request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token, 'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user = User.objects.filter(id = payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) here is corsheaders looks like CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = [ "http://locallhost:4200", "127.0.0.1" ] CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOW_HEADERS = ( "accept", "authorization", "content-type", "user-agent", "x-csrftoken", "x-requested-with", ) -
How do I link a ready-made input to a django form?
I am making a payment system website, it is necessary that the Django form is linked to a ready-made html form, {{form.as_p}} I cannot use it, what can I do here?enter image description hereenter image description hereenter image description here I couldn't find anything in the documentation about this -
Not able to show the form on my modal - Django
I am trying to get my modal to contain a form that can add a task to a to-do list. I have not made changes for the form to work yet. I just want the form to show up on my modal. This is a to-do list website I'm making, and I want to have a modal into which I can directly enter my task details through the modal in my navbar dropdown. Any help is much appreciated views.py: from django.shortcuts import render from .models import to_do from .forms import AddTaskForm def add_task(request): form = AddTaskForm() return render(request, 'navbar.html', {'form': form}) models.py from django.db import models class to_do(models.Model): title = models.CharField('Title', max_length=120) description = models.TextField(blank=True) created_on = models.DateTimeField('Created On') due_by = models.DateTimeField('Due By') status = models.BooleanField('Status', default=False) def __str__(self): return self.title forms.py from django import forms from django.forms import ModelForm from .models import to_do class AddTaskForm(ModelForm): class Meta: model = to_do fields = ("title", "description", "created_on", "due_by") urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('to-do', views.to_do_list, name='list'), ] navbar.html {% load static %} <nav class="navbar navbar-expand-lg bg-tertiary nav justify-content-center" style="background: linear-gradient(to top, #5A99FF, #3D5AFE);"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" … -
Django REST Framework Authentication access problems
I got problems with authentication. I will describe my problem in steps i made to help you understand better what the problem i got. I'm new in Django, so my code may look like trash. Firstly, i create user by using my custom user model. class CustomUserManager(BaseUserManager): def create_user(self, email, username, password=None, **extra_fields): if not email: raise ValueError('The email field must be set') email = self.normalize_email(email) user = self.model(email=email, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractUser, PermissionsMixin): email = models.EmailField(unique=True) password = models.CharField(max_length=128) username = models.CharField(max_length=30, unique=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) # Это поле определяет, активен ли пользователь (False - учетная запись деактивирована) is_active = models.BooleanField(default=True) # Это поле указывает, является ли пользователь членом персонала (в нашем случае - бустером) is_staff = models.BooleanField(default=False) objects = CustomUserManager() # Это поле определяет, какое поле будет использоваться для входа в систему вместо стандартного username USERNAME_FIELD = 'email' # Список полей, которые будут требоваться для создания пользователя с помощью команды createsuperuser REQUIRED_FIELDS = ['username'] def __str__(self): return self.email I use this url, view and serializer to create new user path('api/v1/register/', UserRegistrationView.as_view(), name='user-registration'), class UserRegistrationView(CreateAPIView): serializer_class = UserRegistrationSerializer permission_classes = [permissions.AllowAny] def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() … -
Problem Deploying Django Site on AWS ElasticBeanstalk
I am attempting to deploy a Django site on AWS ElasticBeanstalk for the first time. Using the CLI, when I run "eb create" I get the following error when it begins deployment via CodeCommit: Starting environment deployment via CodeCommit ERROR: TypeError - expected str, bytes or os.PathLike object, not NoneType My .git/config: [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true precomposeunicode = true [remote "origin"] url = https://github.com/user/repository.git fetch = +refs/heads/*:refs/remotes/origin/* [credential] UseHttpPath = true helper = !aws codecommit credential-helper $@ [remote "codecommit-origin"] url = https://git-codecommit.us-east-1.amazonaws.com/v1/repos/siterepos fetch = +refs/heads/*:refs/remotes/codecommit-origin/* pushurl = https://git-codecommit.us-east-1.amazonaws.com/v1/repos/siterepos My .elasticbeanstalk/config.yml: branch-defaults: main: environment: null group_suffix: null global: application_name: company branch: main default_ec2_keyname: company-eb default_platform: Python 3.9 running on 64bit Amazon Linux 2023 default_region: us-east-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: siterepos sc: git workspace_type: Application Any ideas to get this to work? -
My Class Based View(Django) code cant recognize id from SQL database
I tried to make a training project with forms. I wanted to create a code for upgrading feedbacks in the form by Class Based Views. views.py class UpdateFeedbackView(View): def get(self, request, id_feedback): feed = get_object_or_404(Feedback, id=id_feedback) form = FeedbackForm(instance=feed) return render(request, 'form_project/feedback.html', context={'form': form}) def post(self, request, id_feedback): feed = get_object_or_404(Feedback, id=id_feedback) form = FeedbackForm(request.POST, instance=feed) if form.is_valid(): form.save() return HttpResponseRedirect(f'/{id_feedback}') else: form = FeedbackForm(instance=feed) return render(request, 'form_project/feedback.html', context={'form': form}) urls.py path('<int:id_feedback>', views.UpdateFeedbackView.as_view()) html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static 'feedback/field.css'%}"> </head> <body> <h2>Оставьте отзыв</h2> <form method="post"> {% csrf_token %} {% for field in form %} <div class="form-style"> {{ field.errors }} {{ field.label_tag }} {{ field }} </div> {% endfor %} <button type="submit">Отправить</button> </form> </body> </html> When i try to type an feedback's id, i get this error TemplateDoesNotExist at /1 The code thinks that id does not exist. However i tried to write the same upgrade code by simple function and it worked well. By debugger, i realised that problem is in GET method but can't understand why. What did i wrong or miss? -
django-allauth: redirect on log-in to sign-up page if social account exists
I want to create a Google Login authentication method in my Django project. So, when a user visits my website for the first time, it will create a new user in my database and then login that user. In case a user with this email address already exists, that user will simply log in. The first part of my goal works as expected (when a user visits my website for the first time, it will create a new user in my database and then login that user), but If I'm trying to log in as an existing user, django-allauth redirects me to /accounts/social/signup/ I've tried to fix it with a CustomSocialAccountAdapter, but it didn't really help me. Could you help me please to resolve my problem? Here is my settings.py : # allauth AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] SOCIALACCOUNT_PROVIDERS = { "google": { "APP": { "client_id": os.environ.get("GOOGLE_CLIENT_ID", ""), "secret": os.environ.get("GOOGLE_CLIENT_SECRET", ""), }, "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "offline", }, }, } ACCOUNT_LOGIN_REDIRECT_URL = "home" ACCOUNT_LOGOUT_REDIRECT_URL = "home" SOCIALACCOUNT_LOGIN_ON_GET = True SOCIALACCOUNT_LOGOUT_ON_GET = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = None SOCIALACCOUNT_AUTO_SIGNUP = True ACCOUNT_LOGOUT_ON_GET = True SOCIALACCOUNT_ADAPTER = … -
Websocket with Django Channels and IIS - No route found for path
I'm trying to deploy my Django application to my IIS server, but my websocket doesn't work when accessing via IIS, only locally. What did I miss? When I access via IIS: new WebSocket('ws://server:8000/ws/notificacoes') -> error 1006 Log: ValueError: No route found for path 'ws/notificacoes' When I access via python runserver: new WebSocket('ws://http://127.0.0.1:8000/ws/notificacoes') -> connected Log: WebSocket HANDSHAKING /ws/notificacoes [127.0.0.1:53541] WebSocket CONNECT /ws/notificacoes [127.0.0.1:53541] consumers.py class NotificacaoConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'notificacoes' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def notificacao_update(self, event): await self.send(text_data=json.dumps({ 'message': 'Notificação atualizada!' })) routing.py websocket_urlpatterns = [ ... path('ws/notificacoes', NotificacaoConsumer.as_asgi(), name='notificacao'), ] asgi.py from index.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) -
Error in Django - [WinError 3] The system cannot find the path specified - Django
The problem is: Im trying to let users upload 5 images and on uploading I want them to change directory. So far my views.py class ProductCreateView(LoginRequiredMixin, CreateView): template_name = "product/add_product.html" success_url = reverse_lazy('home') form_class = ProductForm login_url = "/login/" # Save current user id as product_user_id in DB def form_valid(self, form, **kwargs): form.instance.product_user_id = self.request.user.id response = super().form_valid(form) id = form.instance.id picture_1 = form.instance.product_img_1 picture_2 = form.instance.product_img_2 picture_3 = form.instance.product_img_3 picture_4 = form.instance.product_img_4 picture_5 = form.instance.product_img_5 product_title = form.instance.product_title user = form.instance.product_user_id # Change directory new_directory = change_directory(id, product_title, user, picture_1, picture_2, picture_3, picture_4, picture_5) return new_directory utils.py def change_directory(id, product_title, user, picture_1, picture_2, picture_3, picture_4, picture_5): file_name = f"{id}-{product_title}-{product_title}-{user}" new_path = os.path.join(settings.MEDIA_ROOT, "product_images", file_name) if not os.path.exists(new_path): os.makedirs(new_path) picture_list = [picture_1, picture_2, picture_3, picture_4, picture_5] for i in picture_list: old_image_path = os.path.join(settings.MEDIA_ROOT, f"product_images/{i}") new_image_path = os.path.join(settings.MEDIA_ROOT, f"product_images/{file_name}/{i}") os.rename(old_image_path, new_image_path) return new_path The solution is not far away, but im out of ideas. If this helps: models.py class Product(models.Model): product_title = models.CharField(max_length=255) product_description = models.TextField() product_description_short = models.CharField(max_length=255, blank=True) product_condition = models.CharField(max_length=100) product_code = models.CharField(max_length=100, blank=True) product_manufacturer = models.CharField(max_length=100, blank=True) product_location_state = models.CharField(max_length=100) product_location_city = models.CharField(max_length=100) product_delivery_time = models.IntegerField() product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, related_name='products') product_img_1 = models.ImageField(upload_to="product_images", blank=True) product_img_2 = … -
celery apply_async returning missing argument error
I have a celery function with definition - @async_worker.task(ignore_result=True, queue="data_path") def publish_msg_from_lock(self, mac: str, data: bytes, gateway_euid: str): previously it wasn't a celery task it was being called like this - n.publish_msg_from_lock(addr, unhexlify(payload), gateway_euid) After making it a celery task I updated the call in this way - n.publish_msg_from_lock.apply_async(args=(addr, unhexlify(payload), gateway_euid),) I've also tried - n.publish_msg_from_lock.apply_async(args=(addr, unhexlify(payload), gateway_euid), kwargs={}) and n.publish_msg_from_lock.apply_async(kwargs={"mac": addr, "data": unhexlify(payload), "gateway_euid": gateway_euid}) But I'm getting error - ** File "/usr/local/lib/python3.8/dist-packages/celery/app/task.py", line 531, in apply_async check_arguments(*(args or ()), **(kwargs or {})) TypeError: publish_msg_from_lock() missing 1 required positional argument: 'gateway_euid' ** Can you please help to fix it? -
Multi Tenancy with Multiple Users Multi Multi Tenancy
Hello I am working on an a project where multi-tenancy is needed. In my case tenant is a company and with in that company you ll have multiple users. Lets say our company is called abc and our domain is domain.com. So abc.domain.com reaches the abc's resources. Now should each request check to see if subdomain is valid at application server level given that our dns is registered as *.domain.com (for simplicity lets forget about www as a domain) or should you explicitly register each subdomain (In this case is the registration of subdomains instant) IS this a common practice to actually write a script that adds the each subdomain explicitly. Starting a new tenant would take a lot longer I think. but if a wildchar is used you would need to make sure that that domain exists, so maybe a DB request is necessary or alternatively maybe you can attach the domain to your token or jwt or whatnot. How do one go about handling the domains ? -
Access to XMLHttpRequest from origin has been blocked by CORS policy
I have backend on Django 4 and frontend on Angular. Django started on 192.168.1.195:8080. Angular on the 192.168.1.195:4200 When i try to open http://192.168.1.195:4200 i got Home:1 Access to XMLHttpRequest at 'http://192.168.1.195:8080/api/hosts_groups' from origin 'http://192.168.1.195:4200' has been blocked by CORS policy: Request header field pragma is not allowed by Access-Control-Allow-Headers in preflight response. settings.py ALLOWED_HOSTS = ['192.168.1.195','127.0.0.1','localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'host_manager.apps.HostManagerConfig', # CORS 'corsheaders', ] CORS_ALLOWED_ORIGINS = ( "http://192.168.1.195:4200", 'http://127.0.0.1:4200', 'http://localhost:4200' ) CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'http://192.168.1.195:8080', 'http://192.168.1.195:4200', 'http://127.0.0.1:4200', 'http://localhost:4200', 'http://127.0.0.1:8080', 'http://localhost:8080' ) CORS_ALLOW_HEADERS = ( 'Access-Control-Allow-Headers', 'Access-Control-Allow-Credentials', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Methods' ) MIDDLEWARE = [ # CORS 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Where i'm wrong? -
Error when passing file content to Celery task: "Object of type InMemoryUploadedFile is not JSON serializable"
Description: I'm encountering an error when trying to pass file content directly to a Celery task in a Django application. The error message I'm getting is: "Error: Object of type InMemoryUploadedFile is not JSON serializable" API View: class TradeMappingView(APIView): parser_classes = (MultiPartParser,) def post(self, request, format=None): serializer = InputSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) file_content = serializer.validated_data['file'] column_mapping = serializer.validated_data["column_mapping"] merge_columns = serializer.validated_data.get("merge_columns", {}) values_to_replace = serializer.validated_data.get("values_to_replace", {}) try: synchronizer.delay( file=file_content, file_type="trade", columns_to_rename=column_mapping, merge_columns=merge_columns, values_to_replace=values_to_replace, ) return Response("Trades synchronization started successfully.", status=status.HTTP_202_ACCEPTED) except Exception as e: return Response(f"Error: {e}", status=status.HTTP_500_INTERNAL_SERVER_ERROR) Celery Task: @shared_task def synchronizer(file, file_type, columns_to_rename=None, values_to_replace=None, merge_columns=None): try: synchronizer_instance = Synchronizer( file=file, file_type=file_type, columns_to_rename=columns_to_rename, values_to_replace=values_to_replace, multiple_sheets=None, merge_columns=merge_columns ) synchronizer_instance.run() except Exception as e: raise synchronizer.retry(exc=e) I've noticed that the error occurs even though the data passed to the Celery task passes the validation of the InputSerializer. How can I resolve this error and successfully pass the file content to the Celery task? -
I am trying to use Zustand but I will get an error
import { create } from 'zustand'; import { mountStoreDevtools } from 'simple-zustand-devtools'; const useAuthStore = create((set, get) =>({ allUserData: null, loading: false, user: () => ({ user_id: get().allUserData?.user_id || null, username: get().allUserData?.username || null, }), setUser: (user) => set({ allUserData: user}), setLoading: (loading) => set({loading }), isLoggedIn: () => get().allUserData !== null, })) if (import.meta.env.DEV){ mountStoreDevtools(useAuthStore, 'AuthStore'); } export default { useAuthStore} Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/simple-zustand-devtools.js?v=0062664c' does not provide an export named 'mountStoreDevtools' (at auth.js:2:10) -
How to keep checkboxes selected and count after navigating to another page in using a select all function - ReactJS
I have a react app that contains a table that is populated with records from Django through rest-API. The app have a function that can select all checkboxes of each record from the table using a main checkbox in the header. I am looking if it is possible to keep the checkboxes checked and keep the count after navigating to another page. Here are the snippets for selectAllHandler, selectOnHandler and the selected counter which counts the number of checkboxes selected. const selectAllHandler = (e) => { const toggleAll = e.target.checked; const updatedCheckBoxes = {}; const newCheckBoxes = {}; accounts.forEach((account) => { updatedCheckBoxes[`ch${account.id}-${account.compliant}`] = toggleAll; }); setCheckBoxes(updatedCheckBoxes); for (let cbox in checkBoxes) { newCheckBoxes[cbox] = toggleAll; } setCheckBoxes(newCheckBoxes); setSelectAll(toggleAll) }; const selectOneHandler = (e) => { const target = e.target; const value = target.checked; const name = target.name; const newCheckBoxes = { ...checkBoxes, [name]: value }; const toggleAll = Object.values(newCheckBoxes).every((chk) => chk); const someChecked = Object.values(newCheckBoxes).some((chk) => chk); setCheckBoxes(newCheckBoxes); setSelectAll(toggleAll || (someChecked && !value)); }; const selectedCount = Object.values(checkBoxes).filter(Boolean).length; Here is how the records are populated const getAccount = async () => { const data = await axios .get("accounts/api/get-accounts/", { params: { page: pageParam, order: order, field: fieldOrder, search_field: searchField, search_value: … -
Celery tasks runs multiple times in a load balanced environment
I have a django project that deployed in a load balanced environment. there are some periodic celery tasks in my project, but they are executing twice at the time that they should execute. what is the problem? this is my tasks: from my_project.celery import app from django_redis_task_lock import lock import sentry_sdk @app.task() @lock('test_task6') def test_task_6(): sentry_sdk.capture_message(this task runs every 4 minutes starting at 17:46 PM time = {timezone.now()}') this is the schedule for this task -
Change a MultipleChoiceField to only be able to select one choice at a time
so I am currently working on a program in Django that uses MultipleChoiceFields, I only want to be able to select one choice at a time within the bounds of my code. How exactly would I be able to change my MultipleChoice field to accomplish this goal, and what attributes would I need to add? I have tried looking into documentation as well as some questions here as well for how one could modify the MultipleChoiceField function as seen here: https://www.geeksforgeeks.org/multiplechoicefield-django-forms/ https://groups.google.com/g/django-users/c/faCorI1i8VE?pli=1 Show multiple choices to admin in django But I have found no attributes to help me limit the size of the answers one could pick out to just one answer, or the answers are unrelated to the problem I am seeking to solve. Here is my code as well which also has the MultipleChoiceFields that I am trying to have select only one option: class ArdvarkForm(forms.ModelForm): class Meta: model = Course fields = ('is_done',) score_visual = forms.IntegerField(widget=forms.HiddenInput()) score_kinestetic = forms.IntegerField(widget=forms.HiddenInput()) score_auditory = forms.IntegerField(widget=forms.HiddenInput()) question1options = (('1', 'Read the instructions.'), ('2', 'Use the diagrams that explain the various stages, moves and strategies in the game.'), ('3', 'Watch others play the game before joining in.'), ('4', 'Listen to somebody explaining … -
displaying choice in django admin
im making a reservation app, i want one of the ways to see the data being in the admin panel but right now i can see everything except for the time, i think it is because its a choice field and in the admin it appears like it wasnt chosen. models.py class Reservation(models.Model): name = models.CharField(max_length=50) people = models.IntegerField() date = models.DateField() time_choice = ( (times_available[0], times_available[0]), (times_available[1], times_available[1]), (times_available[2], times_available[2]), (times_available[3], times_available[3]), (times_available[4], times_available[4]), (times_available[5], times_available[5]), (times_available[6], times_available[6]) ) time = models.CharField( max_length= 7, blank= True, null= True, choices= time_choice ) phone = models.IntegerField() def __str__(self): return self.name views.py def reservar_mesa(request): reserve_form = FormReservarMesa() if request.method == 'POST': reserve_form = FormReservarMesa(request.POST) if reserve_form.is_valid(): reserve_form.save() reserve_form = FormReservarMesa() return HttpResponseRedirect("/home/") context = {'form' : reserve_form} return render(request, 'reservas.html', context) my admin.py is the deafault. i checked and the value is being stored in the database -
I can't use templates for HTML in VS code in a project with jango and vs code doesn't close the tag
enter image description here enter image description here I can't use templates for HTML in VS code in a project with jango using the "! + tab" combination, because vs code thinks it's a different file than html Also vs code doesn't close the tag. If I put "(", vs code puts automatically ")", but there is no such thing with "<". I remember it used to be possible to do that. enter image description here enter image description here I tried different extensions, tried changing the settings a little bit. -
how can i update two model table fields at one request in django rest api
i have two tables called user and address. the address table have a foreign key relation with the user table. so how access the fields of both table and update it in a single request call { "first_name": "abijith", "last_name": "manu", "profile_picture": "http://127.0.0.1:8000/media/profile_pictures/my_pic_RxnXQ6n.jpg", "date_of_birth": "2024-02-16", "username": "", "gender": "male", "email": "doc@gmail.com", "phone_number": "7306986870", "addresses": [ { "street": "xvsvf", "city": "sss", "state": "ssss", "country": "ggggggggg", "zip_code": "sssssss" } ] this is the sample form of response that i want. and i have to update the filed as well -
How to resolve: Django, Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
I have dockerized a django app. And when I start the container the login screen apears. But after login. I get this message: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Of course there is a lot of information available on the internet. But I think, I have set everything correct - settings.py, docker-compose.yml, env file. So that is why I ask. I have the docker-compose file like this: version: "3.9" services: web: image: crdierenwelzijn.azurecr.io/web1 build: context: ./ dockerfile: Dockerfile.prod restart: always command: gunicorn DierenWelzijn.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env proxy: image: crdierenwelzijn.azurecr.io/proxy1 build: context: ./proxy restart: always depends_on: - web ports: - 80:80 volumes: - static_volume:/home/app/staticfiles - media_volume:/home/app/media volumes: static_volume: media_volume: and settings.py file: SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = bool(int(os.environ.get('DEBUG', 1))) ALLOWED_HOSTS = ['localhost', '127.0.0.1', '192.168.1.135', '10.0.2.2', '10.14.194.138', '0.0.0.0', 'dockerwelzijn.azurewebsites.net', 'welzijndocker.azurewebsites.net', 'https://welzijndocker.azurewebsites.net'] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(" "), ) ) # SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") CSRF_TRUSTED_ORIGINS = [ "https://dockerwelzijn.azurewebsites.net", "https://welzijndocker.azurewebsites.net", "http://0.0.0.0:8000", "http://10.0.2.2:8000", "http://localhost:8000", "http://10.14.194.138:8000", …