Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create write and read replicas for a Django App using tenant_schemas
For my application I use the Django rest framework, PostgreSQL and Django's tenant_schemas, to give my clients their own schema in my database. In order to improve the concurrency of my application, I would like to use Write and Read Replicas of my current Database. -
How to fix collectstatic path error in settings.py
I'm trying to set up my application for production. I'm fixing my static folders, however I'm getting this error: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. The message points out the obvious error, however It's causing me some confusion because I do have STATIC_ROOT configured in my settings.py file. I'm assuming the error is then coming from a pathing issue. Please check out my directory: Inside /core, you can see I have two setting files. I have already configured asgi.py and wsgi.py to account for settings_prod.py. Here is settings_prod.py: import os from decouple import config import dj_database_url from datetime import timedelta BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('DJANGO_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['host_url'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_HTTPONLY = True CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( ... ) INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'drf_yasg', 'storages', # Third Party Apps 'django_filters', 'corsheaders', 'django_extensions', # Apps 'users', 'bucket', 'bucket_api', #oauth 'oauth2_provider', 'social_django', 'drf_social_oauth2', ] MIDDLEWARE = [ … -
issue with django rest nested data
Can someone help to fix my issue please exactly in source This is my code : from rest_framework import serializers from task.models import Task, Status class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ("title", ) depth = 1 class StatusSerializer(serializers.ModelSerializer): tasks = TaskSerializer(many=True, source="task_set") class Meta: model = Status fields = '__all__' depth = 1 error i get : Got AttributeError when attempting to get a value for field `tasks` on serializer `StatusSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Task` instance. Original exception text was: 'Task' object has no attribute 'task_set'. -
how i can overwrite text in original forms.py - django allauth
i downloaded allauth to add accounts in my site so how i can overwrite text in original forms.py , i have original code from allauth , link for forms.py from allauth https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py how to edit my text in forms.py , note : when i try to edit text in forms like enter password again and replace it with bla bla it don't apply my new text why ? -
Django S3 using Boto3 with OpenTelekomCloud (OTC)
I followed this tutorial https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html to setup an S3 integration of my Django application with S3. I tested with AWS and it works fine, but for production uses I want to use a different S3 provider: OpenTelekomCloud aka OTC. Using the following client-code I can access both OTC and AWS, depending on the endpoint_url: session = boto3.session.Session() s3_client = session.client( service_name='s3', aws_access_key_id='XXXXXXXXXXX', aws_secret_access_key='XXXXXXXXXXXXXXXXXXXXXXXXX', endpoint_url='https://obs.eu-de.otc.t-systems.com', # region_name='eu-de', use_ssl=True, verify=True, ) print(s3_client.list_buckets()) But I can't move the config to the settings.py file of my Django app the right way for OTC, while it works fine with AWS. AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXX' AWS_STORAGE_BUCKET_NAME = 'my-bucket' AWS_S3_CUSTOM_DOMAIN = 'obs.eu-de.otc.t-systems.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } Tried several different configs but am always getting the following response. An error occurred (InvalidAccessKeyId) when calling the PutObject operation: The AWS Access Key Id you provided does not exist in our records. What would be the right way to config my settings.py for OTC to make it work? -
Can I call an function from another function in django views.py?
Please help me. I have created two functions in my views. def Covid_view() this one will fetch all covid data from an api. Another function is def home() inside this function I want to call covid_view() which will return me data that i can pass in my template. Below is my code, please have a look. Views.py from django.shortcuts import render import requests # this function is just to call api and get data of covid def covid_data(): api_response = requests.get('https://covid19.mathdro.id/api/countries/india') covid_data = (api_response.json()) trim_last_update = covid_data['lastUpdate'] trimmed_date = trim_last_update.find('T') # Here I'm trimming date_time string to show only date. T was for time to I split till T and store prior string res_trimmed_date = trim_last_update[:trimmed_date] # This will print string till T but not T and afterwards confirmed = covid_data['confirmed'] recovered = covid_data['recovered'] deaths = covid_data['deaths'] context = { 'res_trimmed_date': res_trimmed_date, 'confirmed': confirmed['value'], 'recovered': recovered['value'], 'deaths': deaths['value'] } return context def index(request): # here I want to call this function which must return me data so I can pass it to my template data = covid_data() return render(request, 'covidStatsApp/index.html', data) When I tried to run it gives me error like even though I tried to pass request as well. … -
Django gettext function with static vue
I have 2 separate files .html (Django) .vue And then use it together **.html** <div id="container" is="edit-contact-info" > <div slot="csrf-token">{% csrf_token %}</div> </div> <script src="{% static_with_version '/js/restaurant/edit_contact_info.js' %}"></script> <script type="text/javascript" src="{% url 'test.jsi18n' %}"></script> <script> var test = gettext console.log(test('Country'), "!!!!!!!!!!!!"); </script> **.html** **.vue** beforeCreate() { console.log("hi"); console.log(window); console.log(window.django.gettext('Country')); } **.vue** I want to know how to access function gettext in vue file. Currently it got undefined when window.django but if I log console.log(window) It show django is in window object already. Thank for help. -
Django can't import app from apps' folder, ImportError
I have old project made on Django 1.11.10 and Python 2.7 Imports like below isn't working from apps.configuration.utils import HrefModel Traceback from apps.configuration.utils import HrefModel ImportError: No module named configuration.utils Installed apps inside settings INSTALLED_APPS = [ some django apps... "apps.configuration", "apps.nav", "apps.pages", more similar apps... ] Project's folder structure project_name/ ├── apps │ ├── account │ ├── administration │ ├── catalog │ ├── configuration │ ├── content │ ├── elastic_search │ ├── feedback │ ├── google_captcha │ ├── __init__.py │ ├── nav │ ├── pages │ ├── posts │ ├── shop ├── docker-compose.yml ├── Dockerfile ├── entrypoint.sh ├── manage.py ├── requirements.txt -
How to limit each individual user to only allowed to post once every 24 hours in Django Class Based Create View
In views.py: class AddPostView(LoginRequiredMixin, CreateView): login_url = '/member/login' model=Post form_class = PostForm template_name='post/addpost.html' def form_valid(self, form): form.instance.poster = self.request.user return super(AddPostView, self).form_valid(form) In forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','somefields...') labels = {'somelabels': '...'} widgets = {'some css attributes....'} def has_posted_today(self): yesterday = timezone.now() - timezone.timedelta(hours=24) poster = self.cleaned_data.get('poster') if Post.objects.filter(poster=poster, list_date__gt=yesterday).exists(): raise forms.ValidationError("You have already posted today, Come back tomorrow!") in models.py class Post(models.Model): title = models.CharField(max_length=100) poster = models.ForeignKey(User, on_delete=models.CASCADE) ...somefields = ...somemodels If this were a function based view i would imagine the solutions would be something like... if request.method == "POST": yesterday = timezone.now() - timezone.timedelta(days=1) if Post.objects.filter(user=request.user, created__gt=yesterday).exists(): return HttpResponseForbidden("You have already posted today, Come back tomorrow!") First quesiton, my code does not work....how do i make it work.... Second question, How do u do the HttpResponseForbidden thing in a django class based view. -
My UpdateView does show errors on fly orm
I have an update view which displays a form (based on some criteria). I can update my model successfully, but if I enter bad data (like a bad time field), I do not get any errors back, I simply get a refresh of the update form. My view looks like this: class Cd_MixedView(UpdateView): model = Track template_name = 'cd_mixed_view.html' form_class = TrackForm context_object_name = 'cd_edit' def get_context_data(self, **kwargs): context = super(Cd_MixedView,self).get_context_data(**kwargs) cur_track = Track.objects.get(id=self.kwargs['pk']) context['form'] = TrackForm(instance=cur_track) context['cd_info'] = Cd.objects.get(id=cur_track.cd_id.pk) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self,form): form.save() return super(Cd_MixedView, self).form_valid(form) def form_invalid(self,form): print("Form Invalid") return super(Cd_MixedView,self).form_invalid(form) My template is the following: <!-- templates/cd_mixed_view.html --> {% extends 'base.html' %} {% load static %} {% block title %} CD Details{% endblock title %} {% block content %} <h1>CD Update Track </h1> {% if cd_info %} <p>Artist Name:&nbsp;{{ cd_info.artist_name}} <p>Cd Title:&nbsp;{{ cd_info.cd_title }} <p>Cd Total Time:&nbsp;{{ cd_info.cd_total_time|time:"H:i:s" }} <p>Cd Run Time:&nbsp;{{ cd_info.cd_run_time|time:"H:i:s" }} <p>Cd Remaining Time:&nbsp; {% if cd_info.cd_run_time_delta > cd_info.cd_total_time_delta %} (-{{ cd_info.cd_remaining_time|time:"H:i:s" }}) {% else %} {{ cd_info.cd_remaining_time|time:"H:i:s" }} {% endif %} <TABLE BORDER="0" TABLE_LAYOUT="fixed" WIDTH="100%"> <TR BGCOLOR="#B0B0FF"> <TD ALIGN="Center">&nbsp;Track #</TD> <TD ALIGN="Center"> Cut Title</TD> … -
Telethon - How to setup a Django project to work with Telethon on a remote server?
I have a Django project which was made by coworkers, and it functions well and is deployed on a server. I tested methods and new functionalities in a separate test Python project, using the Telethon library (to add users to channels, remove them from channels, create new channels, etc.), and they worked fine on my local environment, just running "python file.py" command and then testing with the Quart library on my local environment. However, now I want to incorporate those functions to the server my coworkers made, in their project, to run it continuosly and with data from Telegram that they will need to get from Telethon. The first error I'm encountering says Cannot send requests while disconnected. Before, I was using Quart as a microservice to make the calls and requests on my browser, but how could I replicate this functionality on a Django server? If I try to run this view: async def get_all_channels(request): try: dialogs = await client.get_dialogs() dialogs_str = '' dialog_list = [] for dialog in dialogs: dialog_type = 0 if str(type(dialog.entity)) == "<class 'telethon.tl.types.Channel'>": type_str = 'CANAL' elif str(type(dialog.entity)) == "<class 'telethon.tl.types.ChannelForbidden'>": type_str = 'CANAL PROHIBIDO' elif str(type(dialog.entity)) == "<class 'telethon.tl.types.User'>": type_str = 'USUARIO' else: … -
Why is my Django field input not connecting to my Model?
I am trying to connect this form input to my model so that it creates an email, and associates it to the product clicked, on the admin side. Currently, when I input an email and click Submit Email, nothing happens. I am able to correctly add emails on the Admin dashboard. How can I make sure when the email is inputted, it is processed correctly and associated to the specific product? store.html When the product is out of stock, the user can click and Remind Me button and the modal will appear. Within the modal, I have a form input field and a submit <div id="stockModal" class="modal fade" role="dialog"> <div class="modal-dialog modal-dialog-centered"> <!-- Modal content--> <div class="modal-content"> <form id="emailform"> <div id="modalheader" class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">This product is Out of Stock</h5> </div> <div id="modalbody" class="modal-body"> <p>Enter your email to be reminded whenever this product goes back in stock.</p> </div> <div class="modal-footer form-field"> <input required class="form-control" type="email" name="email" placeholder="Email.."> <input id="submitEmail" class="btn btn-success btn-block" type="submit" value="Submit Email"> </div> </form> </div> </div> </div> <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.image.url}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <h7>{{product.quantity}} left</h7> <!-- <h7 class="hidden" id="out-of-stock">Notify When Available</h7> --> <div id="content"></div> <hr> <button … -
Django - unable to update input_type on a modelForm
I hope someone can point me in the right direction. So I don't have to create a whole new modelForm class or render the form manually, I'm trying to set the field input_type to hidden with kwarg passed to the class. What I've tried is as follows: in forms.py: class Myform(ModelForm): class Meta: model = MyModel exclude = [ 'created_at', 'updated_at' ] widgets = {'parent_id': HiddenInput()} def __init__(self, *args, **kwargs): hideField = kwargs.pop('hideField') super(form, self).__init__(*args, **kwargs) if hideField == 1: self.fields['field2'].widget.input_type = 'hidden' From views.py: form = MyForm(initial=model_to_dict(data),hideField=1) If I print out self.fields['field2'].widget.input_type I can see that it does change, but when I render the form it still renders as the a select input. I've managed to update choices with a similar method, but the above isn't working. Any thoughts? -
Load geojson file into django database
Can someone help me, please? I am trying two a geojson file into my database (django.contrib.gis.db.backends.postgis) without success. models class Node(models.Model): network = models.ForeignKey(RoadNetwork, on_delete=models.CASCADE) node_id = models.IntegerField() name = models.CharField('Node Name', max_length=200) location = models.PointField() forms class NodeForm(forms.ModelForm): my_file = forms.FileField() class Meta: model=Node fields = [ 'network', 'my_file', ] views (here is my view, I thought the problem was about the foreign key, but no. When upload the file nothing happen. I don't see where am i wrong. def upload_node(request): Node = apps.get_model('metro_app', 'Node') template = "upload.html" form = NodeForm() if request.method == 'POST': form = NodeForm(request.POST) if form.is_valid(): network_fk = form.cleaned_data['nework'] datafile = request.FILES['my_file'] objects = json.load(datafile) for object in objects['features']: properties = object['properties'] geometry = object['geometry'] node_id = properties.get('id') name = properties.get('name', 'no-name') location = fromstr(geometry.get('coordinates')) Node( node_id = node_id, name = name, location = location, network = network_fk, ).save(commit=True) return render(request, template, {'form':form}) geojson file { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "id": 1, "name": "CBD" }, "geometry": { "type": "Point", "coordinates": "POINT (0.0 0.0)" } }, { "type": "Feature", "properties": { "id": 2, "name": "E - 1" }, "geometry": { "type": "Point", "coordinates": "POINT (4.0 0.0)" } }, { "type": "Feature", … -
Django - Unable to Display Values on Page
I am unable to display values from DB on home page. I can't figure out what I've done wrong. Following is my html HTML <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" async></script> </head> <div class="container"> {% for manhour in manhours %} <div class="article-metadata"> <a class="mr-2" href="#">{{ manhour.station }}</a> <small class="text-muted">{{ manhour.date|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'manhour-detail' manhour.id %}">{{ manhour.station }}</a></h2> {% endfor %} </div> <div class="user_panel"> <a href="/logout">logout</a> </div> <div class="user_panel"> <a href="/manhour/new">Upload</a> </div> </html> view.py # Create your views here. from django.shortcuts import render, redirect from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .form import InputForm from manhour.models import ManHour from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib import messages from django.contrib.auth import login, logout, authenticate from django.urls import reverse def login_request(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect('manhour-home') else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") else: form = AuthenticationForm() return render(request = request, template_name = "manhour/login.html", context={"form":form}) class PostListView(LoginRequiredMixin, ListView): model = ManHour … -
'Task' object has no attribute 'task_set'
i'm working on a small project and following a tutorial, using Django / Rest Framework, i would like to know the role of source parameter and many please, because i'm getting an error and i don't know why. What is task_set because i'm getting an error ( there is not attribute called task_set ) this is my serializer from rest_framework import serializers from task.models import Task, Status class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ("title", ) depth = 1 class StatusSerializer(serializers.ModelSerializer): tasks = TaskSerializer(many=True, source="task_set") class Meta: model = Status fields = '__all__' depth = 1 this is my models : this is my models : (Status) from django.db import models from django.conf import settings from contact.models import Contact # Create your models here. class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title This is my Task Model : class Task(models.Model): status = models.ForeignKey(Status, on_delete=models.CASCADE, default=1) title = models.CharField(blank=False, max_length=255) -
How to display images in AJAX request - Django
I am trying to build a search suggestion dropdown with AJAX but I dont know how to get my images to be displayed after ajax request in template Here is the code: html <form class="search" method='get'> {% csrf_token %} {{ form.q }} <button type="submit"> <i style="padding-top: 0.125rem; font-size: 1.75rem;" class="material-icons">search</i></button> </form> --- <script> $(document).on('keyup', '#id_q', function (e) { e.preventDefault(); var results = []; $.ajax({ type: 'POST', url: '{% url "search" %}', data: { ss: $('#id_q').val(), csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function (json) { $.each(JSON.parse(json.search_string), function (i, item) { results.push( `<div onclick="window.location.href='${item.fields.slug}'" class="anime"> \ <div class="background-search"> \ <img src="${item.fields.image.url}" alt=""> \ <div class="cover"></div> \ <div class="anime-data"> \ <img src="${item.fields.icon}" alt=""> \ <div class="anime-info"> \ <div class="data"> \ <h3>${item.fields.title_english}</h3> \ <div class="p">${item.fields.description}</div> \ </div> \ <div class="about"> \ <span>Started:${item.fields.time_and_date_started}</span> \ <span>Rating:${item.fields.rating}</span> \ </div> \ </div> \ </div> \ </div> \ </div>`); }) document.getElementById("anime-list-id").innerHTML = results; }, error: function (xhr, errmsg, err) {} }); }) </script> I tried multiple ideas but none worked ${item.fields.image.url} ${item.fields.image} ${item.fields.image.src} The other fields are working but not the icon / image views.py def search(request): form = SearchForm() if request.POST.get('action') == 'post': search_string = str(request.POST.get('ss')) if search_string is not None: search_string = Anime.objects.filter(title_english__icontains=search_string)[:7] data = … -
Django, jquery, database based autocomplete, improvements
Hello everyone i recently made a autocomplete which is based on my database, the problem is i think it requires a bit of improvement. For example: If a user inputs twice the same value twice, the autocomplete also recommends the same values twice, there is also the problem of escalation i am pretty sure this code might be bad for when my application database size increases. Would love some ideas on how to fix those issues or some good alternatives. Here is the autocomplete view @login_required def AutocompleteModelo(request): if 'term' in request.GET: query=DataDB.objects.filter(modelo__istartswith=request.GET.get('term')) modelos=list() for q in query: modelos.append(q.modelo) return JsonResponse(modelos, safe=False) return render(request,'data.insiradado.html') And here it is the jquery script for the autocomplete. <script> $(function () { $("#modelo").autocomplete({ source: '{% url 'data-AutocompleteModelo' %}', minLength: 1 }); }); </script> Btw modelo is the name of the db column, thanks for the help. -
How to get a nested data structure, in Django Rest
I'm working on a small project ( Kanban board ) using Django / Rest Framework, I have two models one for tasks and one another for status ( columns ), like ( started, pending, Done ). everything works fine with me. the only issue I have is my data structure, is not correctly nested, this is my models : (Status) from django.db import models from django.conf import settings from contact.models import Contact # Create your models here. class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title This is my Task Model : class Task(models.Model): status = models.ForeignKey(Status, on_delete=models.CASCADE, default=1) title = models.CharField(blank=False, max_length=255) This is my serializer : from rest_framework import serializers from task.models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' depth = 1 The result that i get : [ { "id": 1, "title": "my task title must be inside status ", "status": { "id": 1, "title": "step1", "slug": "step1", "order": 1 } } ] **I would like to get a nested Data structure, my tasks my be inside the status dictionary, so I can loop ever the status and the tasks ( nested … -
is it wrong using global variable in my django app
I have learned basic about django and i am currently on a project. there is a login page. Now when the user logs in, I can print his username, email and gender on that view. But there is another page in which i want to print the user's name. The user is still logged in but i don't know how to access it's properties. So i declared the user's username, email and gender global in login view so that i could access them in another view. I know this is weird and wrong but i don't know the solution. I have also tried passing them as the parameters but in my case it wouldn't work. Hope you guys will not brother providing me a solution.... thank you -
Django update functionality
I've got a model, with two forms. When a calf is scanned in, it gets one set of information, then when it's shipped out, it's a separate form with different information. For example when scanned in, it takes DOB and arrival date, when scanned out we need ship out date, milk consumed during it's stay(2 quarts per day), where it is going, and any medication while at the depot. Right now I have the two forms below: Scan in form scan out form Now you can see when I try to update an entry I get an error that it already exists Here is my view: def scanoutcalf(request, id=None): form = ScanOutForm(request.POST or None) context = { 'form': form, } form = ScanOutForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'calves/scan_out.html', context) And my forms: class ScanOutForm(forms.ModelForm): class Meta: model = Calf fields = [ 'eid', 'ship_out_date', 'program', 'destination', 'medical_history', 'milk_consumed' ] widgets = { 'ship_out_date': forms.widgets.DateInput( attrs={'type': 'date'} ) } I've googled around, but couldn't find an example of how to update without having to create a queryset or a URL with instance ID. The idea here is that a user can just scan when calves are leaving, update … -
Weighted graphs in django project
I'm doing a Django project, where I connect 2 points and define the distance between them. After creating the pairs, I need to write a function, which will give me a total distance between any two points.enter image description here For example, if I put H and D, which should give me the sum of distances between H-C, C-F, F-D. Please, give me advice on what kind of tools or libraries are the best option for such kinds of tasks? models.py point1 = models.ForeignKey(Point, related_name='form61_KLS_point', verbose_name='ИП от', on_delete=models.SET_NULL, blank=True, null=True) point2 = models.ForeignKey(Point, related_name='form61_KLS_point2', verbose_name='ИП до', on_delete=models.SET_NULL, blank=True, null=True) total_length_line = models.FloatField("Общая протяженность линии КЛС", default=0, blank=True, null=True) total_length_cable = models.FloatField("Общая протяженность кабеля КЛС", default=0, blank=True, null=True) def __str__(self): return f"{self.point1.name}-{self.point2.name}" ``` #views.py def get_distance_length_kls(request): point1 = request.GET.get("point1") point2 = request.GET.get("point2") forms1 = Form61KLS.objects.filter(point1=point1) data = [] content = {'point1': None, "point2": None, "sum_line": 0, "sum_cable": 0 } for form in forms1: finish_total = copy.deepcopy(content) finish_total['point1'] = form.point1.point while form: total = copy.deepcopy(content) total['point1'] = form.point1.point total['point2'] = form.point2.point total['sum_line'] = form.total_length_line total['sum_cable'] = form.total_length_cable data.append(total) finish_total['point2'] = form.point2.point finish_total['sum_line'] += total['sum_line'] finish_total['sum_cable'] += total['sum_cable'] test = Form61KLS.objects.filter(point1=form.point2).first() if test is None: break form = test data.append(finish_total) return JsonResponse(data, safe=False) -
holding modal after page refreshing
I am working in a project where I show some modals under certain conditions, after some work I realized that if I try to refresh the page while a modal is showing up, the modal vanishes. I would like to know if there is a method that would let me render the modal when refreshing the page. I tried this java script code: // Get the modal var modalBtn = document.getElementById("modalBtn"); // // Get the button that opens the modal // var buttonModal = document.getElementById("buttonModal"); window.onbeforeunload = function (evt) { buttonModal.click(); console.log("refresh") } // //hold modal buttonModal.addEventListener('click', () => { // //show error modal $("#modal_error").modal() }) In the case I click on buttonModal, I can see the modal, but when I refresh it vanishes. If I refresh the page I can see the modal for an short period of time, but it does not hold itself. would there be a way that let me hold the modal, if its being display, inclusive after refreshing? Luis -
How to update m2m connection in overloaded save
I have library project. i have book and order model. the user can order many books at once, bu i have error. this is my code -> book model -> class Book(models.Model): name=models.CharField(max_length=100, verbose_name=_('name')) Condition = models.IntegerField(default=10,verbose_name=_('condition')) author=models.CharField(max_length=100, verbose_name=_('author')) quantity=models.IntegerField(default=100, verbose_name=_('quantity')) branch = models.ManyToManyField(Branch, verbose_name=_('branch')) def __str__(self): return self.name class Order(models.Model): book=models.ManyToManyField(Book, verbose_name=_('book')) user=models.ForeignKey(User,on_delete=models.CASCADE, verbose_name=_('user')) branch=models.ForeignKey(Branch,on_delete=models.CASCADE, verbose_name=_('branch')) start_date=models.DateField(verbose_name=_('start')) end_date=models.DateField(verbose_name=_('finish')) def __str__(self): return str(self.user) def save(self, *args, **kwargs): today = datetime.datetime.now() if not self.pk: # self.book.quantity -= 1 for i in self.book: i.quantity -= 1 i.save() self.end_date = today + datetime.timedelta(days=14) super(Order, self).save(*args, **kwargs) when i save i have this error ->"<Order: d@gmail.com>" needs to have a value for field "id" before this many-to-many relationship can be used. -
Why django-smart-selects doesn't refresh the chained foreign keys after foreign key changes?
I'm using django-smart-selects to be able to handle some fields that depends on each other. Here is the details: In my models I have Faculty and Program. A faculty can have multiple programs and a program can belong to only one faculty. A Student has a faculty and program. from smart_selects.db_fields import ChainedForeignKey class Student(models.Model): ... faculty = models.ForeignKey(Faculty, on_delete=models.CASCADE) program = ChainedForeignKey( Program, chained_field="faculty", chained_model_field="faculty" ) And say I have the following entries in my database: ├── Faculty 1 │ ├── Program a │ └── Program b └── Faculty 2 ├── Program x └── Program y Here is my problem: When I try to select faculty and program for a student for the first time, everything works as expected. But if I save it then come to the same page, when I change faculty from 1 to 2 dropdown for the programs are not updated (if Faculty 1 is selected initially I always see Program a and Program b in the dropdown even if I change the faculty). Is this intended behaviour? If not what should I do to make it work as I want?