Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Python Error when launching pytest --cov
i'm new to django/python and i'm trying to learn faster as i can. I am trying to use coverage by using pytest-cov. When i launch the command 'pytest --cov' i get this error : ImportError while loading conftest '/home/ktech/Documenti/Project/jnportal/tests/conftest.py'. tests/conftest.py:9: in from django.contrib.contenttypes.models import ContentType ../../../.venviroments/jnportal/lib/python3.6/site-packages/django/contrib/contenttypes/models.py:134: in class ContentType(models.Model): ../../../.venviroments/jnportal/lib/python3.6/site-packages/django/db/models/base.py:100: in __new__ app_config = apps.get_containing_app_config(module) ../../../.venviroments/jnportal/lib/python3.6/site-packages/django/apps/registry.py:244: in get_containing_app_config self.check_apps_ready() ../../../.venviroments/jnportal/lib/python3.6/site-packages/django/apps/registry.py:127: in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") E django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. How can i resolve it? I've looking for an answer in the web, but i didn't find it. Thanks to all who answer. -
AttributeError: module 'django.db.models' has no attribute 'MultiPolygonField'
I face to a next problem: AttributeError: module 'django.db.models' has no attribute 'MultiPolygonField'. It was thrown by django when I trying to makemigrate. Old file of migrations (only 1 makemigrations file was done) was deleted. So Django, thinks for some reason that I import 'django.db.models', not django.contrib.gis.db. this plugins allowed in settings.py There is problem part my models.py code (off cause code break on 'geom' field line) from django.contrib.gis.db import models from renter.models import * from classification_list.models import* class ForestryKeys(models.Model): id = models.IntegerField(primary_key=True) df_forestry = models.TextField(blank=True, null=True), geom = models.MultiPolygonField(geography=True, null=True, blank=True, verbose_name='gmtry') class Meta: managed = True verbose_name = 'frst' verbose_name_plural = 'frtses' -
django-ckeditor failing due to template path problem
I just added django-ckeditor to my django project by installing it: pip install django-ckeditor adding it to INSTALLED_APPS, adding the upload path: CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/" run manage.py collecstatic which only added two files, and adding the URLs to my url.py: url(r'^ckeditor/', include('ckeditor_uploader.urls')), I'm not 100% sure if I'm not missing something there. Then I created a very simple model that looks like this: class BlogPost(models.Model): title = models.CharField(max_length=255, blank=False, null=False) body = RichTextField(blank=False, null=False) When I try to add a new record on the admin tool I get this error: TemplateDoesNotExist at /admin/core/blogpost/add/ ckeditor/widget.html The template loader postmortem looks like this: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\pupeno\projectx\venv\lib\site-packages\django\forms\templates\ckeditor\widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\pupeno\projectx\core\templates\ckeditor\widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\pupeno\projectx\venv\lib\site-packages\django\contrib\admin\templates\ckeditor\widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\pupeno\projectx\venv\lib\site-packages\django\contrib\auth\templates\ckeditor\widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\pupeno\projectx\venv\lib\site-packages\rest_framework\templates\ckeditor\widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\pupeno\projectx\venv\lib\site-packages\reversion\templates\ckeditor\widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\pupeno\projectx\venv\lib\site-packages\colorfield\templates\ckeditor\widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\pupeno\projectx\venv\lib\site-packages\ckeditor_uploader\templates\ckeditor\widget.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\pupeno\projectx\venv\lib\site-packages\django_extensions\templates\ckeditor\widget.html (Source does not exist) The line before the last one is relevant, it's trying to load ckeditor/widget.html from ckeditor_uploader but widget.html is present in ckeditor, not ckeditor_uploader: Any ideas what's going on here? I also tried … -
Check if other records are linked to this record in Django Admin
I've got a model which is something like this: class Activity (models.Model): name = models.CharField( max_length = 100 ) slug = models.SlugField(blank=True, null=True) precedent = models.ForeignKey( 'Activity', on_delete = models.SET_NULL, blank = True, null = True ) active = models.BooleanField(default=True) In effect I have a chain of records, on dependent on another. Within my form validation I want to check if the precedent is active and to check if any other records have the one being saved as their precedent. I understand how to do the former, but I don't know how to do the later within the form clean method. This is what I have. class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = '__all__' def clean(self): super().clean() active = self.cleaned_data.get('active') precedent = self.cleaned_data.get('precedent') if active and not precedent.active: raise forms.ValidationError("Precedent must be active") return self.cleaned_data -
how to send html input tag's value to django url parameter
<form id = "ismForm" action = {% url 'polls:todo' username %} method="get" onsubmit="mySubmitFunction(event)" > <input type="text" name="name" id = "new_user" onchange="ChangeHidden(event)"/> <input type="text" name="email" /> <input type="text" name="pass" /> {% csrf_token%} <input type="submit" name="click" value="Register" /> /> I want to send the value of input text, id = "new_user", to the django url parameter in form action. For understanding, I've written 'username' in the url. -
Django PasswordResetTokenGenerator, check_token(user, token) returns False on Production, Locally Works Fine
Problem: I'm using Django built-in class "PasswordResetTokenGenerator" to generate a token, For user account activation link, Which is sent to the user via email after submitting RegistrationForm.(I use Celery and RabbitMQ for Task execution and message queuing) views.py (RegistrationView) class MyUserCreationView(FormView): template_name = 'accounts/auth/register.html' form_class = MyUserCreationForm def form_valid(self, form): user = form.save(commit=False) user.is_active = False email = user.email user.save() current_site = str(get_current_site(self.request)) confirm_mail.apply_async((user.username, current_site), countdown=5) return render(self.request, 'accounts/auth/register.html', {'email': email}) tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp)+ six.text_type(user.is_active) ) account_activation_token = TokenGenerator() tasks.py (Celery Task) Sends Email to the user from django.core.mail import send_mail from django.contrib.auth.models import User from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.shortcuts import get_object_or_404 from celery import task from ecommerce.settings.base import EMAIL_HOST_USER from account.tokens import account_activation_token @task def confirm_mail(user_name, current_site): user_obj = get_object_or_404(User,username=user_name) token=account_activation_token.make_token(user_obj) subject = 'Activate your MissIndia account.' message = render_to_string( 'email/acc_activate_email.html', { 'user': user_obj, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user_obj.pk)).decode(), 'token': token, } ) mail_sent = send_mail(subject, message, EMAIL_HOST_USER, [ user_obj.email], fail_silently=False) return mail_sent urls.py from django.urls import path, re_path from . import views app_name = 'accounts' urlpatterns = [ re_path('confirm-email/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), ] views.py … -
Django Error >>> Question.objects.get(pub_date__year=current_year) While Making Tutorial1
When I Run below code, I gets an error: Question.objects.get(pub_date__year=current_year) from polls.models import Choice, Question working Question.objects.all() working Question.objects.filter(id=1) working Question.objects.filter(question_text__startswith='What') working from django.utils import timezone working current_year = timezone.now().year working Question.objects.get(pub_date__year=current_year) ERRORS Question.objects.get(pub_date__year=current_year) Question.objects.get(pub_date__year=current_year) Traceback (most recent call last): File "", line 1, in File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 393, in get num = len(clone) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 250, in len self._fetch_all() File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 54, in iter results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py", line 1052, in execute_sql sql, params = self.as_sql() File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py", line 464, in as_sql where, w_params = self.compile(self.where) if self.where is not None else ("", []) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py", line 390, in compile sql, params = node.as_sql(self, self.connection) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\where.py", line 81, in as_sql sql, params = compiler.compile(child) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py", line 390, in compile sql, params = node.as_sql(self, self.connection) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\lookups.py", line 526, in as_sql bounds = self.year_lookup_bounds(connection, rhs_params[0]) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\lookups.py", line 484, in year_lookup_bounds bounds = connection.ops.year_lookup_bounds_for_datetime_field(year) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\operations.py", line 555, in year_lookup_bounds_for_datetime_field tz = timezone.get_current_timezone() File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\timezone.py", line 91, in get_current_timezone return getattr(_active, "value", get_default_timezone()) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\timezone.py", line 77, in get_default_timezone return pytz.timezone(settings.TIME_ZONE) File "C:\Users\Haris\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytz__init__.py", line 178, … -
Any ides to fix error with custom management commands in Django
I am trying to create custom management command which will execute data from Api. I wrote this code from django.core.management.base import BaseCommand, CommandError from data.models import Country import requests import json def extracting(): country_req = requests.get("https://api-football-v1.p.rapidapi.com/countries", headers = {"X-RapidAPI-Key": "my_token"}) parsed_string = json.loads(country_req.text) class Command(BaseCommand): def handle(self, **options): print(extracting()) but when i try to execute it with python manage.py extract in my console i see None while when i try to run this code in console without custom management command i see data which i try to execute. Any ideas -
Django dynamic multi steps form
I have a model, with a lot of non required fields. I want to have a multi steps form, like with django-formtools, but with the next form based of the answers of the precedent form... For example, class Survey(models.Model): # 1st form: generic informations name = models.CharField(max_length=300) age = models.CharField(max_length=300) married = models.BooleanField() #2nd form # show it if married worth_it = models.BooleanField(null=True, blank=True) job_status = models.CharField(max_length=300, null=True, blank=True) #... The first step of the form ask the generic information, and then in the second step the field "worth_it" is show to the user only if "married" was checked. I know it's a bad model design, but i choose it to have a very flexible model that can be quickly adapted to the changing mind of the client.. Is there a way to achieve this, DRY and on server side ? I thank about overloading the get_absolute_url method of the model to get a success url corresponding to the next correct form to update the model but i am searching a better solution. -
How to fetch a part of records from db when using Server-side processing in datatables in Django?
My aim is server-side processing of fetched data with datatables. My problem is that I can not fetch from db a part of records(ex: 50 per ajax request). My implementation fetches all the records. Is there something that I am missing in order to fetch data based on pages of records? My view class ProductSerialNumbersListJSon(LoginRequiredMixin,BaseDatatableView): # my model model = ProductSerialNumbers columns = ['snumber' , 'order','product','registration_date'] order_columns = ['snumber','order','product','registration_date'] max_display_length = 100 def get_initial_queryset(self): print("FETCHED DATA") return ProductSerialNumbers.objects.filter(Q(snumber__isnull=True)|Q(order_id__isnull=True)|Q (order_id__finished=0)) def render_column(self, row, column): return super(ProductSerialNumbersListJSon, self).render_column(row, column) My template <script language="javascript"> $(document).ready(function () { /* Here begins the DataTable configuration. */ $('#warehouse').DataTable({ /* Tell the DataTable that we need server-side processing. */ "serverSide": true, "paging": true, "pageLength": 10, "processing": true, "searching": true, /* Set up the data source */ ajax: { url: "{% url "warehouse_list_json" %}" }, "columns": [ {name: "snumber",}, {name: "order",}, {name: "product",}, {name: "registration_date",}, ] }); }); </script> -
Django-admin AUTO-COMPLETE dropdown dependent
I am trying to get dropdown dependent work with auto-complete-light package only using the admin. It is already working but now i have two forms doing the same thing. http://prntscr.com/mn5tul The dropdown on the left it is working , but the right dont show nothing.How can i delete the right dropdown? MY APP myproject/ |-- myproject |-- daa/ |-- avarias/ |-- models.py |-- admin.py |-- forms.py |-- mapeamento/ |-- models.py |-- views.py URLS.PY urlpatterns = [ url(r'^freguesia-autocomplete/$',FreguesiaAutocomplete.as_view(),name='freguesia-autocomplete',), url(r'^rua-autocomplete/$',RuaAutocomplete.as_view(),name='rua-autocomplete',), ] Mapeamento.models.py class Freguesia(models.Model): nome = models.CharField("Freguesia",max_length=200) class Rua(models.Model): freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE) nome = models.CharField("Rua",max_length=200) Mapeamento.views.py class FreguesiaAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Freguesia.objects.all() if self.q: qs = qs.filter(nome__istartswith=self.q) return qs class RuaAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Rua.objects.all() freguesia = self.forwarded.get('freguesia', None) if freguesia: qs = qs.filter(freguesia=freguesia) else: qs = Rua.objects.none() if self.q: qs = qs.filter(nome__istartswith=self.q) return qs Daa.avarias.models.py class Avaria(models.Model): freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE,verbose_name="Freguesia") rua = models.ForeignKey(Rua, on_delete=models.CASCADE,verbose_name="Rua") Daa.avarias.forms.py class AvariaForm(forms.ModelForm): class Meta: model = Avaria fields = '__all__' freguesia = forms.ModelChoiceField(queryset=Freguesia.objects.all(), widget=autocomplete.ModelSelect2(url='freguesia-autocomplete'), ) rua = forms.ModelChoiceField(queryset=Rua.objects.all(), widget=autocomplete.ModelSelect2(url='rua-autocomplete', forward=['freguesia'])) Daa.avarias.admin.py class AvariaAdmin(admin.ModelAdmin): form = AvariaForm model = Avaria fieldsets = ( ('...', { 'fields': ('freguesia','rua',) }), ) -
Create REST API using Django
I have a python script to test REST APIs for CRUD operations. The APIs have been built in JAVA and to test them, input data to be posted is created in JSON/XML/YAML files and then we append the file path in the URL itself and hit the same, which returns the response back in the respective format. Now I need to create same APIs using django, for which i have been having a hard time. All i could find on google is posting data using form but nowhere from a json file. But suppose I do not want a form, I just want a URL to take input from flat file and update the database. Is it possible to create such API using django? -
Running django tests results in duplicate column name id
I'm creating a test for testing a helper function in Django. When running the test, I get the error "Duplicate column name ID" I've tried to run python3 manage.py migrate --fake-initial, saw a solution here on Stackoverflow stating that it would work, but it didn't. Test.py: from django.test import TestCase from reservations.models import Reservation, Table, Restaurant from employee.helpers import * class GetTablesWithCapacityTestCase(TestCase): def setUp(self): Restaurant.objects.create( name="Test Restaurant", description="Restaurant for use in test", opening_time=12, closing_time=24, ) Table.objects.create( restaurant=Restaurant.objects.filter(name="Test Restaurant"), number_of_seats=5, is_occupied=0 ) Table.objects.create( restaurant=Restaurant.objects.filter(name="Test Restaurant"), number_of_seats=4, is_occupied=0 ) def test_get_tables(self): tables = get_tables_with_capacity(5) self.assertEqual(1, tables.size) Models.py: from django.db import models from guest.models import Guest from django.utils import timezone class Restaurant(models.Model): name = models.CharField(max_length=250) description = models.CharField(max_length=250) opening_time = models.TimeField() closing_time = models.TimeField() def __str__(self): return self.name class Table(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True, blank=True) number_of_seats = models.IntegerField() is_occupied = models.BooleanField() def __str__(self): return str(self.id) class Reservation(models.Model): guest = models.ForeignKey(Guest, on_delete=models.CASCADE) number_of_people = models.IntegerField(default=0) start_date_time = models.DateTimeField(default=timezone.now) end_date_time = models.DateTimeField(default=timezone.now) created_date = models.DateTimeField(default=timezone.now) table = models.ForeignKey(Table, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.start_date_time The result I get when running the test is: MySQLdb._exceptions.OperationalError: (1060, "Duplicate column name 'table_id'") The above exception was the direct cause of the following exception: django.db.utils.OperationalError: (1060, "Duplicate … -
Import-Export option on the User and Group for django application
Summary ` Am new on python and django framework. in fact i start coding in python 2 days ago cause i have to handle an open source application for my company. What i have done Am practicing on import-export module of django following this article https://simpleisbetterthancomplex.com/packages/2016/08/11/django-import-export.html Everything works perfectly i can import and export person object using csv format. My Code (view.py) `from django.shortcuts import render from tablib import Dataset from django.http import HttpResponse from .resources import PersonResource def export(request): person_resource = PersonResource() dataset = person_resource.export() response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="persons.csv"' return response def simple_upload(request): if request.method == 'POST': person_resource = PersonResource() dataset = Dataset() new_persons = request.FILES['myfile'] imported_data = dataset.load(new_persons.read()) result = person_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): person_resource.import_data(dataset, dry_run=False) # Actually import now return render(request, 'core/simple_upload.html')` Issue Now the issue is this i dont wish to perform this operation on the person object, i want it to be on the django User and Group objects. When i click on this objects i dont get the options for import and export. How do i go about this? Thank you! -
How to perform Signup and Sign In Api using Django for Android
I am new to back end development. I am using Django framework for implementing back end of my Android application. My app has "create account" and login screens. How can I create api for that using Django? Someone please help! -
Django JSONField filtering Queryset where filter value is annotated sum value
How do I properly write the filter code so it returns only the Animals that are not sold out. I'm using POSTGRES db, python3.6 and Django 2.1.7 (currently there are v2.2a1,v2.2b1 pre-release versions) My questioin is an extension to Django JSONField filtering which filters on a hard coded value in the filter. My Case requires an annotated value in the filter. models.py I know that the models can be optimized, but I already have huge amount of records since more than 3 years from django.db import models from django.contrib.postgres.fields import JSONField class Animal(models.Model): data = models.JSONField(verbose_name=_('data'), blank=True) class Sell(models.Model): count = models.IntegerField(verbose_name=_('data'), blank=True) animal = models.ForeignKey('Animal', on_delete=models.CASCADE, related_name="sales_set", related_query_name="sold" ) in my api I want to return only the animals that still have something left for selling animal = Animal(data={'type':'dog', 'bread':'Husky', 'count':20}) What I want to filter should be similar to animal.data['count'] > sum(animal.sales_set__count Animal.objects.annotate(animals_sold=Sum('sales_set__count')) .filter(data__contains=[{'count__gt': F('animals_sold')}]) with the code above i get builtins.TypeError TypeError: Object of type 'F' is not JSON serializable if I remove the F it won't filter on the value of the animals_sold, but on the text 'animals_sold' and it doesn't do any help. Animal.objects.annotate(animals_sold=Sum('sales_set__count')) .filter(data__contains=[{'count__gt': F('animals_sold')}]) -
model is not showing django admin 2.1
I'm damned if I can figure out why my models are not showing in the admin.i am working on a project called btre_project and this problem is troubling me,help to figure out the solution models.py in the Listing app: from django.db import models from datetime import datetime from realtors.models import Realtor class Listing(models.Model): realtor=models.ForeignKey(Realtor,on_delete=models.DO_NOTHING) models.CharField(max_length=100) state=models.CharField(max_length=100) zipcode=models.CharField(max_length=20) description=models.TextField(blank=True) price=models.IntegerField() bedrooms=models.IntegerField() bathrooms=models.DecimalField(max_digits=2,decimal_places=1) garage=models.IntegerField() sqft=models.IntegerField() lot_size=models.DecimalField(max_digits=5,decimal_places=1) photo_main=models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1=models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_2=models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_3=models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_4=models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_5=models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_6=models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) is_published=models.BooleanField(default=True) list_date=models.DateTimeField(default=datetime.now,blank=True) def __str__(self): return self.title admin.py listing app: from django.contrib import admin from .models import Listing class ListingAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'is_published', 'price', 'list_date', 'realtor') list_display_links=('id','title') list_filter=('realtor',) admin.site.register(Listing) projects settings.py from django.contrib import admin from .models import Listing class ListingAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'is_published', 'price', 'list_date', 'realtor') list_display_links=('id','title') list_filter=('realtor',) admin.site.register(Listing) urls.py: from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('pages.urls')), path('listings/',include('listings.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Help me to figure out the solution -
Python Django if/else logic not returning correct queryset
I'm sure there is a much simpler way to do this (yes I know my code is very redundant), it's just not immediately clear to me and I'm also a beginner. This is also not rendering out the correct data. On the initial request.GET for the homepage (no filter is applied from if 'radius' in request.POST) then the page should be populated with all users. However if 'radius' in request.POST then the page should return the results of the filtered queryset. Right now, on initial GET it appears the page is returning {% for profile in filter.qs %} (with no filter applied) however when a filter is applied, it returns No results, try again? even when there is a matching result. I can see there is a matching results in the console <QuerySet [<User: xxx>]> My code is below and I would really appreciate any advice or materials that will point me in the right direction. .html <form method="POST"> {% csrf_token %} <input type="number" name="radius"> {{ filter.form }} <button type="submit">Search.</button> </form> {% if filter %} {% for profile in filter.qs %} <h5>{{ profile.user.first_name }}</h5> <p>{{ profile.age }}</p> {% empty %} <h1>No results, try again?</h1> {% endfor %} {% else %} … -
Django - Get counts of objects in related sets
There are two models: class Article(..: locations = ManyToMany('Location'...,related_name='locations') class Location(...): ... I'm looking for a way to get number of location appearance in any related_set Article.locations For example: Article1 - Milan, Vienna, Paris Article2 - Milan, Paris Article3 - Paris Article - Dubai The result would be: Paris - 3, Milan - 2, Vienna - 1, Dubai -1 I ended with this: Location.objects.all().annotate(Count(?)) Is it possible to do it in one or two Queries? I want to avoid doing it using loops. Moreover, I want to do it considering only subset of Articles (filtered queryset). -
Django No module named 'mysite.settings' on Heroku
I'm new to Heroku and trying to setup a Django project with multiple setting files. When I run/open my Django app live on Heroku, I get "ModuleNotFoundError: No module named 'mysite.settings'. The catch is that I don't have a 'mysite.settings' file...just a directory. Running the project locally in Visual Studio works fine, and when I do a runserver with no parameters on Heroku via Powershell, it also runs fine, including finding the correct settings file. It just bombs out when I try to open it using 'heroku open'. My directory structure looks like this: -mysite (main project sub-folder) | +- settings | +----- __init__ +----- base +----- development (not imported to production site) +----- production | +- __init__ +- forms +- models +- urls +- views I have looked for the past two days over various posts and nothing seems to work. No matter what I've tried, the error message I get refers to the 'mysite.settings' module which I don't load anywhere. I only load 'mysite.settings.production'. Is the error referring to the directory and not a file? A list of what I've tried: I've set the DJANGO_SETTINGS_MODULE env variable to "mysite.settings.production". heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings.production I've tried setting the PYTHONPATH env … -
How to run a task after every 10 seconds using celery python
I want to run a task after every 1 minutes using celery but somehow it is not working . Can anyone help me to do this ? Code from celery.task import periodic_task from celery.schedules import crontab from datetime import timedelta @periodic_task(run_every=timedelta(seconds=10)) def testProgram(): file = open("/home/op.txt","w+") file.write("test") file.close() The given code is not working can anyone tell me what is the problem and how to solve it ? -
How can I transtlate this SQL to a Django database request?
select * from first_table as ft, second_table as st where ft.user_id = st.user_id The above sql has two tables that have the same column named "user_id" - I"d like to get the results of joining both tables but unsure how to translate the sql I know into something Django would recognise. -
Django celery run periodic task every day at specific time
I want to run django celery periodic task every day at 6:30 pm tasks.py import celery from datetime import datetime @celery.task def my_task(): print(' task called ') print(datetime.now()) return True celery.py from __future__ import absolute_import, unicode_literals from celery import Celery from tasks import my_task from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') celery_instance = Celery('my_app') celery_instance.config_from_object('django.conf:settings', namespace='CELERY') celery_instance.autodiscover_tasks() @celery_instance.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute=30, hour=16, day_of_week='mon,tue,wed,thu,fri,sat'), my_task.s(), ) when i hit celery -A mudrakwik worker -B the task is not hitting at 6:30 pm -
How to compress uploaded file with ffmpy in django?
I have a model with FileField. I have built the form for the model. I want to compress the file using the ffmpy library. I read on the django docs that I can write a custom FileUploadHandler(I have to implement some of the methods while sub classing this class). My question is how can I use the ffmpy library to compress the file? -
CORS issue when React.js app sends request to Django backend
I have Django app (XXX.XXX.XXX.XXX:55002) and React.js front-end (XXX.XXX.XXX.XXX:55001). The app works perfectly locally, but I have CORS issue in the server. I can properly open the front-end in the server, but when it sends the request to Django app via HTTP, then it throws error: Invalid HTTP_HOST header: 'XXX.XXX.XXX.XXX:55002'. You may need to add 'XXX.XXX.XXX.XXX' to ALLOWED_HOSTS. OPTIONS http://XXX.XXX.XXX.XXX:55002/predict?&arrivalDelay=5&schedTurnd=45 400 (Bad Request) fetchData @ Test.js:89 value @ SingleFlight.js:40 Ia @ react-dom.production.min.js:5351 Ra @ react-dom.production.min.js:5099 Aa @ react-dom.production.min.js:5066 za @ react-dom.production.min.js:5481 En @ react-dom.production.min.js:1731 (index):1 Access to fetch at 'http://XXX.XXX.XXX.XXX:55002/predict?&arrivalDelay=5&schedTurnd=45' from origin 'http://XXX.XXX.XXX.XXX:55001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. This is the code of settings.py. As you can see I added XXX.XXX.XXX.XXX to ALLOWED_HOSTS: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'hfkahsf' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['XXX.XXX.XXX.XXX', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', …