Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sqlite3.OperationalError: database is locked
travelers I am trying to run tests in order to to understand if my code is actually saving messages from telegram chat in database properly. The error says that sqlite3.OperationalError: database is locked everytime i am running test. ```settings.py```: ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name', 'USER': 'me', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': `port', 'URL': 'postgres://username:password@host/database', } } Here is my `test_messages.py` which is the problem: ``` my_sqlalch_engine = sqlalchemy.create_engine('postgresql://user:password@localhost:5432/mydatabase') session_factory = orm.sessionmaker(bind=my_sqlalch_engine) session = session_factory() my_base = declarative_base() container = AlchemySessionContainer(session=session, table_base=my_base) session_fr = container.new_session('new_session') @pytest.mark.django_db def test_message_consumer(): # Setup test data api_id = '111231' api_hash = 'my_actual_hash' client = TelegramClient(session_fr, api_id, api_hash) #consumer = MessageConsumer() with transaction.atomic(): messages = client.get_messages('chatmessages') for text in messages: if text.slug not in Post.slug: post = Post( content = messages.text ) post.save() assert Post.objects.count() == len(messages) actual code for retrieving messages consumers.py: ``` api_id = '12391842' api_hash = 'api_hash' client = TelegramClient('news_session', api_id = api_id, api_hash = api_hash) class MessageConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, code): return super().disconnect(code) @transaction.atomic async def receive(self, client): messages = await client.get_messages('chat') async for text in messages: if text.slug not in Post.slug: post = Post( content = messages.text ) post.save() Hope i have provided all … -
Pass data to another html and save
can someone please tell me how to send all content of input.html to approve.html. I want the approve.html to validate input.html and then save it to the database. How can I do that? I'm a newbie, please help me, I've been trying to solve the problem for 7 days. <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">Name:</label> <input type="text" id="name" name="user_name" /> </li> <li> <label for="mail">Email:</label> <input type="email" id="mail" name="user_email" /> </li> <li> <label for="msg">Message:</label> <textarea id="msg" name="user_message"></textarea> </li> <li> <button class="menü_button"><b>send</b></button> </li> </ul> </form> <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">Name:</label> <input type="text" id="name" name="user_name" /> </li> <li> <label for="mail">Email:</label> <input type="email" id="mail" name="user_email" /> </li> <li> <label for="msg">Message:</label> <textarea id="msg" name="user_message"></textarea> </li> <li> <button class="menü_button"><b>save</b></button> </li> <li> <button class="menü_button"><b>remote</b></button> </li> </ul> </form> -
Post request to Djoser user registration route 'appName/v1/users/' throws 401 error
I'm new to Django and trying to build basic user authentication with REST API and a Vue.js frontend. To send the request, I am using axios, which is configured first in a seperate composable axios.js: import axios from 'axios' axios.defaults.withCredentials = true axios.defaults.baseURL = 'http://localhost:8000' and used inside a register.vue component: const submitRegistration = () => { axios.post('api/v1/users/', {username: 'userName', password: 'userPassword'}) .then(res => { console.log(res) }) } To make it simple, I'm sending a data-object with predefined strings, as you can see above. The request gets sent to one of the djoser routes in projectName/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), ] This however, throws a 401 Unauthorized Error: code: "ERR_BAD_REQUEST" config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message: "Request failed with status code 401" name: "AxiosError" request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} response: {data: {…}, status: 401, statusText: 'Unauthorized', headers: AxiosHeaders, config: {…}, …} stack: "AxiosError: Request failed with status code 401\n at settle (http://localhost:3000/node_modules/.vite/deps/axios.js?v=a45c5ec0:1120:12)\n at XMLHttpRequest.onloadend (http://localhost:3000/node_modules/.vite/deps/axios.js?v=a45c5ec0:1331:7)" I've configured settings.py like so: INSTALLED_APPS = [ ..., 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'djoser' ] MIDDLEWARE = … -
How to get access to request inside custom class in django
customclass.py class MyCustomClass(): def __init__(self): if request.user.is_authenticated: // do somtehing custom_class = MyCustomClass() Hi A have an issue to get request data on "init". How to get it there? -
CS50w - Project 1
I try to solve cs50w project 1. But I faced an error in the project. enter image description here <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> This is the layout.html file. I have a form action: go to search, and the name is q. enter image description here urlpatterns = [ path("", views.index, name="index"), path("<str:title>/", views.title, name="title"), path("search/", views.search, name="search"), ] In my urls.py page I add a search path. enter image description here def search(request): if request.method == "POST": entry_search = request.POST['q'] html_content = markdown2.markdown(util.get_entry(entry_search)) if html_content is not None: return render(request, "encyclopedia/title.html", { "content": html_content, "title": entry_search, }) And in views.py i create a function named search. When I start my project and type something in the search bar, it sends me to the error.html page. enter image description here But it needs to take me to the title.html page. Can you help me with this problem? I need to face with title.html page, but it redirects to error.html -
cannot create new record in table django
I am trying to add new record into customer table via django forms but new records are not getting in the table also view function not redirecting to correct url. Here is my model.py class Customer(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) name = models.CharField(max_length=200) category = models.CharField(max_length=1) def __str__(self) -> str: return self.name here are my url patterns urlpatterns = [ path("create-customer" , views.create_customer , name = "create-customer"), path("<str:n>" , views.customer_index , name="cust_index"), path("" , views.home , name = "home"), ] here are my views def create_customer(response): if response.method == "POST": cust_form = createNewCustomer(response.POST) if cust_form.is_valid(): i = cust_form.cleaned_data["id"] n = cust_form.cleaned_data["name"] cat = cust_form.cleaned_data["category"] r = Customer(id = i , name = n , category = cat) r.save() return HttpResponseRedirect("%s" %r.n) else: cust_form = createNewCustomer() return render(response , "main/create-customer.html" , {"form" : cust_form}) def customer_index(response, n): cust = Customer.objects.get(name=n) return render(response , "main/display_cust_det.html" , {"cust":cust}) and here is my form class createNewCustomer(forms.Form): id = forms.IntegerField(label = "id") name = forms.CharField(label="name" , max_length=200) category = forms.CharField(label="category" , max_length=1) now when I am creating the customer it does not putting it into the customer table -
django select related not giving expected result
I am querying select related between two models Requirements and Badge Requirement has a related badge indicated by badge_id Models are, class Badge(models.Model): level = models.PositiveIntegerField(blank=False, unique=True) name = models.CharField(max_length=255, blank=False , unique=True) description = models.TextField(blank=True) class Meta: verbose_name = _("Badge") verbose_name_plural = _("Badges") def __str__(self): return self.name def get_absolute_url(self): return reverse("Badge_detail", kwargs={"pk": self.pk}) """ Requirement Model for requirements """ class Requirement(models.Model): number = models.PositiveIntegerField(blank=False) badge = models.ForeignKey(Badge, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True) class Meta: verbose_name = _("Requirement") verbose_name_plural = _("Requirements") def __str__(self): return self.name def get_absolute_url(self): return reverse("Requirement_detail", kwargs={"pk": self.pk}) In My view I try to join both tables and retrieve. It is, """ ajax requirements in requirements table """ def get_requirements(request): requirements = Requirement.objects.all().select_related('badge').values() print(requirements) return JsonResponse(list(requirements), safe=False) The result is, to the frontend, to the backend, Why does it not give me both tables' values? -
Django Relational managers
I was trying to delete my Apllication model: class Application(models.Model): app_type = models.ForeignKey(ApplicationCategory, on_delete=models.CASCADE, related_name='applications') fio = models.CharField(max_length=40) phone_number = models.CharField(max_length=90) organisation_name = models.CharField(max_length=100, null=True, blank=True) aid_amount = models.PositiveIntegerField() pay_type = models.CharField(max_length=1, choices=PAY_CHOICES, default=PAY_CHOICES[0][0]) status = models.ForeignKey(AppStatus, on_delete=models.CASCADE, related_name='applications', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) benefactor = models.ForeignKey(Benefactor, on_delete=models.CASCADE, related_name='applications', null=True) def __str__(self): return f"id={self.id} li {self.fio} ning mablag\'i!" and this was my Benefactor model: class Benefactor(models.Model): fio = models.CharField(max_length=255) phone_number = models.CharField(max_length=9) image = models.ImageField(upload_to='media/') sponsory_money = models.IntegerField() organisation_name = models.CharField(max_length=55, null=True, blank=True) def __str__(self): return f"{self.fio}" But I got this message on superAdmin Panel: TypeError at /admin/api/benefactor/ create_reverse_many_to_one_manager.<locals>.RelatedManager.call() missing 1 required keyword-only argument: 'manager' I would expect delete smoothly!! -
How to use different content fro the database based on user's languages, in Django
Im building a Bible website. Let's say I have two versions of the Bible - one in English and one in Spanish. Im already using the en in my database and everything is working properly. How can I use the es Bible for Spanish speaking users? -
Django custom management command not found
app/ ├─ management/ │ ├─ commands/ │ │ ├─ customcommand.py myfunction.py site/ ├─ settings.py Contents of myfunction.py from django.core import management def funcA(): management.call_command('customcommand') funcA() On calling myfunction.py from terminal it throws raise CommandError("Unknown command: %r" % command_name) os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings' Inside myfunction.py I have tried setting this, but it still doesn't work. Can someone help me out here, probably I am missing out on some important config -
django migrate not updating on sql database tables therefor raising django.db.utils.OperationalError: (1054, "Unknown column 'field list'")
im having issues with my django project in development. it was working fine till i updated the model fields then it went haywire. here is my models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from multiselectfield import MultiSelectField equipment_choices = ( (1, "Contact Grill & Panini Grill"), (2, "Char Grill"), (3, "Griddle"), (4, "Salamender Grill"), (5, "Toaster Grill"), (6, "Boiling Top"), (7, "Gas Hob"), (8, "Freestanding Fryer"), (9, "Counter Top Fryer"), (10, "Filtration Fyrer"), (11, "Chip Scuttle"),) class Recipe(models.Model): title = models.CharField(max_length=40, unique=True) description = models.CharField(max_length=150, unique=True) prep_time = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1), MaxValueValidator(500), ] ) cook_time = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1), MaxValueValidator(500), ] ) additional_time = models.PositiveSmallIntegerField( validators=[ MinValueValidator(0), MaxValueValidator(200), ] ) total_time = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1), MaxValueValidator(500), ] ) ingridients = models.CharField(max_length=200, unique=True) method = models.TextField(unique=True) equipment = MultiSelectField(choices=equipment_choices, max_choices=5, max_length=11) year = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1), MaxValueValidator(500), ] ) rating = models.PositiveSmallIntegerField(choices=( (1, "★☆☆☆☆"), (2, "★★☆☆☆"), (3, "★★★☆☆"), (4, "★★★★☆"), (5, "★★★★★"), ) ) and when i press a button that works with the model i get the following error Internal Server Error: /recipes/list Traceback (most recent call last): File "/home/buddy/.virtualenvs/takein/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/buddy/.virtualenvs/takein/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File … -
How to send QuerySet from HTML template to views via urldispatcher in django
I am trying to send QuerySet from index.html to views through urldispatcher. I searched through documentations but mostly have information on int:id, path:kjf, etc. There is some information on keyword args but i don't know much about them. I am beginner to Django and this is my first project, also my deadline for this project is near, so any help will be appreciable. index.html listing only necessary code... {% if datadict and datadict != "Sorry no data found" %} {% for item in datadict %} <tr> <th width="5%" scope="row"><a href="{% url 'index' datadict %}" class="btn btn-secondary">Generate</a></th> <td>{{ item.title }}<td> </tr> {% endfor %} {% endif %} urls.py urlpatterns = [ path('', views.index, name='index'), path('<datadict>', views.index, name='index') ] views.py def index(request, datadict=None): if (datadict): b = datadict[0] ### this is just testing to see if i am receiving the data in QuerySet from or not return render(request, 'dapp/index.html', {'b': b}) datadict have this data:- <QuerySet [{'id': 1002, 'year': '2000', 'sector': 'test', 'topic': 'test1', 'insight': 'dont no', 'url': 'localhost', 'start': '2000', 'impact': 'impaca', 'added': 'January 08 2001', 'published': 'August 03 2001', 'relevance': '4', 'pest': 'test2', 'source': 'CBSE', 'title': 'Adding test data', 'like': '5'}]> -
How to autofill user and slug fields in django form
I need two of the three form fields to be filled in automatically before submitting to the database. Slug is supposed to be filled based on test_name, and user have to be filled based on data about the current user. Now I can submit the form, but the database entry will not be created. models.py class Test(models.Model): test_name = models.CharField(max_length=100, db_index=True, verbose_name='Test name') slug = models.SlugField(max_length=100, unique=True, verbose_name='URL') author = models.ForeignKey(User, db_column="user", on_delete=models.PROTECT) forms.py class AddTestForm(forms.ModelForm): class Meta: model = Test fields = ['test_name', 'slug', 'author'] views.py def ask_test_name(request): form = AddTestForm(request.POST) if form.is_valid(): test = form.save(False) test.slug = slugify(test.test_name) test.author = request.user test.save() return render(request, 'app/ask_test_name.html', {'form': form}) ask_test_name.html <form action="{% url 'ask_test_name' %}" method="post"> {% csrf_token %} <p><input type="text" name="test_name" required></p> <p><input type="hidden" name="slug"></p> <p><input type="hidden" name="author"></p> <p><button type="submit">Create</button></p> </form> -
Django Show var as Label name
I'am learning Django and looking for a wat te get a variable shown as tekst I created the following model: ` class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telefoon = models.CharField(max_length=10, blank=True) telefoon_mobiel = models.CharField(max_length=10, blank=True) woonplaats = models.CharField(max_length=20, blank=True) postcode = models.CharField(max_length=6, blank=True) straat = models.CharField(max_length=20, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() ` I created the following Form.py ` class ProfileForm(forms.ModelForm): straat = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) postcode = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) woonplaats = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) telefoon = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) telefoon_mobiel = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Profile fields = ('telefoon', 'telefoon_mobiel', 'woonplaats', 'postcode', 'straat') ` i Created the following views.py ` @login_required @transaction.atomic def profiel(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, ('Profiel aangepast')) return redirect('user') else: messages.error(request, ('Los ondestaande probleem op')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'public/profiel.html', { 'user_form': user_form, 'profile_form': profile_form, }) And created the following template: <div class="card-body"> <h5 class="card-title">Profiel {{ user.get_full_name }}</h5> <hr> <div class="container"> <div class="row"> <div class="col-sm"> {{ user.first_name }} {{ user.last_name }} </div> <div class="col-sm"> {{ straat }} </div> </div> <br/> … -
Reverse for 'detail_serial' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
I have this problem Reverse for 'detail_serial' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/\Z'] and problem is here {{ serial.title }} I don't know how it fix, cause im new in django.Please help html > ``` > <div class="container" style="grid-template-columns: repeat(auto-fill, 300px);"> > for serial in serials %} > <div class="item"> > <img src="{{ serial.poster.url }}" class="img-fluid" alt=""> > <p> > <a href="{% url 'detail_serial' serial.url %}">{{ serial.title }}</a> > </p> > </div> > endfor %} > </div> > ``` > views.py > ``` > class SerialDetailView(View): > def get(self, request): > serials = Serials.objects.all() > genres = Genre.objects.all() > return render(request, "serials/single_serial.html", {"serials": serials, "genres": genres}) > > ``` > > ``` urls.py urlpatterns = [ path('register/', views.Register.as_view(), name='register'), path('reg/', views.Reg.as_view(), name='reg'), path("serials_list/", views.SerialsView.as_view(), name='serials_list'), path("add/", views.AddView.as_view(), name='add'), path("single_serial/", views.SerialDetailView.as_view(), name='single_serial'), path("<slug:slug>/", views.SingleSerial.as_view(), name='detail_serial'), path("actor/<int:id>/", views.ActorView.as_view(), name='actor_detail'), ] models > ```` > class Serials(models.Model): > title = models.CharField('Name',max_length=100) > description = models.CharField('Description', max_length= 200) > poster = models.ImageField('Poster', upload_to='serials/') > date = models.DateField('Date') > country = models.CharField('Страна',max_length=100) > actors = models.ManyToManyField(Actor, verbose_name='actors', related_name='actor') > genre = models.ManyToManyField(Genre, verbose_name='genres') > category = models.ForeignKey(Category, verbose_name='category', on_delete=models.SET_NULL, null=True) > url = models.SlugField(unique=False) > link = models.URLField(max_length=200, blank=True) > ``` > … -
JavaScript fetch to Django view: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I have a JavaScript fetch to call a URL to pass data into my Django view to update a value for the user. Error in views.py: Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\rossw\Documents\Projects\Scry\apps\administration\views.py", line 47, in administration_users_page switchData = json.load(request)['switch'] File "C:\Python310\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "C:\Python310\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Python310\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python310\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Error in browser: 0 PUT http://127.0.0.1:8000/administration/users/JM/ 500 (Internal Server Error) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON JavaScript: const changeAdminUserAction = (id,data) => { console.log(data) fetch(`/administration/users/${id}/`,{ method: 'PUT', body: JSON.stringify({type: "adminUser", switch: data}), headers: {'X-CSRFToken' : csrfToken, 'Content-Type': 'application/json'}, }) .then((response) => response.json()) .then((result) => {location.reload()}) .catch((err) => {console.log(err)}) } views.py: if request.method == 'PUT': user = CustomUser.objects.get(username=kwargs.get('username')) switchType = json.load(request)['type'] switchData = json.load(request)['switch'] print(switchType, switchData) if switchType == 'adminUser': user.admin_user = switchData elif switchType == 'admindata': … -
I was running a test on my signal.py file and i am getting 'ValueError: seek of closed file' error
here is the signals.py file inside main app and here is the test_signals.py file enter image description here the full error is -
what is the best module for periodic tasks (django)
I am trying to save data from some external APIs every 3 minutes and i am wondering which module is the best and easiest one to use in general and also in deployment.( APScheduler , background-tasks or celery beat) -
Can't import properly in fast api project with multiple apps
I'm currently learning fast api cause it's needed for a new project i'm working on,the documentation and tutorials only make their sample project with the assumption that the project is a small project,they usually have file structures similar to this : - app | | | --- __init__.py | --- models.py | --- schemas.py | --- database.py | - main.py But coming from a django background in which most of my projects will be projects with lots of models and functionality, i will definately need a way to decouple the fast api application into separate apps so i took the django approach and made my own project structure into this . └── config ├── __init__.py ├── database.py ├── migrations.py └── recruiters ├── __init__.py ├── models.py ├── schemas.py └── jobs ├── __init__.py ├── models.py ├── schemas.py └── routers ├── __init__.py ├── job.py ├── recruiter.py └── views ├── __init__.py ├── job.py ├── recruiter.py └── main.py └── sqlite.db The only changes i made was to keep all views ( or repository for business logic, i choose to call it views cause that's what i'm used to) in one folder at the root directory same for routers (similar to url routes in django). The … -
NoReverseMatch Error while trying to delete file using django-htmx
I am getting a NoReverseMatch error while trying to delete a document from a list in an update page using htmx.Two parameters are passed to the url template tag: "doc.id" and the update page's object id "obj.id". I need the "doc.id" to delete the document with the view and the "obj.id" to then filter and return the new updated list, because we are dealing with multiple files field. The document gets deleted but for some reason the "obj.id" is blank as the error page (snapshot below) shows. But on refreshing the page the new updated list is returned. Please I need fresh eyes on this problem. What am I missing? What am I doing wrong? Thanks # html template (snippet) <label class="block mb-2 text-md font-bold text-gray-500"> Attached files </label> <span class="mb-4 block w-full p-2 rounded-sm border border-2 border-gray-300 bg-white"> <ol class="text-ellipsis overflow-hidden list-inside list-decimal"> {% for doc in sharefiles %} <li class="p-2 cursor-pointer text-blue-600 font-bold text-md w-auto"> <a target='blank' href="{{ doc.attach_share_capital.url }}" class="underline underline-offset-2"> {{ doc.attach_share_capital.url }} </a> <button type="button" hx-delete="{% url 'removescfile' pk=doc.id update_id=obj.id %}" hx-target="#sharecapital-files" hx-confirm="Are you sure?" class="cursor-pointer text-white bg-red-400 hover:bg-red-500 focus:ring-4 focus:outline-none focus:ring-red-400 font-medium rounded-sm text-sm items-center ml-2 px-2 py-1"> Remove </button> </li> {% endfor %} … -
Django: Send a SELECT value inside form action url
I have a form with multiple select inputs, as below: <form method="POST" class="row" action="{% url 'solution_product_list' %}"> {% csrf_token %} {# main select div: usage or model? #} <div class="col-md-3 mx-md-5"> <h2 class="h5 nm-text-color fw-bold mb-4">انتخاب بر اساس:</h2> <select required aria-label="Select usage or model" id="usage_model_select" class="form-select" onchange="set_usage_or_model_dic()"> <option selected>----</option> <option value="usage">کاربرد</option> <option value="model">مدل</option> </select> </div> {# usage or model select div #} <div class="col-md-3 mx-md-5"> {# usage select div #} <div class="usage visually-hidden" id="usage_div"> <h2 class="h5 nm-text-color fw-bold mb-4">انتخاب کاربرد:</h2> <select required aria-label="Select usage" class="form-select" name="usage_select" onchange="set_sub_usage_list()" id="usage_select_id"> <option selected>----</option> {% for usage in usage_queryset %} <option value="{{ usage.id }}">{{ usage.usage_name_fa }}</option> {% endfor %} </select> </div> {# model select div #} <div class="model visually-hidden" id="model_div"> <h2 class="h5 nm-text-color fw-bold mb-4">انتخاب مدل:</h2> <select required aria-label="Select model" class="form-select" name="model_select" onchange="set_pump_type_list()" id="model_select_id"> <option selected>----</option> {% for model in main_model_queryset %} <option value="{{ model.id }}">{{ model.model_name_fa }}</option> {% endfor %} </select> </div> </div> {# select sub_usage or pump_type div #} <div class="col-md-3 mx-md-5"> {# sub_usage select div #} <div class="sub_usage visually-hidden" id="sub_usage_div"> <h2 class="h5 nm-text-color fw-bold mb-4">انتخاب کاربرد جزئی:</h2> <select required aria-label="Select sub_usage" class="form-select" name="sub_usage_select"> <option selected>همهی کابردهای جزئی</option> {% for sub_usage in sub_usage_queryset %} <option value="{{ sub_usage.id }}">{{ sub_usage.sub_usage_name_fa }}</option> {% endfor … -
How to make Django pagination with ajax without re-querying the DB
I've checked many related questions on building up pagination with ajax and implemented it in my app. The problem I still have is querying DB each time user сlicks next or prev because ajax call goes to the view function. My code: my_template.html <ul class="list-articles" id="dd"> </ul> <div class="buttons"> {% if page_obj.has_previous %} <a href="#" onclick="ajax_function('{{page_obj.previous_page_number}}','{{title}}')" id="prev">&#10094; prev</a> {% endif %} {% if page_obj.has_next %} <a href="#" onclick="ajax_function({{page_obj.next_page_number}},'{{title}}')" id="next"> next &#10095;</a> {% endif %} </div> views.py def my_view_function(request): if is_ajax(request=request): if 'page' in request.GET: return paginate(request) def paginate(request): parameter_a = request.GET['parameterA'] parameter_b = request.GET['parameterB'] li = MyModel.objects.filter(par_a=parameter_a, par_b=parameter_b) paginator = Paginator(li, 1) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'page_obj': page_obj, ... } return render(request, f'my_app/my_template.html', context) main.js function ajax_function(page, title) { $.ajax({ url: '', type: "get", data: { 'page': page, 'title':title, }, success: function(response, status) { $('#dd').empty(); $('#dd').html(response); } }); } So this code is working but in real app I have more complex db queries to get my Model's objects, so every next/prev iteration will recall the objects again and again which look dump. Ideally I'd like to collect the list of objects once and then use them without any additional queries. I'm not a JS … -
how do you pass a parameter from post method to decorator?
I'm working a python django and django rest framework + swagger (drf-yasg) project. I need a dynamic decorator. how do you pass a parameter(named in this case "essource") of post method to decorator? def xxx(esSource): source = {} if esSource == 1: source = { 'field_1': openapi.Schema(type=openapi.TYPE_INTEGER) } else: source = { 'field_44': openapi.Schema(type=openapi.TYPE_INTEGER) } properties = { 'type_operator': openapi.Schema(type=openapi.TYPE_INTEGER,description="L'operatore di insieme AND(0) OR(1)"), 'column_to_hide': openapi.Schema(type=openapi.TYPE_STRING,description="L'elenco di colonne da nascondere separato da virgola") } return properties.update(source) class ShowResultsView(views.APIView): @swagger_auto_schema( operation_description="La prima pagina di risultati della ricerca", request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=['type_operator','column_to_hide'], properties=xxx(essource) ), ) def post(self,request,essource,page): resp = {} resp["status"] = 0 resp["data"] = {} resp["message"] = "I risultati della ricerca" return Response(resp,status=status.HTTP_200_OK) I get an error in this line code: properties=xxx(essource) -
Heroku app won't restart after error 14 (Memory quota exceeded)
We have a Django app deployed on Heroku with the following Procfile: release: python manage.py migrate web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug celery: celery -A RDHQ worker -l info Yesterday the app was down and accessing the site returned ERR_CONNECTION_TIMED_OUT. When I looked at the logs, I saw that the celery process was showing an R14 (Memory usage exceeded) error: 2022-12-24T07:14:46.771299+00:00 heroku[celery.1]: Process running mem=526M(102.7%) 2022-12-24T07:14:46.772983+00:00 heroku[celery.1]: Error R14 (Memory quota exceeded) I restarted the dynos a couple of times, but the celery dyno immediately throws the same error after restart. I then removed the celery process entirely from my Procfile: release: python manage.py migrate web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug After I pushed the new Procfile to Heroku, the app is still down! I tried manually scaling down the web dyno and then scaling it up again - nothing. This is what the logs show: 2022-12-24T07:57:26.757537+00:00 app[web.1]: [2022-12-24 07:57:26 +0000] [12] [DEBUG] Closing connection. 2022-12-24T07:57:53.000000+00:00 app[heroku-postgres]: source=HEROKU_POSTGRESQL_SILVER addon=postgresql-reticulated-80597 sample#current_transaction=796789 sample#db_size=359318383bytes sample#tables=173 sample#active-connections=12 sample#waiting-connections=0 sample#index-cache-hit-rate=0.99972 sample#table-cache-hit-rate=0.99943 sample#load-avg-1m=0.01 sample#load-avg-5m=0.005 sample#load-avg-15m=0 sample#read-iops=0 sample#write-iops=0.076923 sample#tmp-disk-used=543600640 sample#tmp-disk-available=72435191808 sample#memory-total=8038324kB sample#memory-free=3006824kB sample#memory-cached=4357424kB sample#memory-postgres=25916kB sample#wal-percentage-used=0.06576949341778418 2022-12-24T07:59:26.615551+00:00 app[web.1]: [2022-12-24 07:59:26 +0000] [12] [DEBUG] GET /us/first-aid-cover/california/ 2022-12-24T07:59:28.421560+00:00 app[web.1]: 10.1.23.217 - - [24/Dec/2022:07:59:28 +0000] "GET /us/first-aid-cover/california/?order_by=title HTTP/1.1" 200 … -
Display related foreign keys in the parent model in Django admin
I'm using PostgreSQL for the DB. I have two models: Project: can contain N Assets. Asset: has a Foreign Key field that points to a Project. An Asset is related to 1 Project. I want the user to be able to set the order of the Assets of a Project in the Django Admin in a handy way like ordering a list in the edit Project screen. The order of the Assets is important in my bussiness logic, but I dont want the user to set the order in each individual Asset (just to improve UX). Is there a way to show a field in the Project admin screen that lists all the Assets that are related to the project and allow the user to order it as he wishes? I did not found any solution to this more than adding a new field in the Asset modal to specify the order and handling the logic by myself (which is expected), however, I don't want it to be a field that have to be changed manually in each individual Asset.