Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
aldjemy/sqlalchemy engine timeout with google cloud
I have a django app where I am using graphql, it's running on google cloud with 60 minutes timeout. The DB is POSTGRES. At some point I had to use sqlalchemy to upload a large csv file to the databse, and graphql is not fast enough for that. 20 minutes into the upload I get the following error: ERROR in app: Exception on / [GET] and Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/urllib3/connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "/layers/google.python.pip/pip/lib/python3.9/site-packages/urllib3/connectionpool.py", line 449, in _make_request six.raise_from(e, None) File "<string>", line 3, in raise_from File "/layers/google.python.pip/pip/lib/python3.9/site-packages/urllib3/connectionpool.py", line 444, in _make_request this is how I am uploading the file: with pd.read_csv("prices.csv", chunksize=500000) as reader: for prices in reader: engine = get_engine(connect_args={'connect_timeout': 3600, 'pool_size': NullPool}) with engine.begin() as conn: conn.exec_driver_sql( f"CREATE TEMPORARY TABLE {temp_table_name} AS SELECT * FROM {table_name} WHERE false" ) prices.to_sql(temp_table_name, conn, if_exists="append", index=False) conn.exec_driver_sql(stmt) engine.execute(f'DROP TABLE "{temp_table_name}"') I do not get the error when i run the code locally and I can't find any reference to the 20 minutes anywhere on google cloud, except for the function timeout, which is set to 60 minutes in my case. -
Django get Models ID from Zip_longest() function data on HTML
I am working a Django application where I have used python zip_longest function with a the for loop for displaying both the Customer Deposits and Withdrawals in an HTML Table, and I want to get the second zipped list item ID unto a url in a button. How do I achieve this. Here is my Model: class Witdrawal(models.Model): account = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) withdrawal_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.account}- Withdrawn - {self.withdrawal_amount}' Here is my first view: @login_required(login_url='user-login') def account_statement(request, id): try: customer = Account.objects.get(id=id) #Get Customer ID customerID = customer.customer.id except Account.DoesNotExist: messages.error(request, 'Something Went Wrong') return redirect('create-customer') else: deposits = Deposit.objects.filter(customer__id=customerID).order_by('-date')[:5] #Get Customer Withdrawal by ID and order by Date minimum 5 records displayed withdrawals = Witdrawal.objects.filter(account__id=customerID).order_by('-date')[:5] context = { "deposits_and_withdrawals": zip_longest(deposits, withdrawals, fillvalue='No Transaction'), } return render(request, 'dashboard/statement.html', context) Here is my HTML code: {% if deposits_and_withdrawals %} <tbody> {% for deposit, withdrawal in deposits_and_withdrawals %} <tr> <td style="background-color:rgba(231, 232, 233, 0.919); color:blue;">Deposit - </td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.acct }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.transID }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">N{{ deposit.deposit_amount | intcomma }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.date … -
How to redirect after deleting a detail view object?
Unable to redirect because the object no longer exists after deletion. URLs: urlpatterns = [ # home page path('', views.index, name='index'), path('forums/forum_create/', views.forum_create, name='forum_create'), path('forums/forum_edit/<int:id>/', views.forum_edit, name='forum_edit'), path('forums/forum_delete/<int:id>/', views.forum_delete, name='forum_delete'), path('forums/<int:id>/', views.thread_list, name='thread_list'), path('thread/<int:year>/<int:month>/<int:day>/<slug:thread>/', views.thread_detail, name='thread_detail'), path('thread_comment/<int:id>/', views.thread_comment, name='thread_comment'), path('thread_create/<int:id>/', views.thread_create, name='thread_create'), path('thread_edit/<int:id>/', views.thread_edit, name='thread_edit'), path('thread_delete/<int:id>/', views.thread_delete, name='thread_delete'), path('search/', views.site_search, name='site_search'), ] view: def thread_list(request, id): forum = Forum.objects.get(id=id) threads = forum.threads.all() paginator = Paginator(threads, 20) page_number = request.GET.get('page', 1) try: threads = paginator.page(page_number) except PageNotAnInteger: threads = paginator.page(1) except EmptyPage: threads = paginator.page(paginator.num_pages) return render(request, 'forum/thread_list.html', {'forum': forum, 'threads': threads}) (...) # cut @login_required def thread_delete(request, id): thread = get_object_or_404(Thread, id=id) forum = thread.forum if request.method == 'POST': thread.delete() return redirect('forum/thread_list.html', id=forum) return render(request, 'forum/thread_delete.html', {'thread': thread, 'forum': forum}) thread_delete.html: {% extends 'forum/base.html' %} {% block content %} <h1 class="mt-5 pb-4">Forums > Threads > Delete {{ thread.title }}</h1> <p>Are you sure you want to delete thread "{{ thread.title }}"? All replies and other associated objects will be deleted along with it.</p> {% load django_bootstrap5 %} <form action="" method='post'> {% csrf_token %} {% bootstrap_button button_type="submit" content=" Confirm and delete" %} </form> {% endblock content %} The forum = thread.forum will not work because thread. no longer exists after deletion? This … -
how do you use docker to install packages (trying to install flake8 to help me debug) locally to keep the image as light as possible
I am trying to install flake8, to help me debug but it's not installing, note that I do not want to install it in the image here is my docker-compose.yml version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" Dockerfile FROM python:3.9-alpine3.13 LABEL maintainer="jcmbisa" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true"]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user reuirement.txt Django>=4.0.10,<4.1 djangorestframework>=3.12.4,<3.13 requirement.dev.txt flake8>=3.9.2,<3.10 ready to learn thanks -
Django duplicate tables with multiple databases
I have multiple databases one is sqlite and the others in postgresql using one app, when i migrate bases 'using routers' all the tables in models.py gets created in all the bases including sqlite or nothing if i added return false to the allow_migrate function. how to stop duplicate tables from happening ?? this is my code 'example' settings.py DATABASE_ROUTERS = ['routers.router.sqlite_Router','routers.router.postgres_router_1','routers.router.postgres_router_2'] DATABASES = { 'default': {}, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'postgres_db_1': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=test' }, 'NAME': 'test1', 'USER': 'postgres', 'POSRT':'5432', 'PASSWORD': 'postgres', 'HOST':'localhost', }, 'postgres_db_2': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=test' }, 'NAME': 'test2', 'USER': 'postgres', 'POSRT':'5432', 'PASSWORD': 'postgres', 'HOST':'localhost', } } router.py class sqlite_Router: route_app_labels = {'auth', 'contenttypes','admin','sessions','messages','staticfiles'} database = 'auth_db' .... def allow_migrate(self, db, app_label, model_name=None, **hints): model = hints.get('model') if model: usedb = getattr(model._meta, 'database', None) if app_label in self.route_app_labels and usedb == self.database: return db == self.database # True #else: return False # <== i only get django_migrations, no other tables return None class postgres_router_1: route_app_labels = {'test'} database = 'postgres_db_1' .... def allow_migrate(self, db, app_label, model_name=None, **hints): model = hints.get('model') if model: usedb = getattr(model._meta, 'database', None) if app_label in self.route_app_labels and … -
Formsets are returning as valid=False and not saving
I'm trying to create a form that allows teachers to create lessons, which are linked to multiple activities (ManyToMany), which are in turn linked to many Items (ForeignKey). As such, I am using formsets for activities and items. However, activity_formset is coming back as invalid and not saving. The View class N_LessonEditAllView(LoginRequiredMixin, UpdateView): model = Lesson template_name = 'lessons/edit-lesson.html' form_class = LessonForm def get_object(self): return get_object_or_404(Lesson, pk=self.kwargs.get('pk')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) lesson = self.get_object() activity_formset = ActivityFormSet(queryset=lesson.activity.all()) item_formsets = [] for activity_form in activity_formset: item_formset = ItemFormSet(queryset=Item.objects.filter(activity_id=activity_form.instance.id)) item_formsets.append(item_formset) context['activity_formset'] = activity_formset context['item_formsets'] = item_formsets return context def form_valid(self, form): context = self.get_context_data() activity_formset = context['activity_formset'] item_formsets = context['item_formsets'] print('activity_formset is valid:', activity_formset.is_valid()) print('activity_formset errors:', activity_formset.errors) for activity_form in activity_formset: item_formset = ItemFormSet(queryset=Item.objects.filter(activity_id=activity_form.instance.id)) item_formsets.append(item_formset) print(f'activity_formset for activity {activity_form.instance.id} is valid: {item_formset.is_valid()} --- data {activity_formset.data} --- errors: {activity_formset.errors} --- payload {self.request.POST}') if activity_formset.is_valid() and all(item_formset.is_valid() for item_formset in item_formsets): self.object = form.save() activity_formset.instance = self.object activity_formset.save() print('Form is valid:', form.is_valid()) print('Activity formset is valid:', activity_formset.is_valid()) for item_formset in item_formsets: print('Item formset is valid:', item_formset.is_valid()) item_formset.instance = self.object item_formset.save() raise ValueError('Intentional error') print(form.cleaned_data) return super().form_valid(form) else: return self.form_invalid(form) The Template <div class="card"> <form method="post"> <div class="card-header"> {% csrf_token %} {{ form|crispy … -
How to make Django ModelForm filed to update the attrs, so the style can be displayed successfully
from django.forms import ModelForm from django import forms from .models import Project class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags'] widgets = { 'tags': forms.CheckboxSelectMultiple(), } def __int__(self, *args, **kwargs): super().__int__(*args, **kwargs) # self.fields['title'].widget.attrs.update({'class': 'input'}) for name, field in self.fields.item(): field.widget.attrs.update({'class': 'input'}) I AM TRYING TO DISPLAY MY DYNAMIC FORM WITH THE CORRECT STYLING, BUT THIS METHOD DOESN'T SEEM TO WORK Does anybody know how to fix it? Thank you so much for the help in advance ` def __int__(self, *args, **kwargs): super().__int__(*args, **kwargs) # self.fields['title'].widget.attrs.update({'class': 'input'}) for name, field in self.fields.item(): field.widget.attrs.update({'class': 'input'})` This doesn't seem to work -
Displaying an image stored in a Django database
I have a website dedicated to pets (dead ones), and I have some stock images in the database stored under the pet using a manytomany field (so, any number of pets can be in an image, and a pet can have any number of images associated with it--seems logical so far). I am trying to display the pet photos in any way at all in one of the templates. My problem is, I have NO IDEA what the correct syntax for iterating over a context_dictionary data structure I have made to store pets and pet photos for the purpose of accessing in the associated template file. I am having to do this because I think (correct me if I'm wrong) a view can only have one associated model, and I need a few models, their data, to display in one view. So. It is what it is. I think it's probably about time I showed some of my code. Here is one after another: pet_profile/models.py from django.db import models from django.utils.crypto import get_random_string import uuid from django.urls import reverse class PetPhoto(models.Model): slug = models.SlugField(max_length = 5, primary_key = True, blank = True, null=False) title = models.CharField(max_length = 255) id = … -
Incorrect floating label positioning on responsive input form
I've created a form using Django, Crispy Forms and Bootstrap. At screen widths above 575px the form and labels look as expected with fields of the correct width and floating labels in the correct position, however at screen widths below 575px the floating labels appear in the wrong position. I'd appreciate any guidance as to how I can make the floating labels remain in the correct position relative to the input field regardless of screen width. Expected: >575px Unexpected: <575px I believe this happens because, in order to force the responsive resizing of the input fields, I manually amended the CSS to reduce the the field width to 85% at screen widths lower than 575px by using a media query as follows: CSS .form-floating { position: relative; } .form-floating > .form-control, .form-floating > .form-select { height: calc(3.5rem + 2px); line-height: 1.25; } .form-floating > label { position: absolute; top: 0; left: 0; height: 100%; padding: 1rem 0.75rem; pointer-events: none; border: 1px solid transparent; transform-origin: 0 0; transition: opacity 0.1s ease-in-out, transform 0.1s ease-in-out; } @media (max-width: 575px) { .form-floating > .form-control, .form-floating > .form-select { display: block; width: 85%; padding: 0.375rem 0.75rem; margin: 0 auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: … -
Django model-chain, im not reaching bottom from top
class Firma(models.Model): #company isim = models.CharField(max_length=20) def __str__(self): return f"{self.isim}" class Proje(models.Model): #project isim = models.CharField(max_length=20) #name projeBedeli = models.DecimalField(max_digits=20, decimal_places=0) #total project cost projeKalantutar = models.DecimalField(max_digits=20, decimal_places=0) #remaining project cost projeTarih = models.DateField() #project date firma = models.ForeignKey(Firma, on_delete=models.CASCADE) #company def __str__(self): return f"{self.isim} {self.projeBedeli} {self.projeKalantutar} {self.projeTarih}" class Odeme(models.Model): #payment hakedisAdi = models.CharField(max_length=20) #WpName hakedisTutar = models.DecimalField(max_digits=20, decimal_places=0) #WpPrice hakedisTarih = models.DateField() #Date proje = models.ManyToManyField(Proje, through='Santiye') #project def __str__(self): return f"{self.hakedisAdi} {self.hakedisTutar} {self.hakedisTarih} {self.proje}" class Araclar(models.Model): #tools tip = models.CharField(max_length=20) #type def __str__(self): return f"{self.tip}" class Santiye(models.Model): #Work field butce = models.ForeignKey(Odeme, on_delete=models.CASCADE, null=True, default=0) #budget proje = models.ForeignKey(Proje, on_delete=models.CASCADE) #project isim = models.CharField(max_length=50) #name araclar = models.ManyToManyField(Araclar) #tools def __str__(self): return f"Birim : {self.isim} / Şantiye Bütçesi : {self.butce} / Bağlı Olduğu Proje : {self.proje} / Kullanılan Araçlar : {self.araclar}" class Personel(models.Model): #Workers ad = models.CharField(max_length=50) #name cinsiyet = models.CharField(max_length=10) #gender yas = models.DecimalField(max_digits=4, decimal_places=0) #age baslamaTarih = models.DateField() #date resim = models.FileField(default="static/images/avatar.jpg") #avatar birim = models.ForeignKey(Santiye, on_delete=models.CASCADE, null=True, default='') #which work field def __str__(self): return f"{self.ad} {self.cinsiyet} {self.yas} {self.baslamaTarih} {self.birim}" I am not sure this models.py perfectly fits with this diagram to be honest.. Here is the link of ERD Diagram : https://ibb.co/7GchYCM Actually I want … -
wfastcgi-enable.exe is not recognize on python 3.10.10
How can I configure a Django Project on IIS without wfastcgi.py? I don't found any wfastcgi.py in python's 3.10.10 folder. Anyone could help me? I tried at least 5 tutorials on youtube, but everyone requires wfastcgi.py. I've expected anyone could help me to solve this issue. -
Html Form Posting Values to Django Backend only when submitted twice, or rather hit back to form and then submit again
So I have stumbled upon a case where my form does not post values after I click the submit button once, it goes to the next page indeed but my Django View can not fetch the post values. But soon after I hit back button on browser and then clicks the submit button again it works ; I can then see the POSTed values in my DJango Views. Here's my HTML form. (Please note I have removed the unnecessary code which is long) <form action="" method="POST" id="quizform"> {% csrf_token %} <fieldset class="cfield" id="box1"> <p id="question" class="fs-title"> 1. {{data.0.question}}</p> <div class="row"> <div class="{% if data.0.correct_answer2 == "" %}col-12{% else %}col-9{% endif %}"> <div class="form-check"> <label class="form-check-label"> <img id="a1-icon-{{data.0.pk}}" src="/static/assets/img/correct.png" class="answer_icon" width="20px" style="z-index: 99;" hidden> <input id="a1{{data.pk}}" style="z-index: -1;" type="radio" class="radiobox form-check-input radio-box ans" name="q{{data.0.pk}}" qid="{{ data.0.pk }}" value="{{data.0.a1}}" required {% if data.0.correct_answer2 != "" %}disabled{% endif %}> <span class="cspan" style="color: white;">TES</span> </label> <span id="a1" class="cspan">{% if data.0.a1_image.url != None %}<img src="{{ data.0.a1_image.url }}" class="" width="100px">{% endif %} {{data.0.a1}} </span> </div> <div class="form-check"> <label class="form-check-label"><img id="a2-icon-{{data.0.pk}}" src="/static/assets/img/correct.png" class="answer_icon" width="20px" style="z-index: 99;" hidden> <input id="a2{{data.pk}}" style="z-index: -1;" type="radio" class="radiobox form-check-input radio-box ans" name="q{{data.0.pk}}" qid="{{ data.0.pk }}" value="{{data.0.a2}}" required {% if data.0.correct_answer2 != "" … -
My comment form does not appear on the template page (django)
My codes work on local but not work on the net :) Here is my simple django blog website. When i tested these codes work but when i try live version, it doesnt work. Where is the my fault? If you wanna see the live page you can look this page https://www.endustri.io/kaynak-perdesi-nedir-ne-ise-yarar-cesitleri-fiyatlari/ I added two types comment section the template page but none of them work. Here is my codes; blog post codes page (detail.html) {% extends 'blog/base1.html' %} {% load static %} {% block content %} <head>{% block title %}<title>{{ post.title }} - Endustri.io</title>{% endblock %}</head> <div class="card"> <h5 class="card-header">{{ post.title }}</h5> <div class="card-body"> <h6 class="card-title">Yazar: {{ post.author.first_name }} {{ post.author.last_name }} - Tarih: {{post.date_added}} - Kategori: <a href="{% url 'category' post.category.slug %}"> {{ post.category.title }}</a> <hr/></h6> <p class="card-text">{{ post.body|safe }}</p> </div> </div> <div class="card"> <h5 class="card-header">Yorumlar</h5> <div class="card-body"> <h6 class="card-title"> {% for comment in comments %} <article> <strong>{{ comment.name}} at {{ comment.date_added }}</strong></br> {{ comment.body }} </article> {% endfor %}</h6> </div> </div> <form method="POST" class="form-group"> {% csrf_token %} {{ form.as_p }} <button type="submit">Yorum Ekle</button> </form> <br> <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} <button type="submit">Add comment</button> </div> </form> {% endblock %} Comment model class Comment(models.Model): … -
(No asignation direction ipv6 in docker) /usr/bin/env: ‘bash\r’: No such file or directory
Soy nuevo en esto, estoy tratando de clonar un repositorio de GitHub, trabajo con el docker, en el powershell, creo la carpeta, descargo el repositorio, abro la carpeta del repositorio, ejecuto la instrucción docker compuse build, pero al ejecutar el docker compouse up, me da la direccion ipv4 pero la direccion ipv6 no, en el docker me crear los contenedores pero al iniciarlos, no hace nada. Intenté de nuevo, creando otra carpeta, sigue igual -
How to decode uidb64 from activation link's url Django
i hope you are all doing well. I am working on a django project with MySQL. I am working on the signup part for the candidate with an activation link sent in the email. When i connected django to MySQL Workbench, It generated a Model file including the "Candidats form" which iam using in my view. The problem is that i cannot decode the uidb64 from the url. I can send a link in the email but it always return "Activation went wrong" and when i debugged my code i found out that my methid is not returing the uid but None. This is my view.py from django.urls import reverse from .tokenssss import token_generator from django.core.mail import EmailMessage from django.contrib.sites.shortcuts import get_current_site from django.shortcuts import render from django.http import HttpResponse from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.views import View from .models import Candidats, Recruteurs # Create your views here. def sign_up_candidat(request): if request.method == "POST": nom = request.POST.get('nom') prenom = request.POST.get('prenom') date = request.POST.get('date') sexe = request.POST.get('sexe') telephone = request.POST.get('telephone') email = request.POST.get('email') password = request.POST.get('pass') password_c = request.POST.get('pass_c') if password != password_c: return HttpResponse("Confirmation password went wrong") else: my_user = Candidats(nomcandidat=nom, prenomcandidat=prenom, datenaissance=date, sexe=sexe, … -
Is there anyway to activate 'venv' on Pycharm?
**Hello i'm using pycharm for Django on windows and when i use this code .\venv\Scripts\activate system shows me this error this is my error what should i do to activating my virtual enviroment ** i just try this code .\venv\Scripts\activate -
How to properly extend user model in Django
I am working on a Django employee management system, I want the employee bio data on the same table as the user object used for registration and login I tried adding the user model as a OnetoOneField on the employee table, but I don’t like having to register the user and then fill the employee form separately. I want the users to be able to create their bio data while creating an account -
Trying to retrieve array from django QueryDict
I want to transfer an array from an Inertia form array to django. In the debug window it's shown as test[0] = 1, test[1] = 2. Neither calling request.POST.get("test") nor request.POST.getlist("test") nor request.POST.getlist("test[]") returns me a usable list. My form object looks as follows (data is hard coded for test purposes): let form = useForm({ "test": [1, 2, 3] }) -
I'm trying to deploy a django site on a hosting. But I don't have SSH access. Are there any other options to do this? [closed]
Я пытаюсь задеплоить сайт на джанго на хостинг. Но у меня нет доступа к SSH. Есть какие нибудь другие способы это сделать? How to deploy django project on host without usinng SSH? Я пытался через wsgi/ htaccess. Но что то не получилось ничего -
psql Cannot open extension control file, but the file exists
psql command line: postgres=# CREATE EXTENSION pg_tgrm; ERROR: extension "pg_tgrm" is not available DETAIL: Could not open extension control file "C:/Program Files/PostgreSQL/15/share/extension/pg_tgrm.control": No such file or directory. HINT: The extension must first be installed on the system where PostgreSQL is running. postgres=# yum install postgresql14-contrib postgres-# CREATE EXTENSION pg_tgrm; The directory: enter image description here What am I doing wrong? The file is definately there and I've installed it on another postgresql server just beforehand on the same machine? This is for a Django project on Windows 11. Tried to install the pg_tgrm; extension and expected it to work. -
Cannot import models into view.py
I have following models.py and views.py . I am trying to change the date to workweek in views file. But when i try to import date , I get the following error: NameError at / name 'date' is not defined Any idea why ?? and how to fix it ?? ---------models.py--------------->> class metric(models.Model): metric = models.CharField(max_length=200) date = models.DateField() value = models.FloatField() goal = models.FloatField() Mowner = models.CharField(max_length=200) ---------views.py ---------------->> from dashboard.models import * from .models import metric import pandas as pd from plotly.offline import plot import plotly.express as px from datetime import datetime def index(request): # Convert date to workweek weeks = [] for date_str in date: date_obj = datetime.strptime(date_str, '%d-%m-%Y') week_num = date_obj.isocalendar()[1] weeks.append(week_num) I tried importing the metrics in views.py file in different ways but still doesnot seem to work . -
How to set a rate limit a specific query in Django?
I have a multithreading function that looks up and locks each item in a list. (I'm locking the query for each individual item so that other users can't hit it at the same time). I also want to limit the rate in which users can look up a specific item, i.e. item1 was just searched so I don't want anyone else to be able to query item1 for 3 minutes. def worker(): """ Item search Multithreading Function """ while True: item = q.get() try: with transaction.atomic(): """ Lock the API for specified item search """ locked = Models.objects.filter(name__icontains=item)[0] locked_search = Models.objects.select_for_update().get(pk=locked.pk) print("Search for " + str(locked_search) + ", " + str(item) + " is locked") ### ADD SERVER RATE LIMIT FOR ITEM SEARCHED HERE ### # ... Do work here I've looked into Django Throttling and django-ratelimit but can't seem to find anything that limits the query rate of particular object. Anyone have any experience in this? Thank you for your help -
Django running function every minutes even without request
I want to write a web application with django. The user choose a specific function (which is defined by developer) and gives the necessary arguments and a frequency (e.g. every 1 minute). Now Django should call the function every 1 minutes and save the required output in database. So I want to ask how can I do scheduling using Django? I heard something about Celery. However, I'm looking for an easier solution. I don't want to end up with queue and messaging concepts! -
Creating multiple objects in DRF failing with error "'int' object has no attribute 'pk'"
I use ListCreateAPIView to create new instances of the Review model. Running my code in debug mode I can see that once the line serializer.is_valid(raise_exception=True) is executed, the code fails with the error AttributeError: 'int' object has no attribute 'pk'. models.py class App(models.Model): name = models.CharField(max_length=200, unique=True) identifier = models.CharField(max_length=200, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) image_url = models.URLField(blank=True, null=True) image_file = models.ImageField( upload_to='images/app_icons/', blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): """ Custom save method which fetches the image_file from the image_url, if image_file does not exist """ if self.image_url and not self.image_file: image = urllib.request.urlopen(self.image_url).read() self.image_file.save(self.name + '.jpg', ContentFile(image), save=False) super().save(*args, **kwargs) class Review(models.Model): comment = models.TextField() rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) review_id = models.IntegerField(unique=True) review_date = models.DateTimeField() review_author = models.CharField(max_length=200) app = models.ForeignKey( App, on_delete=models.CASCADE, related_name='reviews') serializers.py class ReviewListSerializer(serializers.ListSerializer): def create(self, validated_data): items = [Review(**item) for item in validated_data] return Review.objects.bulk_create(items) class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = '__all__' list_serializer_class = ReviewListSerializer views.py class ReviewList(generics.ListCreateAPIView): """Retrieves lists of reviews and creates new reviews Default list method is modified to: - Return count of data under key 'count' """ queryset = Review.objects.all() serializer_class = ReviewSerializer def create(self, request, *args, **kwargs): data = request.data … -
Django CBV with DropzoneJS and django-storages backend for multifile upload form won't validate
I am using django-storages with (GCS backend) and would like to be able to use DropZonejs to upload multiple files to a model that has a FK. This is where I've gotten so far. It always comes back what Bad Request, form not valid. Assuming you're getting to this view from a detail view that includes a pk for 'thing'. (the backend works just fine uploading through django admin) Models.py class Thing(models.Model): name = models.CharField(max_length=25, verbose_name="name") def image_dir_path(instance, filename): # specify file naming return 'folder/{}/{}'.format(instance.thing, filename) class Image(MetadataFields): thing = models.ForeignKey(Thing, on_delete=models.DO_NOTHING, related_name="things", verbose_name=_("Thing")) my_image = models.ImageField(upload_to=image_dir_path, null=True, blank=True, verbose_name=_("My image")) Forms.py class ImageForm(forms.ModelForm): class Meta: model = Image fields = '__all__' widgets = { 'my_image': forms.ClearableFileInput( attrs={'multiple': True}), } Views.py class ImageUploadView(FormView): form_class = ImageForm template_name = "appname/_uploadimages.html" def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file') # thing= self.kwargs.get('pk') if form.is_valid(): for uploaded_image in files: # image = models.Image.objects.create(thing=thing, my_image=uploaded_image) image = models.Image() image.my_image = uploaded_image thing_instance= models.Thing.objects.get(id=self.kwargs.get('pk')) image.thing= thing_instance image.save() return HttpResponse('Image upload succeeded.') return HttpResponseBadRequest("Image upload form not valid.") Urls.py path('thing_detail/<int:pk>/view/', views.ThingDetail.as_view(), name='thing_detail'), path('thing/<int:pk>/image/upload/', views.ImageUploadView.as_view(), name='image_upload'), _uploadimages.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> …