Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Media' object has no attribute 'render_q'
screenshothow to fix "'Media' object has no attribute 'render_q'" appears when editing the model in the admin panel -
Update only that property not all model, django
@property def policy_escape(self): if self.date - datetime.date.today: self.status = 2 self.save() def save(self, *args, **kwargs): self.counter = counter + 1 I have this logic for policies. For every policy created I want to increase a property nnumber(this is not exact my case). I want when policy date is today date to change the status of that policy. But when I change it, the policy counter is increasing. Can someone help me to update only status without updating other properties? Thanks in advance -
Django/OpenResty validate JWT
at my Django REST application, the user receives a JWT after providing his login credentials to the API. Now I have second service, the user can download files from. In front of this second service, there should be an OpenResty proxy to validate the JWT my Django application generates after login for the user. How can I make OpenResty validate the JWT to allow a user access to the second service? My intention here is to implement kinda SSO using the JWT my Django application generates Thanks in advance -
How to filter on a foreign key that is grouped?
Model: from django.db import models class Person(models.Model): name = models.CharField(max_length=100) class Result(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) outcome = models.IntegerField() time = models.DateTimeField() Sql: select * from person as p inner join ( select person_id, max(time) as max_time, outcome from result group by person_id ) r on p.id = r.person_id where r.result in (2, 3) I'm wanting to get the all person records where the last result outcome was either a 2 or 3. I added the raw sql above to further explain. I looked at using a subquery to filter person records that have a matching result id sub_query = Result.objects.values("person_id").annotate(max_time=Max("time")) however using values strips out the other fields. Ideally I'd be able to do this in one person queryset but I don't think that is the case. -
Django: composite primary key doesn't work
The Django seems to completely ignore my use of unique_together constraint given to it and instead it treates one field as a primary key, but not the composition of two fields. In my postgres db everything works fine, but not in Django. I tried this and that, even overriding ModelForm's save method to create object manually, nothing helps. Seems like I have to create some fake id field in this table to make Django think that this is the primary key, which is not convinient. Advices needed. -
How to display data in a table from a database for a search for a Foreign Key in the same page using Ajax in a Django project?
I am quite new to programming and I have been trying to resolve this issue from the past two days and couldn't wrap my head around on how to implement it to my requirement. (It would be helpful if you could explain what you are doing with the commands in your solution.) I have a PostgreSQL database that I have imported to Django models. My models from the database. Students objects from Student table have total marks assigned to them in the ExamMarks table through two Foreign Keys( 1. Student_ID and the other Classroom_ID I want to display the rank list of a classroom in descending order of the top 5 students with respect to their total marks in the 'total' column of the ExamMarks. I want to display it on the same page as the search page of my website. I had used to redirect it to another page to display the results but I want it to display on the same page using Ajax. The below pictures show how I did it previously using another page. Image shows my search page My HTML search page file My HTML file. Here I am displaying only the top 5 Students … -
Why is my side navigation bar overlapping the text on the web pages
So I am using django to create a website but there must be a problem in my CSS and or HTML code, when I run the server the text on the pages is being covered by the sidenav bar I have. I previously had a width set for the sidenav but removed it but that didn't work either, here is the code: <html> <head> <style type="text/css"> .sidenav { height: 100%; position: fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: hidden; padding-top: 20px; } .sidenav a { padding: 6px 8px 6px 16px; text-decoration: none; font-size: 25px; color: #818181; display: block; } .sidenav a:hover{ color: #f1f1f1; } .main{ margin-left: 160px; padding: 0px 10px; } </style> <title>{% block title %} My Website {% endblock %}</title> </head> <body> <div class="sidenav"> <a href="/home">Home</a> <a href="/create">Create</a> <a href="/6">View</a> </div> <div id="content", name="content"></div> {% block content %} {% endblock %} </body> </html> -
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'. **