Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django_celery_results Logs Spill Secrets
I am using Celery tasks with my Django application. It has been configured to use django_celery_results as a backend for logging task results. I am however experiencing some issues. The connection between the broker, Django and Celery is secure. This is no issue. I am sending mails with celery, I am not storing the credentials on the celery side, nor is it possible to do so as they are provided dynamically. However, the credentials I pass to the celery task get logged by django_celery_results. Is there a way to omit these credentials from the task results? I have though about encrypting before sending it to the celery task, but maybe there is a better way. -
Django with multiple websites, shared apps, one domain, Apache server
The goal is to have several websites running on one domain, with Apache and wsgi What I currently have is one virtualhost configuration: WSGIScriptAlias /site1 /opt/django/wsgi.py process-group=site1 Since there is only one project, there is only one wsgi.py, so all apps are running under domain.com/site1, i.e. site2 is available at domain.com/site1/site2 which is not what I want. The desired config is : site1 reachable at domain.com/site1 site2 reachable at domain.com/site2. Also, there are some shared apps between site1 and site2. project/urls.py configuration: path('', include(('site1.urls', 'site1'), namespace='site1')), path('/site2', include(('site2.urls', 'site2'), namespace='site2')), -
How do I log out any user when using the cache session backend?
I am building a form into django admin where I can submit a user id and the system is expected to log the user out. I cannot do django.contrib.auth.logout() because it does not take a user id as a parameter. I also cannot query against django.contrib.sessions.models.Session because I am using the django.contrib.sessions.backends.cache session engine. -
custom id not showing up in paypal webhook
So I'm trying to put in a custom id (order id) in my paypal order so it get's returned to me in my paypal webhook but I cannot find it in my webhook. This is my order code. payment = paypalrestsdk.Payment({ "intent":"sale", "payer":{ "payment_method":"paypal" }, "redirect_urls":{ "return_url":"http://localhost:3000/order/success", "cancel_url":"http://localhost:3000/order/cancel" }, "transactions":[{ "item_list":{ "items":items }, "amount":{ "total":price, "currency":"EUR" }, "description":"This is the payment transaction description.", "custom_id": order_data["products"][0]['order'] }] }) if payment.create(): return JsonResponse({'status': 'success', "url": payment.links[1].href}) else: return JsonResponse({'status': 'error'}) Everything in this code works except for the custom id which i dont get back in my webhook. Am I missing something. Extra note. Just tried this. payment = paypalrestsdk.Payment({ "intent":"sale", "payer":{ "payment_method":"paypal" }, "redirect_urls":{ "return_url":"http://localhost:3000/order/success", "cancel_url":"http://localhost:3000/order/cancel" }, "transactions":[{ "item_list":{ "items":items }, "amount":{ "total":price, "currency":"EUR" }, "description":"This is the payment transaction description." }], "custom_id": order_data["products"][0]['order'] }) if payment.create(): return JsonResponse({'status': 'success', "url": payment.links[1].href}) else: return JsonResponse({'status': 'error'}) I moved the custom id out of the transactions key, it was an oversight of me but now my payment does not get created in the browser I receive {status: error} instead of the payment url of paypal. All help is greatly appreciated -
How do I avoid django URL KeyError but keep my site's URL struture?
I am new to programming with Django and recently started a Django web app with only one "food" app/section that leads to the food app URLs so my base url.py looks similar to this. urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('', include('food.urls')), ] Now I want to add/include a new "water" section for the water app urls.py similar to this urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('', include('food.urls')), path('', include('water.urls')), ] However, when I click on the water URLs I get a KeyError as the water URLs are being applied to the food.urls. My web app is already in production and I don't want to change the URL structure as this is bad for SEO. Therefore, what is the best solution to keep the current URL structure for both the food.urls and water.urls? For example, mysite.com/a-food-url and mysite.com/a-water-url. or is the only solution to change the URL structures to: urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('food/', include('food.urls')), path('water/', include('food.urls')), ] where the URLs will be mysite.com/food/a-food-url and mysite.com/water/a-water-url? -
How to use transaction with async function in Django?
Here is code class Utils: @sync_to_async def get_orders(self): orders = Order.objects.all() return [orders] @sync_to_async def get_sellers(self): sellers = Seller.objects.all() return [sellers] class Orders(View, Utils): async def get(self, request): orders = asyncio.ensure_future(self.get_orders()) await asyncio.wait([orders]) print(orders.result()) return render(request, 'orders.html') Here is logs of error Traceback (most recent call last): File "C:\Хранилище говна\pythonProject1\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner File "C:\Хранилище говна\pythonProject1\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Хранилище говна\pythonProject1\venv\lib\site-packages\django\core\handlers\base.py", line 192, in _get_response wrapped_callback = self.make_view_atomic(callback) File "C:\Хранилище говна\pythonProject1\venv\lib\site-packages\django\core\handlers\base.py", line 350, in make_view_atomic raise RuntimeError( RuntimeError: You cannot use ATOMIC_REQUESTS with async views. I'm trying to get list of orders from database(PostgreSQL) in async function, but it rasie RuntimeError. I tried to detect where this code raise error by debuging, but "get" function in Orders didn't call at all. Tried find info in django docs, no info. Can some one help me with this one? -
couldn't serve static file for a django app (apache - wsgi )
i have the projected is named Portfolio which is my main page. And i have created an app named experiences on this project. On dev server i'm able to serve static files for both. but on production, i'm only able to serve for main page (project) and not for the app. I have the 404 Not Found error. i have make the collecstatic. I have a static dir on each app (and project). And i'm using apache with wsgi module. i have this conf on settings file : STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "Portfolio/static") ] Below the arch : src/ |-- Experiences | |-- __pycache__ | |-- migrations | | `-- __pycache__ | |-- static | | `-- Experiences | | |-- assets | | | |-- fonts | | | `-- img | | `-- css | `-- templates | `-- Experiences |-- Portfolio | |-- __pycache__ | |-- static | | `-- Portfolio | | |-- assets | | | |-- fonts | | | `-- img | | `-- css | `-- templates | `-- Portfolio `-- staticfiles |-- Experiences | |-- assets | | |-- fonts | | `-- … -
Getting "field does not exist" when running pytest
I added a slug field to a model and re-created the migrations from the initial one. When I try to run a unit test for this model, I always get the django.db.utils.ProgrammingError: column courses_course.slug does not exist. I tried to undo the migration with the code below, but it still doesn't work. python manage.py migrate courses zero python manage.py migrate -
Select a valid choice. That choice is not one of the available choices with django
Hi guys basically I'm working with a license generator with django, i have a javascrit logic so that i can filter users by company name and create licenses for those users, i would like to add an option "select all users" so that i can create multiple licenses for all the users in a specific company, i have something like this: I use dropdowns for the companies and the users {% extends "main_page_layout.dj.html" %} {% block content %} <div class="control"> <a href="/user/management/"> <div class="button">Generate user</div> </a> </div><br> <form action="/avt/generate/" method="post" id="avt-form" data-users-url="{% url 'load_users' %}" >{% csrf_token %} <div class="field"> <label class="label">Company</label> <div class="control"> <div class="is-fullwidth"> <select class=" select2 {% if form.errors.company %} is-danger {% endif %} " type="text" name="company" id="company" value="value={{form.company.name}}">> <option value=" ">Select a company first</option> {% for company in companies %} <option>{{ company.name }}</option> {% endfor %} </select> </div> </div> </div> {% if form.errors.company %} <p class="help is-danger">{{ form.errors.company }}</p> {% endif %} {% include 'users_dropdown_list_options.html' %} <div class="field"> <label class="label">Expire Date</label> <div class="control"> <input class="input avt_datepicker {% if form.errors.expire_date %} is-danger {% endif %} " type="text" placeholder="YYYY-MM-DD e.g. '2000-01-01'" name="expire_date" value="{{ form.expire_date.value | default_if_none:'' }}"> </div> {% if form.errors.expire_date %} <p class="help is-danger">{{ form.errors.expire_date }}</p> {% … -
How do I avoid django URL KeyError but keep my site's URL struture?
I started a Django web app with only one "food" app/section that leads to the food app URLs so my base url.py looks similar to this. urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('', include('food.urls')), ] Now I want to add/include a new "water" section for the water app urls.py similar to this urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('', include('food.urls')), path('', include('water.urls')), ] However, when I click on the water URLs I get a KeyError as the water URLs are being applied to the food.urls. My web app is already in production and I don't want to change the URL structure as this is bad for SEO. Therefore, what is the best solution to keep the current URL structure for both the food.urls and water.urls? For example, mysite.com/a-food-url and mysite.com/a-water-url. -
How can I use django-filter's DateTimeFromToRangeFilter with Graphene?
I'm attempting to use an instance of django-filter's DateTimeFromToRangeFilter in conjunction with a custom FilterSet. However, this does not work when I attempt to do the following: class CustomFilterSet(FilterSet): modified = django_filters.IsoDateTimeFromToRangeFilter() class Meta: fields = "__all__" model = Custom This does not result in additional fields or annotations being created, like I'd expect based on the docs. Something like: f = F({'modified_after': '...', 'modified_before': '...'}) If I inspect the single field (modified) which has been added to my DjangoFilterConnectionField, I see the following: {'creation_counter': 395, 'name': None, '_type': <String meta=<ScalarOptions name='String'>>, 'default_value': Undefined, 'description': None, 'deprecation_reason': None} So, how do I configure this filter such that I can write a query like the following? query { allTheSmallThings( modified_before: "2023-09-26 17:21:22.921692+00:00" ) { edges { node { id } } } } -
how i can filter with foregin key
0 I have a football stadium booking site -- the user logs in and then selects the stadium he wants to book and then selects the day and how much he wants to book the canned (an hour or two hours, etc.*) example: user John booked the stadium X on the day of 5 at 10 to 12 I want to make sure that there is no reservation at the same stadium, the same day and the same time, and if there is a reservation at the same data, he does not complete the reservation when i try to filtter in models with Foreign key pitche filter = OpeningHours.objects.filter(made_on=self.made_on,pitche=self.pitche,period = self.period).filter(Q(from_hour__range=in_range) | Q(to_hour__range=in_range)).exists() the error happens (relatedobjectdoesnotexist) OpeningHours has no pitche. my models is : class Pitche(models.Model): Name = models.CharField(max_length=50) city =models.CharField(max_length=50) photo = models.ImageField(upload_to='photos') price = models.DecimalField(max_digits=5,decimal_places=2) location = models.CharField(max_length=500) name_of_supervisor = models.CharField(max_length=50) phone_of_supervisor = models.CharField(max_length=11) manager = models.ForeignKey(Manager,on_delete=models.DO_NOTHING) class OpeningHours(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) pitche = models.ForeignKey(Pitche,on_delete=models.DO_NOTHING) made_on = models.DateField() period = models.CharField(max_length=50,choices=period) from_hour = models.TimeField() to_hour = models.TimeField() timing = models.CharField(max_length=50,choices=timing) def __str__(self): return f"{self.pitche}-{self.from_hour} to {self.to_hour}" def clean(self): if self.from_hour == self.to_hour: raise ValidationError("Wrong Time") if self.made_on <datetime.date.today(): raise ValidationError("InVaild Date") ##################### in_range = (self.from_hour, self.to_hour) filter … -
exec ./start.sh: no such file or directory
I have a Django project that runs in a Docker container within docker-compose.yml with postgresql, pgadmin4 and redis. I have start.sh script that make and run migrations: start.sh: #!/bin/bash # Creating migrations if they are python manage.py makemigrations # Apply migrations python manage.py migrate After building the image and runing docker-compose up command django project give me an error: exec ./start.sh: no such file or directory but my start.sh file is in the same directory where Dockerfile and docker-compose.yml are. PostgreSQL, pgadmin4 and Redis runs successfully. How to solve this problem? My system is Windows 10. Dockerfile: FROM python:3.11.3-alpine ENV PYTHONBUFFERED=1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt --upgrade COPY . . COPY start.sh . RUN chmod +x start.sh ENTRYPOINT [ "./start.sh" ] EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml: services: api: image: meduzzen-backend-api container_name: django tty: true stdin_open: true volumes: - .:/code - ./code:/apps ports: - "8000:8000" depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis postgres-db: image: postgres:latest container_name: postgres_db ports: - "5432:5432" volumes: - data:/var/lib/postgresql/data env_file: - .env networks: api-db-redis: # Have access the database using pgadmin4 ipv4_address: 172.24.0.6 pg-admin: image: dpage/pgadmin4:latest container_name: pg_admin env_file: - .env ports: - "5050:5050" networks: … -
Celery revoke_by_stamped_headers doesn't work into the Django signal
I try to revoke celery task using revoke_by_stamped_headers. When app.control.revoke_by_stamped_headers is inside if block with stamped_task it works. @receiver(post_save, sender=Bet) def send_prepared_notifications(sender, instance, created, *args, **kwargs): """Send prepared push notifications. Args: sender (Bet): The sender. instance (Bet): The instance. created (bool): Whether the instance was created. """ class MonitoringIdStampingVisitor(StampingVisitor): def on_signature(self, sig, **headers) -> dict: return {"bet_id": str(instance.id), "stamped_headers": ["bet_id"]} if created: daily_config = DailyBetConfig.objects.last() bet_added_message, _ = PushMessage.objects.get_or_create( type="bet added", defaults={"title": "Bet added", "body": "Bet added"} ) start_added_bet_progress = instance.start_date_time - timedelta(hours=daily_config.event_added_diff) def start(): stamped_task = send_push_notification_active_devices.s(bet_added_message.title, bet_added_message.body) stamped_task.stamp(visitor=MonitoringIdStampingVisitor()) stamped_task.apply_async( eta=start_added_bet_progress, expires=instance.start_date_time, ignore_result=True, ) transaction.on_commit(lambda: start()) else: app.control.revoke_by_stamped_headers(headers={"bet_id": [str(instance.id)]}, terminate=True, signal="SIGKILL") ` I am expecting to revoke celery task if Bet object is exist. -
Server Error (500) where deploy django app to render
Server Error (500) I only encounter this error when trying to access this page: https://e-courses.onrender.com/course/1/ after uploading it to render. Here is the website link and the repository link on GitHub: website on render: https://e-courses.onrender.com/ repo: https://github.com/HamzaWaleedDV/e_academy settings.py: """ Django settings for academy project. Generated by 'django-admin startproject' using Django 4.2.5. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ import os from pathlib import Path import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)b!9$0$t-985es5kf$xsiw5bek^+wl^5w(&%(ft5f6w6e_xg@w' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['e-courses.onrender.com'] # Application definition INSTALLED_APPS = [ 'accounts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'academy_courses', 'academy_blog', 'tinymce', 'django_cleanup.apps.CleanupConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'academy.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'academy_courses.custom_context_proccessor.slider_footer', 'academy_courses.custom_context_proccessor.category', 'academy_courses.custom_context_proccessor.slider_image', ], }, }, ] WSGI_APPLICATION = 'academy.wsgi.application' # Database … -
django date by month only filter validation err
I need a date filter that selects month only. But it gives "Enter a valid date" error when filter is applied. How to fix it? Thanks in advance. filters.py class OrderFilter(django_filters.FilterSet): date = django_filters.DateFilter( field_name='date', lookup_expr='exact', # You can change the lookup expression if needed widget=forms.DateInput(attrs={'type': 'month'}) ) class Meta: model = Order fields = ['product', 'date'] template <form method="get"> {{ filter.form|crispy }} <input type="submit" name="order_filter" value="Apply"/> </form> views.py filter = OrderFilter(request.GET, queryset=Order.objects.filter(status=True)) -
How to display data from Postgresql query into a Pie ChartJs in Django Framework?
I am working in a Django Project and I would like to show some data from PostgreSql to a Pie ChartJs, but I do not find a way, here my view: from django.shortcuts import render from appclientes.models import Cliente, Municipio from django.db.models import Count Create your views here. def pie_chart_view(request): results = Cliente.objects.values('municipio__nombre_municipio').annotate(clientes_adsl=Count('id')) nombres_municipio = [result['municipio__nombre_municipio'] for result in results] totals = [result['clientes_adsl'] for result in results] print(nombres_municipio,totals) print(results) context = { 'results': results } return render(request, "appclientes/pie_chart.html", context)` `` The QuerySet that I obtained with the sentence print(results) is correct and I here you are my Template where I render the pie: {% load static %} {{ title }} <canvas id="pieChart" width="400" height="100"> <script> var ctx = document.getElementById('pieChart').getContext('2d'); var data = { labels: [{% for result in results %}{{ result.nombre_municipio }}{% endfor %}], datasets: [{ data: [{% for result in results %}{{ result.clientes_adsl }}{% endfor %}], backgroundColor: [ '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', ], }] }; var chart = new Chart(ctx, { type: 'pie', data: data, }); </script> ` But wehe I call the URL it does not show anything just a painted red circle with nothing else. When I inspect in the data appear a number 98343255114 … -
Connecting a Docker-ized Django app to local Postgresql database
For deployment purposes, I have set up my Django app in a Docker container. The setup works, and I am able to serve it using Gunicorn and Apache. However, I can't seem to access my Postgresql database anymore. This database is running locally, and I have no problem accessing it when launching my Django app from outside the container. But when I launch my app from inside the Docker container, all I get is this error: django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5433 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Clearly I am not the first one having trouble with this. I have made sure that Postgresql is listening to external adresses, as stated here, so this shouldn't be a problem. I have also tried playing around with my Docker compose configuration file. Using network_mode=host is not compatible with port bindings. Back in network_mode=bridge, I have also tried as accepted here : extra_hosts: - "host.docker.internal:host-gateway" But it does not change anything, nor does replacing 127.0.0.1 with 172.17.0.0 in my Django .env file. I am a bit at a loss here, so any insight would be appreciated. I have to say that I … -
How to define and increment value of a variable in django template?
I want to define a variable in django template and then increament its value by 1. {% with variable=0 %} {% if some_condition == True %} {{ variable++ }} {% endif %} {% endwith %} For defining the variable, I have figured out that I can use with. How can I increment its value? -
Django LoginRequiredMiddleware continuingly requests reload on the login page
I implemented Django's LoginRequiredMiddleware and it seems to work fine basically. My only problem is, when I'm at the login page I get multiple reload requests per second. In the settings I included the login url and the middleware MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "login_required.middleware.LoginRequiredMiddleware", #<- it's here "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django_htmx.middleware.HtmxMiddleware", "django_browser_reload.middleware.BrowserReloadMiddleware", ] LOGIN_URL = "/login" and this is my view function @login_not_required def login_page( request, ) -> HttpResponseRedirect | HttpResponsePermanentRedirect | HttpResponse: if request.method == "POST": username: str = request.POST.get("username") password: str = request.POST.get("password") user: AbstractBaseUser | None = authenticate( request, username=username, password=password ) if user is not None: login(request, user) return redirect("landingPage", username=username) else: messages.info(request, "Username or password is incorrect!") return render(request, "a[...]/login.html") I can't find a reason why this happens and would prefer it not to happen to reduce traffic for my app. -
Django User model Groups and permissions error abstracteduser
Im busy creating a User model in Django that can Authenticate users for login, im using abstracteduser to create this model put I am constantly getting this error when making the migrations ERRORS: api.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'api.User.groups' clashes with reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'api.User.groups' or 'auth.User.groups'. api.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'api.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'api.User.user_permissions' or 'auth.User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'api.User.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'api.User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'auth.User.user_permissions' clashes with reverse accessor for 'api.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'api.User.user_permissions'. The code I've implemented for it: class User(AbstractUser): #User first name eg. Piet first_name = models.CharField(max_length= 60, validators=[MinLengthValidator(3)], verbose_name= "First name", null= False, blank= False) # User surname last_name = models.CharField(max_length= 60, validators=[MinLengthValidator(3)], verbose_name= "Surname", null= False, blank= False) #user type user_type = models.ForeignKey(UserPlans, on_delete= models.PROTECT, related_name='userType') #user email user_email = models.EmailField() # total requests made by the user … -
How to add multiple records from POST in Django?
I had a little difficulty making multiple record in Django. I found a solution myself, but I couldn't make it work. Can anyone with knowledge help? form.html <form action="" method="POST"> {% csrf_token %} {% for work_stations in ws %} {% if work_stations.is_active %} <div class="row"> <div class="col"> <input type="text" class="form-control" placeholder="work stations1" aria-label="" name="ws1"> </div> <div class="col"> <input type="text" class="form-control" placeholder="work stations2" aria-label="last ws2" name="reject_ws"> </div> </div> {% endif %} {% endfor %} <input type="submit" > </form>` Models.py from django.db import models class Master_data(models.Model): ws1 = models.CharField(max_length=100, verbose_name=' ', blank=True) ws2= models.CharField(max_length=100, verbose_name=' ', blank=True) views.py from django.shortcuts import render from .models import Master_data def createpost(request): if request.method == 'POST': posts = request.POST.getlist('post_list[]') Master_data.objects.all().values() post_list_data = posts for x in post_list_data: x.save() return render(request, 'main/cretedata.html') else: return render(request, 'main/cretedata.html') -
Django and Javascript: Multiple events fired with same button not working as expected
I have this ongoing issue with an eventlistener. I can't seem to delegate the proper way and I'm at my wits end with this issue. The user clicks on a delete button which will check the hidden delete checkbox that the inlineformeset provides. This click of the delete button also adjusts the value of the TOTALFORMS in the management form. The box checks properly and the management form adjusts properly. However, when the user submits the form the delete checkbox that is checked submits false (unchecked) and the should-be deleted form is still there when I return back to the page. I have asked this question before and listened to the one suggestion. I also have tried countless things by adding options and rearranging code and making looping through the buttons. . . but nothing. Probably everything but the correct thing by now. {% load crispy_forms_tags %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}"> </head> <body> <input type="button" class="sun-not-available" value="Not Available Sunday" onclick="sunCheckOne(); sunHideShow()" id="sun-not-available"> <form id="all-add-form" method="POST" action="" enctype="multipart/form-data"> <div class="sun-hide" id="sun-hide-id"> <div class="sunday-all" id="sunday-all-id"> {% csrf_token %} <legend class="bottom mb-4">Profiles Info</legend> <div … -
Django-smart-select doesn't work in FilterSet
Let me start by saying that I am truly a beginner in Django. But I have already tried to search for possible solutions on the Internet and I still haven't solved my problem. In fact, in the template that uses the form based on the "Interventions" model django-smart-selects work. While in the template that uses the form based on the "InterventionFilter", the Plants are not filtered by the Company. Here is my code: models.py class Company(models.Model): ID = models.AutoField(primary_key=True, unique=True) company_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=100, blank=True) class Plant(models.Model): ID = models.AutoField(primary_key=True) plant_name = models.CharField(max_length=100) ID_company = models.ForeignKey(Company, on_delete=models.CASCADE) class Intervention(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() description = models.TextField() ID_company = models.ForeignKey(Company, on_delete=models.CASCADE) ID_plant = ChainedForeignKey( Plant, chained_field="ID_company", chained_model_field="ID_company", show_all=False, auto_choose=True, sort=True) filters.py import django_filters from django_filters import DateFilter, CharFilter from django.forms import DateInput from .models import Intervention class InterventionFilter(django_filters.FilterSet): date1 = DateFilter(field_name='start_date', lookup_expr='gte', label='From', widget=DateInput(attrs={'type': 'date'})) #GTE date2 = DateFilter(field_name='start_date', lookup_expr='lte', label='To', widget=DateInput(attrs={'type': 'date'})) #LTE descr = CharFilter(field_name='description', lookup_expr='icontains', label='Description') class Meta: model = Intervention exclude = ['start_date', 'description'] #(date1, date2, descr) fields = ['date1', 'date2', 'ID_company', 'ID_plant', 'descr'] html {% extends 'base.html'%} {% load crispy_forms_tags %} {% block content %} <form method="post" action="{% … -
Embed VueJs Frontend into Django Backend
I have a vue Js frontend and a Django backend running on 2 different ports. Currently I want to embed the frontend into the backend and both only output to a single port. I tried embedding the frontend and backend and both only output 1 port on the backend to run, but essentially still run 2 ports.