Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loading data faster from GraphQL endpoint for React
I have an e-commerce Django App that uses Graphene GraphQL to store some data at the backend. I use React at the frontend to load the data from the GraphQL endpoint. I have a requirement where I need to load all of the products (estimated to be about 100-170 products) in one go. This load is taking a long time at the moment (~7-10 seconds). Is there a way I can use caching to help the data load faster. I have read about this: https://docs.graphene-python.org/en/latest/execution/dataloader/ which seems like an option. Is there a better of doing this? Any help is appreciated -
Add a permission to Django admin panel without a model
I would like to create a custom user permission that is not related to a model that I can assign to users through the django admin panel. I have already tried something like class CustomPermissions(Permission): class Meta: proxy = True verbose_name = "MIDB Has write permission" permissions = ( ('can_write_to_midb', 'Can write to midb') ) admin.site.register(CustomPermissions) And variations on that. Is it possible to have just a user permission without a model that can be assigned through the admin panel? Thank you -
How do I match the model to the parent model, in html?
I have 2 pages, on the first page I create questions in the form, on the second page I want to display these questions and match the questions created on the first page, but I have to manually select the query result (I have 2 questions created). How do I do it dynamically? The question to fit its corresponding Answer model this is my code -> models.py from django.db import models from django.core.exceptions import ValidationError class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100, null=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question,Answer import random from django.forms import modelformset_factory def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): questions=Question.objects.all() form=AnswerForm() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): print("Test validation only") print(request.POST) return render(request, "question/ans.html", {"form":form, "questions":questions}) ans.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> <form … -
clearing browser cache in django
I have a website that I developed using Django. Sometimes I have to change some small css styles or add some new things to the website but every time I need to clear the browser cache by pressing ctrl+f5. obviously, I cant tell everyone else to clear their browser cache every time they want to use the website. what should I do to make the app forcingly clear the cache for everyone? thanks for your responses -
Passing variables from a from to a view in Django
Working on a site where Managers can view database entries made by Reps. I want Managers to be able to specify search dates for the reports I'm building, but for the life of me I can't figure out how to pass the values from a simple Django form with two DateFields to my view that would then use those variable to query the database. models.py class ReportRequestForm(forms.Form): start_date = forms.DateField() end_date = forms.DateField() views.py def weekly_rep_report(request, start_date=datetime.today(), end_date=datetime.today()): weekly_visit_objects = Store.objects.filter(visit_filed__range=(start_date, end_date)) My view/html works fine with the default values provided in the arguments, but I'm lost as to how to have the ReportRequestForm submit data to the weekly_report_view as most of my forms are adding/editing items in the database. -
name 'HTML' is not defined
I am working with the Django project and trying to render a pdf with WeasyPrint. my views.py: def WeasyPDF(request): paragraphs = ['first paragraph', 'second paragraph', 'third paragraph'] html_string = render_to_string('app/pdf_report.html', {'paragraphs': paragraphs}) html = HTML(string=html_string) html.write_pdf( target='/tmp/mypdf.pdf', stylesheets=[ # Change this to suit your css path settings.BASE_DIR + 'css/bootstrap.min.css', settings.BASE_DIR + 'css/main.css', ], ); fs = FileSystemStorage('/tmp') with fs.open('mypdf.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return response return response But it says the following error: name 'HTML' is not defined I was following this tutorial: link. How can I fix it? -
How to use updateview without createview in django python?
I'm creating shop profile by create function so i'm not using createview for that but now I wanted to update that default shop profile with updateview , right now i'm getting following here : Exception Value: ShopProfileDetailView is missing a QuerySet. Define ShopProfileDetailView.model, ShopProfileDetailView.queryset, or override ShopProfileDetailView.get_queryset(). models.py class ShopProfile(models.Model): shop_owner = models.OneToOneField(User, related_name='shop_profile', on_delete=models.CASCADE) shop_address = models.CharField(_("shop address"), max_length=255) title = models.CharField(("shop"), max_length=50) slug = models.SlugField(blank =True,unique = True) create_date = models.DateTimeField(("create date"), default=timezone.now) shop_bg =models.ImageField(_("Shop background image"), upload_to="shop_back_grounds",default="shop_default.jpeg" ,height_field=None, width_field=None, max_length=None) customers = models.ManyToManyField(User, related_name="customers", verbose_name=_("coutomers")) customers_favorite = models.ManyToManyField(User,related_name="customers_favorite", verbose_name=_("customers favorite")) views.py class ShopProfileDetailView(DetailView): Shop = ShopProfile template_name='shops/shop_profile.html' class ShopProfileUpdateView(UpdateView): model = ShopProfile form_class = ShopProfileForm template_name = 'shops/shop_profile_update.html' def get_object(self, *args, **kwargs): return self.request.user.shop_profile def get_form_kwargs(self, *args, **kwargs): form_kwargs = super().get_form_kwargs(*args, **kwargs) form_kwargs['request'] = self.request return form_kwargs def get_context_data(self, *args, **kwargs): context = super(ShopProfileUpdateView, self).get_context_data(*args, **kwargs) update_form = ShopProfileForm(instance = self.request.user.shop_profile) context['form']=update_form return context def form_valid(self, form): if self.request == 'POST': form.save() return super().form_valid(form) urls.py app_name = 'shops' urlpatterns = [ path('profile/<str:slug>/',views.ShopProfileDetailView.as_view(),name='shop_profile'), path('profile/update/<str:slug>/',views.ShopProfileUpdateView.as_view(),name='shop_profile_update') ] If more code if require then tell me in a comment section. traceback here you will get complete traceback.. -
How to reload page while keeping FormGroup content alive
I have got a filter function in a sidenav in my application which filters the list of profiles. However when I submit the filter function in the HTML I call this onFilterButtonSubmit function (see below) which should give my profile-list.component.ts the parameters while also reloading the page. onFilterButtonSubmit(minA, maxA, gen): void { this.profileService.minAge = minA; this.profileService.maxAge = maxA; this.profileService.gender = gen; this.router.navigate(['/home']); } The site is not being reloaded though. Only when I am on another page (f.e. profile-page), parsing the filter criteria and clicking on Filter, it correctly reroutes me to /home and displays the results I filtered for. I also tried using window.location.reload(); which reloads the page successfully but does not save the FormField content. I am kinda lost here, any help is appreciated. Not sure which other code parts are relevant but let me know and I will add it to the question. I am using Angular and Django for the backend. app.component.ts export class AppComponent implements OnInit { title = 'frontend'; isLoggedIn = false; filteredFormControl: any = new FormControl(''); filteredProfilesFormGroup: FormGroup; profiles: Profile[]; public isFiltered: boolean; constructor(public userService: UserService, public profileService: ProfileService, private router: Router) { } ngOnInit(): void { this.filteredProfilesFormGroup = new FormGroup({ minAge: new … -
Change the Django Rest Framework Default Router api root?
In development, my defaultrouter works along the base url/domain of http://127.0.0.1:8000/, however the api is going to be hosted on http://website.com/test/location/ How do i change the default default router location so apiview,inner links, and the api work at http://website.com/test/location/ as the api root? -
Is there a way to reference variable name as a string in that variable's declaration in Python?
For my Django application, I have a dictionary of field names (keys) mapped to help texts (values) (which I read in from a csv file). In models.py, I want to retrieve the appropriate help text for each field name. If I have a sample dictionary like the following, with an entry for each field: test_dict = { 'host_name': 'The name of a host', ... } And my models.py looks like this: class Host_main(models.Model): host_name = models.CharField(max_length=20, unique=True, help_text=test_dict['host_name']) def __str__(self): return self.host_name Is there a way to call the variable name (host_name) dynamically in each help_text definition? I do have the option to do something like the following: from varname import nameof host_name = models.CharField(max_length=20, unique=True, help_text=test_dict[nameof(host_name)]) But if possible, I'd like to reference the current variable name with something consistent to avoid typing out the field name a second time, like help_text=test_dict[nameof(**this**)] in pseudocode. Thanks! -
Django AssertionError at /search/
I have an issue when I try to search for a second time. I will get the results from the first search, however, when I want to search for a different field I'm getting AssertionError. I'm not sure how can I fix this error. Any help is appreciated. def search(request): queryset_list = Oglas.objects.order_by('-list_date')[:5] # keywords if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains = keywords) # Area if 'area' in request.GET: area = request.GET['area'] if area: queryset_list = queryset_list.filter(area__iexact = area) # rooms if 'bedrooms' in request.GET: bedrooms = request.GET['bedrooms'] if bedrooms: queryset_list = queryset_list.filter(bedrooms__lte=bedrooms) -
Django annotated queryset with latest values for some fields
I have a model which store some marketing performances: class DailyPerformance(models.Model): class Meta: unique_together = ('route_hash_value', 'datetime_tz') ordering = ('-datetime_tz',) route_hash_value = models.CharField(max_length=255, db_index=True, editable=False) datetime_tz = models.DateTimeField(db_index=True, editable=False) network = models.ForeignKey('administration.Network', on_delete=models.PROTECT, null=True) account = models.ForeignKey('administration.Account', on_delete=models.SET_NULL, null=True) # Properties budget = models.FloatField(null=True, db_index=True) bid = models.FloatField(null=True, db_index=True) status = models.CharField(max_length=255, null=True, db_index=True) # METRICS cost_amount = models.FloatField(null=True, db_index=True) impressions = models.IntegerField(null=True, db_index=True) clicks_in = models.IntegerField(null=True, db_index=True) clicks_out = models.IntegerField(null=True, db_index=True) revenue_amount_net = models.FloatField(null=True, db_index=True) _profit = models.FloatField(null=True, db_index=True) _roi = models.FloatField(null=True, db_index=True) _ctr = models.FloatField(null=True, db_index=True) And I need to generate a queryset for the drf ModelViewset which aggregate numeric metrics and get the last values for the fields: bid, budget and status. Something like this: class DailyPerformanceHViewSet(viewsets.ReadOnlyModelViewSet): def get_queryset(self): queryset = DailyPerformance.objects.values( 'route_hash_value', 'datetime_tz', 'network', 'account', ).annotate( cost_amount=Round(Sum('cost_amount'), 3), revenue_amount_net=Round(Sum('revenue_amount_net'), 3), impressions=Sum('cost_impressions', output_field=FloatField()), clicks_in=Sum('cost_clicks_in', output_field=FloatField()), clicks_out=Sum('cost_clicks_out', output_field=FloatField()), _profit=Round(Sum('_profit'), 3), _roi=Round(F('_profit') / F('cost_amount'), 3), _ctr=Round(F('clicks_out') / F('clicks_in'), 3), ### budget=..., # <== LATEST BUDGET ORDERED BY -datetime_tz bid=..., # <== LATEST BID ORDERED BY -datetime_tz status=..., # <== LATEST STATUS ORDERED BY -datetime_tz ) return queryset but I really don't know how to do that -
gunicorn.service: Failed to determine user credentials: No such process
I keep getting an error when trying to set gunicorn with my django project ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2021-02-04 17:45:34 +01; 25min ago TriggeredBy: ● gunicorn.socket Main PID: 754981 (code=exited, status=217/USER) Feb 04 17:45:34 vps141106 systemd[1]: Started gunicorn daemon. Feb 04 17:45:34 vps141106 systemd[754981]: gunicorn.service: Failed to determine user credentials: No such process Feb 04 17:45:34 vps141106 systemd[754981]: gunicorn.service: Failed at step USER spawning /home/root/venv/bin/gunicorn: No such process Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Start request repeated too quickly. Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Feb 04 17:45:34 vps141106 systemd[1]: Failed to start gunicorn daemon. This is my service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/root/test ExecStart=/home/root/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ test.wsgi:application [Install] WantedBy=multi-user.target Im getting those errors gunicorn.service: Failed to determine user credentials: No such process gunicorn.service: Failed at step USER spawning /home/root/venv/bin/gunicorn: No such process Now Im pretty sure I have something in /home/root/venv/bin/gunicorn I just did a nano /home/root/venv/bin/gunicorn and … -
Django import from csv(update_or_create)
my program loads data from csv (customoer, item, total), here is my data model: from django.db import models class Member(models.Model): customer = models.CharField(max_length=50) item = models.JSONField(max_length=50) total = models.IntegerField() def __str__(self): return self.customer My view: def upload(request): template = 'upload.html' promt = { 'member': 'Member of CSV should be customer, item, total' } if request.method == 'GET': return render(request, template, promt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=','): _, created = Member.objects.update_or_create( customer=column[0], item=column[1], total=column[2] ) context = {} return render(request, template, context) In general, the download works, but instead of updating the user data, a new object is created with the same customer, how can I make it so that a new customer is not created, but only the total and item are updated in it? Example CSV data: customer,item,total bellwether,Cavorit,6126 resplendent,Saphire,8502 bellwether,Ruby,342 Instead of not creating two or more objects with the bellwether customer, there was only one object with customer bellwether an item ("Kavorit", "Ruby"), total (6468). Thank you for your time -
Django "Class 'User' has no 'objects' Member" pylint(no-member) [30, 16]
I'm new to Django, and I got some issue with views.py. I'm not sure why but there is error at User model. I tried to install pylint using pip install pylint-django and wrote {"python.linting.pylintArgs": [ "--load-plugins=pylint_django" ],} in my vsCode setting. But it doesn't work. Can anyone help me to solve this issue? This is my code for models.py and views.py models.py: class User(models.Model): username = models.CharField(max_length=100) def __str__(self): return self.username views.py: from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.shortcuts import render from stream_chat import StreamChat from .models import User # this decorator marks a view as being exempt from the protection ensured by the middleware @csrf_exempt def init(request): if not request.body: return JsonResponse(status=200, data={'message': 'No request body'}) body = json.loads(bytes(request.body).decode('utf-8')) if 'username' not in body: return JsonResponse(status=400, data={'message': 'Username is required to join the channel'}) username = body['username'] client = StreamChat(api_key=settings.STREAM_API_KEY, api_secret=settings.STREAM_API_SECRET) channel = client.channel('messaging', 'General') try: user = User.objects.get(username=username) token = bytes(client.create_token( user_id=user.username)).decode('utf-8') return JsonResponse(status=200, data={"username": user.username, "token": token, "apikey": settings.STREAM_API_KEY}) except User.DoesNotExist: user = User(username=username) user.save() token = bytes(client.create_token( user_id=username)).decode('utf-8') client.update_users({"id": username, "role": "admin"}) channel.add_members([username]) return JsonResponse(status=200, data={"username": user.username, "token": token, "apiKey": settings.STREAM_API_KEY}) Thank you -
How to work with Ajax in Django Admin Panel?
I have a ForeignKey relation between project and projectfloorplan, and my project model has multiple projectfloorplan. Now I have created a new section for Property and the property have ForeinKey relation with Project, Now if I select any project from the dropdown then the project floorplan should be automatic display of selected project in another dropdown, and I am using ForeignKey relation with projectfloorplan in Property model, but it's displaying all projects floorplan list in the dropdown, Please let me know how I can display particular projectfloorplan in Dropdown if I select any Project. here is my models.py file for the Property model... class Property(models.Model): project=models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_listing') floorplan=models.ForeignKey(ProjectFloorPlan, on_delete=models.CASCADE, related_name='project_floorplan') -
Access a pdf file from views.py which is created by Js in a Django project
I am trying to render with HTML to pdf in my Django project. I am using html2pdf package form js and render my html into pdf by following link: youtubelink. my template: <div class="container-fluid py-5 bg-light"> <div class="col-xl-10 bg-white" id="pdf_portion"> <p>Lots of staff is in this div. I just skip those unnecessary things in this question.</p> </div> </div> <button class="btn btn-primary" id="download"> download pdf</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.js"></script> <script type="text/javascript"> window.onload = function () { document.getElementById("download") .addEventListener("click", () => { const invoice = this.document.getElementById("pdf_portion"); console.log(invoice); console.log(window); var opt = { margin: 0.8, filename: 'myfile.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 4 }, jsPDF: { unit: 'in', format: 'A4', orientation: 'portrait' } }; html2pdf().from(invoice).set(opt).save(); }) } </script> Here the 'download' button gives us the option to download the pdf. I need to send the pdf in my views.py in any method, thus I will able to save it in my database's filefield. Please suggest How can I able to access that pdf file in my views.py. -
Page not found, dynamic URLs | Django
I'm having some trouble on performing a query in Django 3.1.4. The main problem is that the field that I use for my dynamic URLs can sometimes be a string with slashes: 'ABC/1/2/3D' This last one I'm having trouble with due to the slashes Rather than creating a slug field in the model and just replacing those slashes with some value (an _ per say) and using that parameter, I'd like to pass the parameter with the _ (without existing in my model) in the URL and then, replace all the _ with / to perform the query. views.py class DetailViewTest(LoginRequiredMixin, PermissionRequiredMixin, DetailView): slug_field = "some_stuff" slug_url_kwarg = "some_stuff" model = Stuff template_name = 'things/stuff.html' permission_required = 'stuff.view_stuff' def get_context_data(self, *args, **kwargs): context = super(DetailViewTest, self).get_context_data(**kwargs) if self.kwargs['some_stuff'].find('_') == -1: stuff = get_object_or_404(Stuff, some_stuff=self.kwargs['some_stuff']) # This is were I'm having some trouble else: temp_stuff = self.kwargs['some_stuff'].replace('_', '/') stuff = get_object_or_404(Stuff, some_stuff=temp_stuff) thing = stuff # Some other code goes here... context['...'] = ... return context urls.py urlpatterns = [ path('<str:some_stuff>/test/', DetailViewTest.as_view(), name='stuff_test'), ] As you can see, 'some_stuff' is the parameter I use, I works fine with values that don't have slashes However, when I pass 'TEST_12' for example, it … -
Am using drf-spectacular for my Django rest api documentation am getting below error when i am trying to over SPECTACULAR_SETTINGS in setting.py
Settings are configurable in settings.py in the scope SPECTACULAR_SETTINGS. You can override any setting, otherwise the defaults below are used. for ref: https://drf-spectacular.readthedocs.io/en/latest/settings.html [ -
How to request data as json response in Django?
How can i make request as a jsonResponse with template rendering also? The code below is working fine but i want to convert data as json data and i want to get data with ajax request jquery in template. I would be grateful for any help. VIEWS.py def Prompter(request, pk): obj = get_object_or_404(SetRundown, pk=pk) articles = obj.articles.order_by('position') return render(request, 'prompter.html', {'articles': articles}) -
An object is returning true even if it is not there
So i'm trying to see if the user has something in their cart, if they don't and they click on chekout then it should say that their cart is empty but it just makes an order object. makeorder and createorder function handles creating orders. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist import random # Create your views here. removederror = '' def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in oof: fianlprice += item.book.price def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html', {'error':'You are already logged in'}) elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signinuser.html', {'form':AuthenticationForm()}) … -
EmptyPage at /HomeFeed/ That page contains no results
This is a very weird Django Pagination problem: My django project is basically a blog website where people can make posts. So here I'm trying to query blog posts that belong to a user and page them. Basically, if the logged in user hasn't made any posts or that he has made enough posts to go beyond one page, everything works and this error does not shot. This error only shows when the logged in user has less than the number of posts a page should have. Why is this so? In case you are wondering why I am using page2 in my template instead of page, its because I have another pagination on the same page, so it's used to differentiate them... Error points to this line: blog_post = own_account_post.page(page) and also says that During handling of the above exception (int() argument must be a string, a bytes-like object or a number, not 'NoneType'), another exception occurred: in my browser. views.py def home_feed_view(request, *args, **kwargs): context = {} if request.user.is_authenticated: if BlogPost.objects.filter(author=request.user.id).exists(): blog_post = BlogPost.objects.filter(author=request.user.id).order_by('date_updated') page = request.GET.get('page2') own_account_post = Paginator(blog_post, 3) try: blog_post = own_account_post.page(page) except PageNotAnInteger: blog_post = own_account_post.page(3) except EmptyPage: blog_post = own_account_post.page(blog_post_paginator.num_pages) context['blog_post'] = blog_post … -
Django async view giving the same result as sync view
I am learining async views and just at the beginning i encountered a problem. Async view should run two functions at the same time but they go one after another just like in the regular view. What am I doing wrong? # helper funcs def get_movies(): print('prepare to get the movies...') time.sleep(2) qs = Movie.objects.all() print(qs) print('got all the movies.') def get_stories(): print('prepare to get the stories...') time.sleep(5) qs = Story.objects.all() print(qs) print('got all the stories.') @sync_to_async def get_movies_async(): print('prepare to get the movies...') time.sleep(2) qs = Movie.objects.all() print(qs) print('got all the movies.') @sync_to_async def get_stories_async(): print('prepare to get the stories...') time.sleep(5) qs = Story.objects.all() print(qs) print('got all the stories.') def main_view(request): start_time = time.time() get_movies() get_stories() total = (time.time() - start_time) print('Total: ', total) return HttpResponse('sync') async def main_view_async(request): start_time = time.time() # task1 = asyncio.ensure_future((get_movies_async())) # task2 = asyncio.ensure_future((get_stories_async())) # await asyncio.wait([task1, task2]) await asyncio.gather(get_movies_async(), get_stories_async()) total = (time.time() - start_time) print('Total: ', total) return HttpResponse('async') -
Error passing field to views, How do I correctly pass the model field to the view?
I am trying to pass a model field to the view to calculate the sum of time, but I get an error: Cannot resolve keyword 'hours_worked' into field. Choices are: car, car_id, date, deal_gts, deal_me, driver, driver_id, finish_work, gain, id, start_work models.py class Trip(models.Model): date = models.DateField(auto_now=False, verbose_name='Дата') car = models.ForeignKey(Cars, on_delete=models.CASCADE, verbose_name='Автомобиль') driver = models.ForeignKey(Driver, on_delete=models.CASCADE, verbose_name='Водитель') start_work = models.TimeField(verbose_name='Начало работы') finish_work = models.TimeField(verbose_name='Окончание работы') hours_worked = models.CharField(max_length=20, blank=True, verbose_name='Отработано часов') deal_me = models.IntegerField(verbose_name='Сделки МЭ', blank=True, default=0) deal_gts = models.IntegerField(verbose_name='Сделки ГТС', blank=True, default=0) gain = models.IntegerField(verbose_name='Выручка') class Meta: verbose_name = 'Доставка' verbose_name_plural = 'Достваки' def hours_worked(self): fw = self.finish_work sw = self.start_work hw = datetime.combine(date.today(), fw) - datetime.combine(date.today(), sw) hours_worked = str(hw).rsplit(':', 1)[0] return hours_worked wiews.py from django.shortcuts import render, redirect from .forms import TripForm from .models import Trip def home_view(request): trip = Trip.objects.all() # сумма чвасов sum_hour = 0 me = Trip.objects.values_list('hours_worked') # print(me) for el in me: for i in el: sum_hour = int(sum_hour) + int(i) context = { 'sum_hour': sum_hour } return render(request, 'driver_productivity/home.html', context) Tell me if I'm thinking in the right direction, or is it better to do the calculation not in the model? -
How to select from a subquery in Django's ORM?
I want to select all rows for which bet_index is not NULL: BetHistory.objects.values('account_id').annotate( bet_index=models.Case(models.When( models.Q(event_id=1, market_id=2) & (models.Q(account_id=3) | models.Q(account_id=4)), then=0), default=None, output_field=models.IntegerField()) ).exclude(bet_index=None) that yields the following SQL query SELECT "bet_history"."account_id", CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end AS "bet_index" FROM "bet_history" WHERE NOT ( CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end IS NULL ) but there the case is repeated, I would like to have the following query: SELECT * FROM (SELECT "bet_history"."account_id", CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end AS "bet_index" FROM "bet_history") AS "subquery" WHERE "subquery"."bet_index" IS NOT NULL; so I need a select from subquery, how to do it in Django? Thanks.