Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to relate two Django models without Foreign Key in Django Rest Framework using PostgreSQL DB
If I was to have two Django models as shown below with Book related to Category, how else can i show the relation without using a Foreign Key when using Django Rest Framework using PostgreSQL DB to make the Foreign Key field editable in a HTML form? CATEGORIES = [ ('Fiction', ('Fiction')), ('Non-Fiction', ('Non-Fiction')) ] class Category(models.Model): category_name = models.CharField(max_length=255, choices=CATEGORIES) class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) pages = models.IntergerField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) My challenge comes up in the DB when in the book table the category column in represented as category_id which are integers. This creates a problem as when performing CRUD functions especially EDIT since i can't edit the category from the front-end in a form because it's represented as i.e. 1,2,3..... instead of the actual categories. I want to achieve this with a REST API. My serializer class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' My API views @api_view(['POST']) def AddBookAPI(request): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT']) def EditBookAPI(request, id): book_record =get_object_or_404(Book, id=id) serializer = BookSerializer(instance=book_record, data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_304_NOT_MODIFIED) @api_view(['DELETE']) def DeleteBookAPI(request, id): book = get_object_or_404(Book, id=id) book.delete() … -
No reverse after trying the correct parameters
i've been getting the NoReverseMatch Error but everything seems correct. i tried the link it generated and it works but using get_absolute_url always gives the NoReverseMatch Error. This is my models.py: from django.db import models from django.db.models.expressions import OrderBy from django.db.models.fields import CharField, EmailField from phonenumber_field.modelfields import PhoneNumberField from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. ############announcements######### class Announcement(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) DEPARTMENTS = ( ('appost', 'Appointments and Posting'), ('bdgt', 'Budget, Planning, Research and Statistics'), ('mgt', 'Management Services'), ('psn', 'Personnel'), ('tmd', 'Training and Manpower Development'), ('gen', 'General Public'), ) graphics = models.ImageField( upload_to='media/Announcements' ) title = models.CharField(max_length=250) slug = models.SlugField( max_length=250, unique_for_date='publish' ) announcer = models.CharField(max_length=30) due_date = models.DateTimeField(default=timezone.now) department = models.CharField( max_length=44, choices=DEPARTMENTS, default='appost' ) audience = models.CharField(max_length=50) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft' ) def __str__(self): return f'{self.title} - {self.slug}' def get_absolute_url(self): return reverse('web:ann_details',args=[self.title]) and this is my urls.py: from django.contrib import admin from django.urls import path from web import views app_name = 'web' urlpatterns = [ path('search',views.search,name="search"), path('profile',views.profile,name="profile"), path('principals',views.principals,name='principals'), path('announcement/<str:title>',views.announcement_details,name='ann_details') ] this is the error: NoReverseMatch at /principals Reverse for 'ann_details' … -
Is the remote host causing an import error?
abstract My vps server is constantly throwing errors. Apparently the other person is accessing and causing an import error, but I don't know if my server is the cause. detail When I try whois ip, it seems to be a foreigner (not Japanese) Can these be left alone? [Wed Oct 20 00:58:08.247129 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] mod_wsgi (pid=1458): Exception occurred processing WSGI script '/var/www/html/portfolio/mysite/mysite/wsgi.py'. [Wed Oct 20 00:58:08.253151 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] Traceback (most recent call last): [Wed Oct 20 00:58:08.253237 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] File "/var/www/html/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner [Wed Oct 20 00:58:08.253241 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] response = get_response(request) [Wed Oct 20 00:58:08.253245 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] File "/var/www/html/venv/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__ [Wed Oct 20 00:58:08.253248 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] response = self.process_request(request) [Wed Oct 20 00:58:08.253252 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] File "/var/www/html/venv/lib/python3.8/site-packages/django/middleware/common.py", line 53, in process_request [Wed Oct 20 00:58:08.253254 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] if self.should_redirect_with_slash(request): [Wed Oct 20 00:58:08.253258 2021] [wsgi:error] [pid 1458:tid 139712947496704] [remote 185.191.171.24:62800] File "/var/www/html/venv/lib/python3.8/site-packages/django/middleware/common.py", line 70, in should_redirect_with_slash [Wed Oct 20 00:58:08.253261 2021] [wsgi:error] [pid 1458:tid … -
view must be a callable or a list/tuple when using decorators
After I created a decorator to forbid a logged user to access the login page this error started to appear when I run the server: File "/home/user1/Dev/sites/pai/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/user1/Dev/sites/pai/planeja_tere/publications/urls.py", line 7, in <module> path('login/', views.loginPage, name='login'), File "/home/user1/Dev/sites/pai/lib/python3.8/site-packages/django/urls/conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). my urls.py: from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('publications/', views.Publications, name='publications'), path('login/', views.loginPage, name='login'), path('logout/', views.logoutUser, name='logout'), path('register/', views.registerPage, name='register'), ] views.py: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.forms import inlineformset_factory from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import CreateUserForm from .decorators import unauthenticated_user # Create your views here. … -
django tenant with abstract user and auth
I'm running into an issue should the auth and abstract users be in the tenant apps and note in the shared apps, because i'm able to once User1 is connected to his tenant1 he is actually able to access tenant2 urls thanks in advance -
get_absolute_url gives unsupported format character 'O' (0x4f) at index 13 error
i created a get_absolute_url method for a model and whenever it appears on a template i get unsupported format character 'O' (0x4f) at index 13 error this is my models.py: from django.db import models from django.db.models.expressions import OrderBy from django.db.models.fields import CharField, EmailField from phonenumber_field.modelfields import PhoneNumberField from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PrincipalOfficial(models.Model): STATUS_CHOICE = ( ('on', 'Active'), ('off', 'Not_active') ) DEPARTMENTS = ( ('appost', 'Appointments and Posting'), ('bdgt', 'Budget, Planning, Research and Statistics'), ('mgt', 'Management Services'), ('psn', 'Personnel'), ('tmd', 'Training and Manpower Development'), ) Profile_image=models.ImageField(upload_to="media/Officials") First_name = models.CharField(max_length=30) Last_name = models.CharField(max_length=30) date_of_birth = models.DateField() bio = models.TextField(max_length=5000) portfolio = models.CharField(max_length=50) status = models.CharField(max_length=10, choices=STATUS_CHOICE, default='off') department = models.CharField(max_length=50, choices=DEPARTMENTS) academic_achievements =models.TextField(max_length=250) trainings_attended = models.TextField(max_length=250) def __str__(self): return f'{self.First_name} - {self.Last_name}' def get_absolute_url(self): return reverse('web:principal_details',args=[self.First_name]) and this is my urls.py: from django.contrib import admin from django.urls import path from web import views app_name = 'web' urlpatterns = [ path('search',views.search,name="search"), path('profile',views.profile,name="profile"), path('principals',views.principals,name='principals'), path('principal%20Officials/<str:First_name>',views.principal_details,name='principal_details'), ] i have no idea where this error is coming from but i think it has to do with an a char i have to escape but i can't find where that would even come in -
how can i redirect user own 'post-detail' url in UpdateView class...?
views.py class PostUpdateView(LoginRequiredMixin , UpdateView): model = Post template_name = 'blog/post_create.html' fields = ['title', 'content' ] # after post request url success_url = 'post-detail' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): Post = self.get_object() if self.request.user == Post.author: return True return False this 'success_url' don't work i need - a user after update own post than redirect own post detalis page (this url :-"path('post/int:pk/', PostDetailview.as_view(), name='post-detail')") urls.py from django.urls import path from .views import ( PostListView, PostDetailview, PostCreateView, PostUpdateView, PostDeleteView, about ) urlpatterns = [ path('', PostListView.as_view(), name='home'), path('post/<int:pk>/', PostDetailview.as_view(), name='post-detail'), path('post/create', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete', PostDeleteView.as_view(), name='post-delete'), path('about/', about, name='about'), ] -
How to print list data in next line in Django
Here i am getting some data into list through for loop and this should be printed in next line Let us consider my views.py as def items_log(request, pk): logg = [] client = request.user.client items_log = JobItemsLogs.objects.filter(client=client,item_id=pk).order_by('-id')[:5] for x in items_log: log_text = 'Type of entry: {0} - date: {1}; Created by: {2}'.format( x.type_of_entry,x.created_at.date(),x.created_by) logg.append(log_text) ... ... ... Now let us consider by index.html as <div class="span4"> <div class="well"> <ul class="nav nav-list"> <li class="nav-header" >Log entries</li> {% for i in logg %} {{i}} {% endfor %} </ul> </div> </div> Here how its getting displayed is how i wanted to display is Type of entry: Plumbing - date: 2021-11-02; Created by: A Krishna* Type of entry: Plumbing - date: 2021-11-02; Created by: A Krishna* Type of entry: None - date: 2021-07-28; Created by: A Krishna* Type of entry: None - date: 2021-07-28; Created by: A Krishna* Type of entry: None - date: 2021-07-28; Created by: A Krishna* Each of these list data should be seen in new lines -
Auto generate an access_token when expired in python or django itself
How can one auto regenerate a refresh_token within a django admin app, am using simple jwt package, but I want to track if the token has expired then I send a request to auto generate a new acces_token, when the session is still on. Yes I know this can be achieved on the frontend, forexample like in javascript we can use axios interceptors, to auto get another access_token, so how can one do this in django it's self. -
how do I turn a function into a class and pass the form to a Django?
in my Django project i have a function: def retail_product_detail(request, slug): context = { 'product_retail': get_object_or_404(Product, slug=slug), 'cart_product_form': CartAddProductRetailForm(), 'related_products': Product.objects.filter(category__slug=self.kwargs['slug']) } return render(request, 'retail/single_product_retail.html', context) how can i turn it into class RetailProductDetail and pass the form to be displayed? i tried: class RetailProductDetail(FormView): template_name = 'retail/single_product_retail.html' context_object_name = 'product_retail' form_class = CartAddProductRetailForm def get_queryset(self): return Product.objects.filter(category__slug=self.kwargs['slug']) def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['product_retail'] = Product.objects.get(slug=self.kwargs['slug']) context['related_products_1'] = Product.objects.select_related('tag').all() return context But form doesn't works. In template: <form action="{% url 'cart_add_retail' slug=product_retail.slug %}" method="post"> {{ cart_product_form }} {% csrf_token %} <br> <input class="btn btn-outline-dark flex-shrink-0" type="submit" value="Add to cart> </form> How can I fix it? -
How to improve Django N+1 problem for data export?
I am trying to export data as CSV and for that purpose need to query thousands of model instances. Without any optimisations, my code can export ~700 instances and their related statuses. Any more and the server times out with a 502 - Bad Gateway error. Adding prefetch_related('statuses') improved performance, but it still crashes when selecting more than ~1000 instances. Statuses 200 and 300 can be missing or exist multiple times. Otherwise I could ditch the line obj.statuses.filter(status=status_number).first() and simply append them in order, but I think it is necessary here. How can I improve performance for this code snippet? Or am I using prefetch_related() incorrectly? # models.py class MyExportModel(models.Model): id = models.PrimaryKey() name = models.CharField(max_length=255) class StatusModel(models.Model): STATUS_CHOICES = [ (100, 'created'), (200, 'paid'), (300, 'cancelled'), (400, 'billed'), (500, 'completed') ] export_model = models.ForeignKey('MyExportModel', related_name='statuses', on_delete=models.CASCADE) number = models.IntegerField(choices=STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) # export_as_csv.py def export_as_csv(writer, queryset): # Write headings into CSV writer.writerow(['id', 'name'] + [f'{number} - {name}' for (number, name) in StatusModel.STATUS_CHOICES]) # Iterate over all selected models and their related statuses for obj in queryset.prefetch_related('statuses'): fields = [obj.id, obj.name] # Append date for statuses if known (problematic section) for (status_number, _) in StatusModel.STATUS_CHOICES: status = obj.statuses.filter(status=status_number).first() fields.append(status.created … -
How to configure waitress in Procfile to deploy a Django app on Heroku?
I am using Windows, and so far I know that gunicorn is not working on Windows, I've tried it and it doesn't work. I've seen that waitress is a good alternative for gunicorn on Windows. Running this locally works fine to start a server: waitress-serve --port=*:8000 EnergyManagement.wsgi:application And I've pasted it in the Procfile like this: web: waitress-serve --port=*:8000 EnergyManagement.wsgi:application When I deploy it on Heroku, I see these errors in heroku logs --tail: 2021-11-03T13:01:24.553794+00:00 heroku[web.1]: Starting process with command `waitress-serve --port=*:8000 EnergyManagement.wsgi:application` 2021-11-03T13:01:26.003543+00:00 heroku[web.1]: Process exited with status 1 2021-11-03T13:01:26.067675+00:00 heroku[web.1]: State changed from starting to crashed 2021-11-03T13:01:25.798582+00:00 app[web.1]: Traceback (most recent call last): 2021-11-03T13:01:25.798610+00:00 app[web.1]: File "/app/.heroku/python/bin/waitress-serve", line 8, in <module> 2021-11-03T13:01:25.798712+00:00 app[web.1]: sys.exit(run()) 2021-11-03T13:01:25.798724+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/waitress/runner.py", line 298, in run 2021-11-03T13:01:25.798888+00:00 app[web.1]: _serve(app, **kw) 2021-11-03T13:01:25.798904+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/waitress/__init__.py", line 13, in serve 2021-11-03T13:01:25.798982+00:00 app[web.1]: server = _server(app, **kw) 2021-11-03T13:01:25.798990+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/waitress/server.py", line 49, in create_server 2021-11-03T13:01:25.799064+00:00 app[web.1]: adj = Adjustments(**kw) 2021-11-03T13:01:25.799066+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/waitress/adjustments.py", line 325, in __init__ 2021-11-03T13:01:25.799178+00:00 app[web.1]: setattr(self, k, self._param_map[k](v)) 2021-11-03T13:01:25.799194+00:00 app[web.1]: ValueError: invalid literal for int() with base 10: '*:8000' 2021-11-03T13:01:31.000000+00:00 app[api]: Build succeeded 2021-11-03T13:03:11.184360+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=energy-management-backend.herokuapp.com request_id=1335c13a-c017-4d92-b8d3-87f7bbea54d1 fwd="193.226.6.228" dyno= connect= service= status=503 bytes= protocol=https … -
Associar dados entre duas models no django
Queria saber se alguém sabe como que posso puxar o nome do estádio do da class Estadio para a class PrecoFinal. Eu tenho uma página que puxa o nome do estádio e pergunta a data de quando o usuário quer agendar ele, porém, na hora de salvar essa data, queria salvar o nome do estadio junto para poder mostrar em outra página, esse nome é registrado em outro form, nessa página de escolher a data só tem esse campo. models.py from django.db import models class Estadio(models.Model): cidade = models.CharField('Cidade', max_length=40, default="oi") nomeEstadio = models.CharField('Nome do Estadio', max_length=50, default="oi") donoCampo = models.CharField('Dono do Campo', max_length=80, default="oi") enderecoCampo = models.CharField('Endereço do Campo', max_length=150, default="oi") comprimentoCampo = models.SmallIntegerField('Comprimento do Campo') larguraCampo = models.SmallIntegerField('Largura do Campo') precoHora = models.PositiveSmallIntegerField('Preço por Hora') def __str__(self): return self.cidade class PrecoFinal(models.Model): data = models.CharField("Insira a data no formato MM/DD/YYYY: ", max_length=10) def __str__(self): return self.data views.py def escolherEstadio(request, id): estadio = Estadio.objects.get(id=id) form = PrecoFinalForm(request.POST or None) if form.is_valid(): form.save() return redirect('listaEstadios') return render(request, 'precoFinal.html', {"form": form, "estadio": estadio}) def estadiosEscolhidos(request): nome = Estadio.objects.all() estadios = PrecoFinal.objects.all() return render(request, "estadiosAgendados.html", {"estadios": estadios, "nome": nome}) a template <!doctype html> {% load static %} <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta … -
How to set default language in multi language Django project
my settings : LANGUAGE_CODE = 'fa' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True # Languages LANGUAGES = ( ('fa', _('Persian')), ('en', _('English')), ('ar', _('Arabic')), ) LOCALE_PATHS = [ BASE_DIR / 'locale/', ] i want at the beginning when server get start default language for everyone be "fa" but it's still "en" how can i change that ? everything about multi language and translation works well -
Installing torch with python 3.10 (64 bit) on a Mac
Following the instructions provided on https://pytorch.org/get-started/locally/, i've tried running the command: pip3 install torch torchvision It fails and I end up getting: Collecting torch Using cached torch-0.1.2.post2.tar.gz (128 kB) Preparing metadata (setup.py) ... done Collecting torchvision Using cached torchvision-0.2.2.post3-py2.py3-none-any.whl (64 kB) Requirement already satisfied: pyyaml in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (from torch) (6.0) Requirement already satisfied: six in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (from torchvision) (1.16.0) Collecting pillow>=4.1.1 Using cached Pillow-8.4.0-cp310-cp310-macosx_10_10_universal2.whl (3.0 MB) Requirement already satisfied: numpy in /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (from torchvision) (1.21.3) WARNING: The candidate selected for download or install is a yanked version: 'torch' candidate (version 0.1.2.post2 at https://files.pythonhosted.org/packages/f8/02/880b468bd382dc79896eaecbeb8ce95e9c4b99a24902874a2cef0b562cea/torch-0.1.2.post2.tar.gz#sha256=a43e37f8f927c5b18f80cd163daaf6a1920edafcab5102e02e3e14bb97d9c874 (from https://pypi.org/simple/torch/)) Reason for being yanked: 0.1.2 is past it's support date and confuses users on unsupported platforms Building wheels for collected packages: torch Building wheel for torch (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.10/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/t7/fqh_tff16qx90b62sxgz7s800000gn/T/pip-install-3sjlcyjd/torch_676910a6bf6747c28f8a748f246308d6/setup.py'"'"'; __file__='"'"'/private/var/folders/t7/fqh_tff16qx90b62sxgz7s800000gn/T/pip-install-3sjlcyjd/torch_676910a6bf6747c28f8a748f246308d6/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/t7/fqh_tff16qx90b62sxgz7s800000gn/T/pip-wheel-fmaosysd cwd: /private/var/folders/t7/fqh_tff16qx90b62sxgz7s800000gn/T/pip-install-3sjlcyjd/torch_676910a6bf6747c28f8a748f246308d6/ Complete output (30 lines): running bdist_wheel running build running build_deps Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/t7/fqh_tff16qx90b62sxgz7s800000gn/T/pip-install-3sjlcyjd/torch_676910a6bf6747c28f8a748f246308d6/setup.py", line 225, in <module> setup(name="torch", version="0.1.2.post2", File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/setuptools/__init__.py", line … -
Django filtering timestamps using url parameters
I am making a backend for an investment APY in Django rest framework. I am updating database on daily timeframe, means value and timestamp of the APY is stored in the database once a day. I am able to view the APY using URL below http://127.0.0.1:8000/api/v1/apy/data?pair=1 I want to update the APY hourly and then filter the result based on timeframe like this For Instance, for hourly timeframe I wanna use http://127.0.0.1:8000/api/v1/apy/data?pair=1&interval=60 and Daily time frame I wanna use http://127.0.0.1:8000/api/v1/apy/data?pair=1&interval=1440 I tried objects.filter but its not helping for my case. file structure -- BaseApp -> Models - apy_model.py -> Views - apy_view.py -> Urls - apy_url.py -> Serializer - apy_serializer.py apy_models.py #-----apy_models.py------------- from django.db import models class priceApy(models.Model): value = models.DecimalField( max_digits=10, decimal_places=5, null=False, blank=False) time = models.CharField(max_length=10, null = False, blank=False) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self._id) apy_urls.py #------apy_urls.py---------- from django.urls import path from base.views import apy_views as views urlpatterns = [ path('data', views.getapy, name = 'apy'), ] apy_view.py #-------apy_view.py--------------- from django.shortcuts import render from rest_framework.response import Response from rest_framework.decorators import api_view from base.models.apy_models import * from base.serializers.apy_serializer import * @api_view(['GET']) def getapy(request): pair=request.query_params.get("pair") if pair != None and int(pair) >= 1: def switch_case(argument): switcher = { … -
Django REST-Framework serializer dataframe CSV file
I list in Django restframework a external DB settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', ... }, 'tec': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', ... }, } models.py from django.db import models class TmaskMda02(models.Model): id = models.BigAutoField(primary_key=True) uuid = models.TextField(blank=True, null=True) filename = models.TextField(blank=True, null=True) log = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) sha256 = models.TextField(blank=True, null=True) # Field renamed because it was a Python reserved word. import_field = models.TextField(db_column='import', blank=True, null=True) export = models.TextField(blank=True, null=True) params = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'mda00' views.py from django.shortcuts import render from rest_framework import viewsets from rest_framework import permissions from .serializers import HomeSerializer from .models import TmaskMda02 class HomeViewSet(viewsets.ModelViewSet): queryset = TmaskMda02.objects.using('tec').all() serializer_class = HomeSerializer permission_classes = [permissions.IsAuthenticated] serializers.py from rest_framework import serializers from .models import TmaskMda02 class HomeSerializer(serializers.ModelSerializer): class Meta: model = TmaskMda02 fields = ('id', 'uuid', 'filename', 'log', 'timestamp', 'sha256', 'import_field', 'export', 'params') All is fine If I would like to display a CSV file or data from the API how to do it? np. CSV Link np. Ext API Link Thank you for all your comments -
<class 'API.admin.User'>: (admin.E108)
**<class 'API.admin.User'>: (admin.E108) The value of 'list display[2]' refers to 'user type', which is not a callable, an attribute of 'User', or an attribute or method on 'API.UserManager'. ** -
Django wrong count after exclude
I am having trouble getting a correct count after excluding users on a queryset. I am using Django==2.2.24. Please consider below scenario: Model A: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, related_name="modelA_user", on_delete=models.CASCADE) Model B: user = models.ForeignKey(CustomUserModel, on_delete=models.CASCADE) CustomUserModel: has FK on User model When I count() on said querysets on these models I get correct results for the objects I filter for. Queryset on Model A: usersFromModelA = apps.get_model("models.ModelA").objects.filter( status=2 ).distinct().order_by().values_list("user_id", flat=True) print(usersFromModelA.count()) # returns correct result, total count = 37 Queryset on Model B: modelb_objects = apps.get_model("models.ModelB").objects.filter( boolField=False ) print(modelb_objects.count()) # returns correct result, total count = 2396 When I try to exclude users from modelA on modelB queryset I get a wrong result; I expect to get a total of 2396 - 37 = 2359 but I get 2386 instead. All records in both models have values, no nulls. modelb_objects = modelb_objects.exclude(user__user_id__in=usersFromModelA).distinct() # returns wrong result, total count = 2386 Any ideas how to fix this? -
django rest framework set_cookie is not working
I am creating a login api for my app, I want to set_cookie for the response is httponly = True, secure = True, samesite = 'strict', I did it but this is not working, does someone help me to solve this ? class LoginView(APIView): def post(self, request): username = request.data['username'] password = request.data['password'] try: user = User.objects.get(username = username, password = password) except: raise ValidationError('user not found') try: user_token = user.auth_token.key except: token = Token.objects.create(user = user) user_token = token.key res = Response() res.set_cookie(key = 'key', value = user_token, httponly = True, secure = True, samesite = 'strict') res.data = { 'key': user_token } return res -
how to make dynamic color change in table heading in django
Table heading color not working after 3 class name in CSS, I want to change color when if new data will be added in database after 3 heading how to make it dynamic color change in CSS. <style>.demo1{ background-color: #F4CCCC; } .demo2{ background-color: #D0E0E3; } .demo3{ background-color: #EAD1DC; } </style> {% for i in trades %} <th class="demo{{forloop.counter}}">Capicity</th> <th class="demo{{forloop.counter}}">Total</th> <th class="demo{{forloop.counter}}">Training completed</th> {% endfor %} -
how to properly show "similar products" using the carousel in the Django template?
I want to display similar products with the help of the carousel. But I can only display 4 products per "carousel item". If in the loop {% for item in related_products %} there are more than 4, it doesn't display correctly. I've made 'context' slices of 4 items and it even works, but I'm sure there's a better way. How can I solve this problem and carry the following products to the next "carousel item"? Also, can you please tell me how not to display a 'carousel item' if there are no products for it? The {% if related_products_1 is not null %} construct failed. my views: class ProductDetail(FormView): template_name = 'retail/single_product.html' context_object_name = 'product' form_class = CartAddProductRetailForm def get_queryset(self): return Product.objects.filter(category__slug=self.kwargs['slug']) def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['product'] = Product.objects.get(slug=self.kwargs['slug']) # slices: context['related_products_1'] = Product.objects.select_related('tag').all()[:4] context['related_products_2'] = Product.objects.select_related('tag').all()[4:8] context['related_products_3'] = Product.objects.select_related('tag').all()[9:12] return context Template: <div id="carouselFourColumn" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselFourColumn" data-slide-to="0" class="active"></li> <li data-target="#carouselFourColumn" data-slide-to="1"></li> <li data-target="#carouselFourColumn" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% if related_products_1 is not null %} <div class="carousel-item active"> <div class="row"> {% for item in related_products_1 %} <div class="col-xl-3 p-1" > <div class="col mb-5"> <div class="card h-100"> <!-- Product image--> <a href="{% … -
How to stop django-python3-ldap package from storing user passwords in the database?
I am developing a django web application where I am using django-python3-ldap package for LDAP authentication. I am successfully able to authenticate users using LDAP. Once a user is successfully authenticated, its profile gets created in the default django user model (By fetching firstname, lastname and email from Active Directory) However, it is also storing user's password in the user model(in encrypted format). I do not want this to happen. I simply wish to authneticate users using AD and fetch firstname, lastname and email of the user but not the password. Is it possible? If yes, kindly tell me how. Any help would be highly appreciated. -
I can't find out my mistake in displaying database data in django template
I am working on a Django project. I have to display database data in the Django template but I can't find out my mistake in my code that is not allowing me to display data on the HTML page. views.py def viewposts(request): posts = NewPost.objects.all() return render(request,"network/index.html",{ "posts" : posts, }) Here is my model: models.py class NewPost(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) post = models.TextField() timestamp = models.DateTimeField(auto_now_add = True) def __str__(self): return f"post : {post} || user: {user} || timestamp: {timestamp} " HTML template <div id="posts"> {% for posts in posts %} <ul> <li> <h4>{{ posts.user }} || {{ posts.timestamp }}</h4> <h3>{{ posts.post }}</h3> </li> </ul> {% empty %} <h6>No post availabel 😔</h6> {% endfor %} </div> urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("index/",views.NewPostMaker,name="post"), path("index/",views.viewposts,name="posts") ] I know I have done a silly mistake on any part of my code but I can hardly find it out. When I fill-up the form, data is stored in the database but I can't display them on the HTML page. -
Django: how to test for concurrency issues when using cron jobs
I have a Django application hosted on a remote server which runs some cron jobs at relatively short intervals. One of these cron jobs executes a command that fetches a queryset from the database, calls an external API and changes the models based on the response from the API. If I don't take care, the cron job will execute multiple times before the API responds, thus leading to concurrency issues and multiple instances of the same models being updated at the same time. I have different strategies to avoid this issue, but I would like to write tests that I can run locally, mocking the API call and ensuring, that two cron tasks don't both try to work on an object at the same time. How do I do that? My code looks something like this (illustrative purpose to show the problem): def task(): qs = MyModel.objects.filter(task_ran=False) for model in qs: resp = api_call(model.foo) model.bar = resp model.task_ran = True model.save() So, how can I write a test, that checks that if task() is called a second time before the first call has finished, then it won't update the model again and the API won't get called again? Below is …