Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get attribute from urls
Hi I'm new to django and i'm trying to make a website that provides series with seasons and episodes. I successfully created the CreateView for the Serie. Now i'm about to do the CreateView for the Season. It should look something like this. Seasons: [1] [2] [3] [add] If you click add it should show a modal with the form for the season. My code looks like this: models.py class Serie(models.Model): title = models.CharField(max_length=120) thumbnail = models.ImageField(upload_to=serie_dir_path) ... class Season(models.Model): order = models.IntegerField() serie = models.ForeignKey(Serie, on_delete=models.CASCADE) ... class Episode(models.Model): title = models.CharField(max_length=120) order = models.IntegerField() episode = models.FileField(upload_to=episode_dir_path) season = models.ForeignKey(Season, on_delete=models.CASCADE) urls.py urlpatterns = [ path('library', LibListView.as_view(), name='library'), path('series/<int:pk>/season/<int:order>', SeriesDetailView.as_view(), name='serie-detail'), ] views.py class SeasonCreateView(LoginRequiredMixin, CreateView): model = Season fields = ['order'] season_form.html {% for season in serie.season_set.all %} ... {% endfor %} With the code above it doesn't show me any season. So I guess the mistake is in the for loop or in the views.py but I don't know where. Can anyone help? -
How to get the values from html form into ajax
I am doing a project in django which is a car rental/sale web app, the search query works, but when i am trying to submit my form in ajax it seems like it never reaches into ajax. <div class="container"> <div class="card-header bg-info text-white"> <h4> <i class="fas fa-car"></i> Search Car </h4> </div> <form method="get" id="search-form"> <div class="input-field"> <label for="from">Number:</label> <input type="number" class="form-control" id="from-place" placeholder="Any" name="number" /> </div> <section> <label for="class">Car Type:</label> <select class="cs-select cs-skin-border input-half"> <option value="" disabled selected>Any</option> <option value="1">Sedan</option> <option value="2">Saloon</option> </select> </section> <section> <label for="class">Price:</label> <div class="wide"> <select class="cs-select cs-select-half cs-skin-border input-half" name="price"> <option value="" disabled selected>any</option> <option value="1000">1.000</option> <option value="2000">2.000</option> <option value="3000">3.000</option> </div> </section> <div class="col-xxs-12 col-xs-12 text-center"> <input type="hidden" name="search_filter" value="true"> <input type="submit" id="search-apa" value="Search"> </div> </form> </div> and this ajax code: $(document).ready(function() { $('#search-form').on('submit', function(e) { e.preventDefault(); var searchText = $('#search-form').val(); $.ajax({ url: '/cars/search_car/?search_filter=' + searchText, type: 'GET', success: function(resp) { var newHtml = resp.data.map(d => { return `<div class="cars"> <a href="/cars/${d.id}"> <h4>${d.type}</h4> <p>${d.price}</p> </a> </div>` }); $('.cars-index').html(newHtml.join('')); $('.search-form').val( ''); }, error: function(xhr, ststus, error) { console.log(error); } }) }); }); I am trying to get the values from the form into ajax, but when i click search it says undefined. I printed searchText and … -
How do i save user ratings in django database?
Its my first project in django. I am trying to save rating in django database but when i click on radio buttons the value doesn't store in database.I have tried solutions of stack overflow previously uploaded but none helped me in resolving my issue.I was firstly using RadioSelect in forms.py but still having the same problem. Please if any one can help. It's really urgent please help me in fixing this. Here is the code: Model.py class Product(models.Model): title = models.CharField(max_length=120) brand = models.CharField(max_length=120,default="None") model = models.CharField(max_length=120,default="None") slug = models.SlugField(blank=True, unique=True) category = models.CharField(max_length=120 , default="Phone") price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) class Rating(models.Model): product=models.ForeignKey(Product,default=None, on_delete=models.PROTECT) user=models.ForeignKey(User,default=None, on_delete=models.PROTECT) rating = models.CharField(max_length=120) Views.py def add_rating(request,id): product = get_object_or_404(Product, pk=id) pro = Product.objects.get(id=id) if request.method == "POST": form = RatingForm(request.POST) if form.is_valid(): product = form.cleaned_data['product'] user = form.cleaned_data['user'] rating = form.cleaned_data['rating'] product = request.POST.get('product', ''), user = request.POST.get('user', ''), rating = request.POST.get('rating', ''), obj = Rating(product=product, user=user, rating=rating) obj.save() context = {'obj': obj} return render(request, 'product/detail.html',context) else: form=RatingForm() return HttpResponse('Please rate the product') Forms.py from django import forms from .models import Rating class RatingForm(forms.ModelForm): class Meta: model = Rating fields = ('product', 'user','rating') template.py <form method="POST" action="{% url 'add_rating' product.id %}">{% csrf_token %} … -
Filter objects or (if 0 found) gell all objects in Django with one DB hit
Is there a way in Django to achieve the following in one DB hit (Debug Toolbar shows 2 queries)? q = SomeModel.objects.filter(name=name).order_by(some_field) if q.count() == 0: q = SomeModel.objects.all().order_by(some_field) I want to check if there are objects with a given name. If yes, then return them. If not, return all objects. All done in one query. I've checked Subquery, Q, conditional expressions but still don't see how to fit it into one query. -
Adding a request.user in a ManyToMany field
I am trying to add a request.user to a manytomany field to create an item. But I receive this error: TypeError at /api/v1/movies/ 'User' object is not iterable Models.py class Movie(models.Model): class Movie(models.Model): title = models.CharField(max_length=100) genre = models.CharField(max_length=100) year = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) creator = models.ManyToManyField('auth.User', related_name='movies') views.py # Create a new movie def post(self, request): serializer = MovieSerializer(data=request.data) if serializer.is_valid(): serializer.save(creator=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Dynamic column in tables
I have a model class Timetable(models.Model): day = models.CharField(max_length=9,choices=timetable_choices,blank=True) start = models.TimeField() end = models.TimeField() period = models.CharField(max_length=15) number_of_periods = models.IntegerField() and a createview for the same model class Timetableadd(CreateView): model = Timetable fields = ['day', 'start' ,'end','period','number_of_periods'] success_url = 'timetable-add' Respective view to display the table class Timetabletest(ListView): model = Timetable template_name = 'timetable.html' I am trying to create a table with columns= number of periods which is taken from the user . Things i need to fix: I need the user to input the number of periods only once ,but the problem is :- with the model and view I have provided user has to provide number of periods each time. I need to create a table with columns= number of periods which is taken from the user clearly number of columns will be changed based on the number of periods. I am not sure how to do this . I have tried the below code in my template to display the created table , and it was a failure . <table> <tr> {% for item.number_of_periods in object_list t%} <td>{{item}}</td> {% endfor %} </tr> <tr> <td>Monday</td> {% for item.number_of_periods in object_list t%} <td>{{period}}</td> {% endfor %} </tr> <tr> … -
Heroku is not able to find the react index.html (TemplateDoesNotExist)
I am not sure what I am doing wrong. I followed this tutorial https://alphacoder.xyz/deploy-react-django-app-on-heroku/ and cloned the git repo. The tutorial was about how to create a django, react app and push it to heroku I replaced the "build" => to templates and renamed the folder build to templates 'DIRS': [os.path.join(BASE_DIR, 'build') ], I created in every subfolder a build folder which contain the index.html. Below the code you find my folder structur and the heroku error message. Here is the link to the git repo: https://github.com/gwillig/testreact_heroku Any suggestion is much appreciated """ Django settings for reactdjango project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['research-click.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'sampleapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Select the fastest time for each athlete
I'm trying to generate a list of the best result of each athlete, ordered on time. Currently I'm just throwing out every duplicate result after getting all results and ordering on time. I have the following two models: class Athlete(models.Model): name = models.CharField(max_length=100) class Result(models.Model): athlete = ForeignKey(Athlete, on_delete=models.CASCADE) time = models.DurationField() Say the Result table looks like this: athlete time ------- ---- 1 15.00 1 14.00 2 16.00 2 18.00 2 13.00 3 12.00 How do I get the fastest time for each athlete and then sort the list on time? Like this: athlete time ------- ---- 3 12.00 2 13.00 1 14.00 -
Does a django server offer the developer local memory?
Does a Django server have any permanent local memory available to the developer? I want to use the server as a simple data relay. For example, I would post a small quantity of data from one source, store it in local memory, then get the data from another source: #From source #1: import requests packet = [6, 42] requests.post('https://www.example.com/postdata/', json=packet) #On server in views.py: import LOCAL_DATA_STORAGE # a made up thing that acts like what I want def postdata(request): LOCAL_DATA_STORAGE.mydata = request.body return HttpResponse(status=200) def getdata(request): return JsonResponse(LOCAL_DATA_STORAGE.mydata) #From source #2: import requests response = requests.get('https://www.example.com/getdata/') packet = response.body This seems like a trivial task to set up a database for, as I always want to overwrite the old data whenever I get new data and the data size is very small. I found the cache setup, but that seems to be for caching pages, not arbitrary data. Is there a way to put this kind of small data in some local memory that can be accessed between views? -
Problem with instalation python-ldap in django project
After installing dependencies for python-ldap i still have an error. I've installed dependencies with command (According to "I can't install python-ldap" post): sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev Still have an error: ... Installing collected packages: pyasn1, pyasn1-modules, python-ldap Running setup.py install for python-ldap ... error ERROR: Complete output from command /home/administrator/DjangoProjects/sofvenv/bin/python3 -u -c 'import setuptools, tokenize;file='"'"'/tmp/pip-install-8iq7rwmo/python-ldap/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-kzaa8l2y/install-record.txt --single-version-externally-managed --compile --install-headers /home/administrator/DjangoProjects/sofvenv/include/site/python3.6/python-ldap: ERROR: running install ... -
CSRF verification failed in Django project update, and RequestContext solution not working
I have a Django project in which trying to 'update' (clicking on the button) causes the following error: CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. I have viewed various questions and answers that suggest that adding RequestContext is the solution, but I have tried something to that effect tailored to my code, and still am unable to get it working. Original code views.py is below #USERS (register) view.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages #this allows us flash messages for testing from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm from .forms import UserUpdateForm from .forms import ProfileUpdateForm from django.contrib.auth.decorators import login_required def register(request): if request.method =='POST': #this UserRegisterForm is created in forms.py and inherits from UserCreationForm (the ready made form) form = UserRegisterForm(request.POST) #create a form that has the data that was in request.POST if form.is_valid(): #is the form valid (do you have a username like this already, passwords match? form.save() username = form.cleaned_data.get('username') messages.success(request,f'Account created for {username}, you can now login.') return redirect('login') else: form =UserRegisterForm() #if the form input is invalid, render the empty form again return render(request, 'users/register.html',{'form':form}) @login_required #this is a decorator … -
How to render a many to manyfield?
I'm making a todo with a friend and we are trying to render it in our template. This is my models.py class Todo(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") class Routine(models.Model): todo= models.ManyToManyField(Todo) text = models.CharField(max_length=150,) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.text My views.py class DashboardListView(LoginRequiredMixin,ListView): model = Links template_name = 'dashboard/home.html' context_object_name ='links_list' def get_queryset(self): return self.model.objects.filter(author=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['todo_list']= Todo.objects.filter(author=self.request.user).order_by('-pk')[:15] context['routine_list']= Routine.objects.filter(author=self.request.user).order_by('-pk')[:15] return context And in my template I am trying to render it like that : {% for routine in routine_list %} {{routine.text|capfirst}} <br/>{% for todo in routine.todo.all %}{{ text }}<br/>{% endfor %} {{routine.todo.text|capfirst}} {% endfor %} But only the "routine" is being render, any help ? -
How can I remove the 'total:' at the bottom of my ui-grid?
I have my ui-grid setup with the sum of each column showing at the bottom. The thing is I have many columns and so 'total' showing up for every column is a bit messy for my grid. I was hoping if anyone could help me get rid of it?? I would just like it to show just the number. I have attached a picture for reference. https://imgur.com/Gv5OYzq -
Stop function giving new results when page refreshes django
I have a function that takes inputted choices and gives random objects from the database that match the users choice: def someFunction(): if choice == 'Choice1' result = Choice1.objects.all.order_by('?')[0] elif choice == 'Choice2' result = Choice2.objects.all.order_by('?')[0] return result It is passed to the view like so: def ChoiceView(): context = { 'Choice': someFunction(), } return render(request, 'project/choice.html', context) The issue I'm having is that because the function gives random objects by design every time the page is refreshed a different result is given. I want to keep the function random, however once the function is ran, I don't want it to be ran again when the page is refreshed but rather keep the original function results to remain until the choice parameters change, or it is purposely refreshed with the intention of getting a new set of results, or a given time period has elapsed etc Any help is much appreciated. Thanks in advance! -
Display a custom Django View in the templates
I'm setting up a Django project with search functionalities using Django-Haystack and Elasticsearch and my goal is farely simple: Give a random percent matching score to my search results based on the order of an ordered list. I was recently suggested to use the following code to implement the matching scores and display them in the templates but I can't find a way to make them appear in the templates. The suggested custom defs in Views.py: def random_search_match_percentages(array): from random import random from math import floor index = 0 results = [] for element in array: # define a maximum and a minimum range maximum = 100 - index if index <= 100 else 0 minimum = maximum - 5 if maximum > 0 else 0 num = floor(random() * (maximum - minimum) + minimum + 0.5) element.match = '{}%'.format(num) # add the match param results.append(element) # decrease the maximum and minimum for the next iteration index += 5 return results def MatchingScore(request): some_data = Product.objects.all() # just an example of grabbing data... paginator = Paginator(some_data, per_page=20) page_obj = paginator.get_page(page) results = random_search_match_percentages(page_obj) return render(request, 'search_result.html', {'results': results}) But I already have this custom View for the object_name and Pagination … -
How to filter a one-to-one generic relation with Django?
I have a moderation model : class ItemModeration(models.Model): class Meta: indexes = [ models.Index(fields=['object_id', 'content_type']), ] unique_together = ('content_type', 'object_id') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') published = models.BooleanField(default=False) ... A descriptor to attach a moderation object on-the-fly : class ItemModerationDescriptor(object): def __init__(self, **default_kwargs): self.default_kwargs = default_kwargs def __get__(self, instance, owner): ctype = ContentType.objects.get_for_model(instance.__class__) try: moderation = ItemModeration.objects.get(content_type__pk=ctype.id, object_id=instance.pk) except ItemModeration.DoesNotExist: moderation = ItemModeration(item=instance,**self.default_kwargs) moderation.save() return moderation And a model I want to moderate : class Product(models.Model): user = models.ForeignKey( User, null=True, on_delete=models.SET_NULL) created = models.DateTimeField( auto_now_add=True, blank=True, null=True, ) modified = models.DateTimeField( auto_now=True, blank=True, null=True, ) name = models.CharField( max_length=PRODUCT_NAME_MAX_LENGTH, blank=True, null=True, ) moderation = ItemModerationDescriptor() Now I can see a product 'published' state easily : p=Product(name='my super product') p.save() print(p.moderation.published) -> False The generic relation is useful because I will be able to search the objects to moderate whatever the type is : it could be products, images, comments. to_moderate_qs = ItemModeration.objects.filter(published=False) Now, how can I get the list of published products ? I would like to do something like this published_products_qs = Product.objects.filter(moderation__published=True) But, of course, it won't work as moderation attribute is not a Django model field. How can I do … -
Django. How to completely hide the fields in the form?
Tell me, please, how to completely hide the fields in the form, now only the field is hidden, but the name of the field remains? Model: class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риелтор') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область') city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город') district = models.ForeignKey(District, on_delete=models.CASCADE, verbose_name='Район') title = models.CharField(max_length=200, verbose_name='Заголовок') landmark = models.CharField(blank=True, max_length=200, verbose_name='Ориентир') description = models.TextField(blank=True, verbose_name='Описание') series = models.ForeignKey(Series, on_delete=models.CASCADE, verbose_name='Серия') rooms = models.IntegerField(default=0, blank=True, verbose_name='Количество комнат') sqmt = models.IntegerField(default=0, blank=True, verbose_name='Площадь') price = models.IntegerField(default=0, blank=True, verbose_name='Цена') photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Основное фото') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 1') photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 2') photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 3') photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 4') photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 5') photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, verbose_name='Фото 6') is_published = models.BooleanField(default=True, verbose_name='Публично') list_date = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата публикации') def __str__(self): return self.title forms.py class ListingForm(forms.ModelForm): class Meta: model = Listing exclude = ('realtor',) When selecting a category, unnecessary fields are hidden, but the labels remain, and I cannot register a div that needs to be hidden completely, but what was hidden I looked at the page code in the browser: <div class="card-body"> <form method="POST" id="ListingForm" data-cities-url="{% url 'ajax_load_cities' %}" … -
How to use Marzipano 360 media viewer in Django project?
Sorry if I make any mistakes, this is my first ever question on stackoverflow. I've got a Marzipano sample with all the necessary files and folders. When I open index.html a 360 viewer runs in the browser and everything works fine. Now I want to get the same thing working inside of Django project. The directory structure for Marzipano sample looks like that (unfortunately I could not post the folder structure in a tree form, stackoverflow gives an error): img vendor tiles data.js index.html index.js styles.css The only folder I care is tiles, which has many folders with images. To get this working in Django I have to put those images in the right place in the static folder of Django project. I tried to figure out where exactly inside of JavaScript files the image paths are set, but unfortunately I have very poor knowledge of JavaScript. I assume I am doing something very wrong, because I googled the problem and could not find anyone trying to put any 360 viewer in to Django project. I would be grateful for any advise. -
How to create a model related to another to generate a list
I am trying to create a todolist where users can create a list of tasks like "morning routine" and import them directly into my todo app. Models.py Todo and TodoList class Todo(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") content = models.TextField(verbose_name="Description supplémentaire",null=True, blank=True) class TodoList(models.Model): list = models.ForeignKey(Todo, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") My todoApp is working but I cannot figure out how to link them and import the list from todo to TodoList Thanks guys -
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' return length
My view method accept values and call score methods, but my terminal output this error > return sum(item['quantity'] for item in self.cart.values()) TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' views.py def cart_update(request): cart = Cart(request) quantity = request.GET.get('quantity') product_slug = request.GET.get('product_slug') product = Product.objects.get(slug=product_slug) cart.add(product=product, quantity=quantity, update_quantity=True) return JsonResponse({ # here errors 'cart_length':cart.get_length(), 'cart_total':cart.get_total_price(), 'cart_price':cart.get_price(product=product, quantity=quantity) }) cart.py def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def get_price(self, product, quantity): return quantity * Decimal(product.price) def get_length(self): return sum(item['quantity'] for item in self.cart.values()) What I am doing wrong? -
How to pass Show_Drive selected value inside os.chdir(?-----------)
Dear all can you tell me? How to pass Show_Drive selected value inside os.chdir(?-----------) drives_a = [chr(x) + ':' for x in range(65, 90) if os.path.exists(chr(x) + ':')] -
Django - iterating the elements of a dictionary and saving them generates problems at the level of connections to the database?
I'm working with a survey app, so I need to save all the answers a user gives in the database. The way I'm doing it is this: for key, value in request.POST.items(): if key != 'csrfmiddlewaretoken': # I don't want to save the token info item = Item.objects.get(pk=key) # I get the question(item) I want to save if item == None: return render(request, "survey/error.html") Answer.objects.create(item= item, answer=value, user = request.user) Taking into account that django by default closes connections to the database (i.e. does not use persistent connections). My question is: In case the dictionary has for example the answer to 60 questions (so it will iterate 60 times), would it open and close the connections 60 times, or does it only do it once? Is there a better way to save POST information manually? (without using django forms, since for various reasons I currently need to do it manually) -
Save Results of a Function to be presented on 'Saved' page - Django
I have a function in a services.py file which basically gets random objects which match user preferences: def workoutSelect(request): today = datetime.datetime.today().weekday() current_user = request.user if today == 0: workout = User.objects.get(pk=current_user.id).profile.monday elif today == 1: workout = User.objects.get(pk=current_user.id).profile.tuesday elif today == 2: workout = User.objects.get(pk=current_user.id).profile.wednesday elif today == 3: workout = User.objects.get(pk=current_user.id).profile.thursday elif today == 4: workout = User.objects.get(pk=current_user.id).profile.friday elif today == 5: workout = User.objects.get(pk=current_user.id).profile.saturday elif today == 6: workout = User.objects.get(pk=current_user.id).profile.sunday if workout == 'ARMS': warmup = Workout.objects.filter(settype='Warm-up', muscle='Biceps').order_by('?')[0] ex_1 = Workout.objects.filter(settype='Working1', muscle='Biceps').order_by('?')[0] ex_2 = Workout.objects.filter(settype='Working2', muscle='Biceps').order_by('?')[0] ex_3 = Workout.objects.filter(settype='Working3', muscle='Biceps').order_by('?')[0] ex_4 = Workout.objects.filter(settype='Working4', muscle='Biceps').order_by('?')[0] workout = [warmup, ex_1, ex_2, ex_3, ex_4] elif workout == 'BACK': warmup = Workout.objects.filter(settype='Warm-up', muscle='Back').order_by('?')[0] ex_1 = Workout.objects.filter(settype='Working1', muscle='Back').order_by('?')[0] ex_2 = Workout.objects.filter(settype='Working2', muscle='Back').order_by('?')[0] ex_3 = Workout.objects.filter(settype='Working3', muscle='Back').order_by('?')[0] ex_4 = Workout.objects.filter(settype='Working4', muscle='Back').order_by('?')[0] workout = [warmup, ex_1, ex_2, ex_3, ex_4] elif workout == 'CRDO': warmup = Workout.objects.filter(settype='Warm-up', muscle='Cardio').order_by('?')[0] ex_1 = Workout.objects.filter(settype='Working1', muscle='Cardio').order_by('?')[0] ex_2 = Workout.objects.filter(settype='Working2', muscle='Cardio').order_by('?')[0] ex_3 = Workout.objects.filter(settype='Working3', muscle='Cardio').order_by('?')[0] ex_4 = Workout.objects.filter(settype='Working4', muscle='Cardio').order_by('?')[0] workout = [warmup, ex_1, ex_2, ex_3, ex_4] elif workout == 'CHST': warmup = Workout.objects.filter(settype='Warm-up', muscle='Chest').order_by('?')[0] ex_1 = Workout.objects.filter(settype='Working1', muscle='Chest').order_by('?')[0] ex_2 = Workout.objects.filter(settype='Working2', muscle='Chest').order_by('?')[0] ex_3 = Workout.objects.filter(settype='Working3', muscle='Chest').order_by('?')[0] ex_4 = Workout.objects.filter(settype='Working4', muscle='Chest').order_by('?')[0] workout = [warmup, ex_1, ex_2, ex_3, ex_4] elif workout … -
How to work with getting data from google books api?
I'm trying to create simple view with 1 form field for book searching through Google Books Api but idk what's wrong. All what I'm trying is make simple search feature, when user enter any string like "hobbit" and click search button he should retrieve the data from https://www.googleapis.com/books/v1/volumes?q=hobbit but all time I got a problem like MultiValueDictKeyError or not all arguments converted during string formatting Does anyone know how to deal with Django + Google api? views.py # view for importing books from google api def api(request): book = {} if 'book' in request.GET: book = request.GET['book'] url = 'https://www.googleapis.com/books/v1/volumes?q=' % book response = requests.get(url) user = response.json() return render(request, 'books/api.html', {'book': book}) api.html {% block content %} <h2>Google API</h2> <form method="get"> <input type="text" name="book"> <button type="submit">search on google books api</button> </form> {% if book %} <p> <strong>{{ book.title }} </p> {% endif %} {% endblock %} -
Django 1.11 filter by time delta between latest and next to latest
Let's imagine we have an Event model: class Event(models.Model): actor = models.ForeignKey(Actor, null=False, blank=False, on_delete=models.PROTECT) happened_datetime = models.DateTimeField(_('When did the event took place?'), blank=False, null=False) and an actor model: class Actor(models.Model): name = models.CharField(_('Name'), max_length=100, blank=False, null=False, default='') After a while, we have a potentially long list of events. How should we go about to get the actors whose latest two events are separated by less or more than a specified timedelta, for example: Give me all actors whose latest and next to latest events are not separated by more than 10 days or Give me all actors whose latest and next to latest events are not separated by less than 5 hours Is a Subquery the way to go? An ExpressionWrapper with F expressions? Note: the above queries means we should also filter by Actors who have caused at least two events, with something similar to this: actors_with_at_least_two = Actor.objects.annotate( nb_events=Subquery( Event.objects.filter( actor=OuterRef('pk') ).values( 'actor__pk' ).order_by().annotate( cnt=Count('*') ).values('cnt')[:1], output_field=models.IntegerField() ) ).filter( nb_events__gte=2 ) The above works well, but filtering with "introspection" on same table (timedelta, etc) I struggle with. Any ideas/clue would be kindly appreciated! :-)