Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why am I not getting the second validation?
I am trying to validate my signup form, but I am getting the desired output from the first, and third, but I try to validate if it's short or too common. I got nothing, but I can have matched validation if(data['message']['email'] == 'Enter a valid email address.' || data['message']['email'] == 'User with this Email address already exists.'){ $("#erroremail").html(data['message']['email'][0]); } if(data['message']['password2'] == 'This password is too short.'){ $("#errorpass").html(data['message']['password2'][0]); } if(data['message']['password2'] == "The two password fields didn't match."){ $("#errorpass").html(data['message']['password2'][0]); } JSON response message: email: ["User with this Email address already exists."] password2: Array(3) 0: "This password is too short. It must contain at least 8 characters." 1: "This password is too common." 2: "This password is entirely numeric." -
Cant render new context to template from another view In Django
I create an app to check how to run background tasks in Django but I catch such error in rendering that I can't explain and I have not found a similar question anywhere. I cant figure up where are an error. There is my views.py from django.shortcuts import render, get_object_or_404, redirect from django.http import JsonResponse from django.http import HttpResponseBadRequest, HttpResponseRedirect, HttpResponse from django.urls import reverse import json import datetime from .models import Simulation, get_simulation from .forms import SimulationForm # Create your views here. def simulation_page(request): context = { "simulations_exists": Simulation.objects.all().exists() } return render(request, 'simulation_page.html', context) def simulate(request): if request.method == 'POST': # data = json.loads(request.body) action = data['action'] # 0 or 1 that mean run or stop sim = get_simulation() if action == "0" and sim.status == True: sim.status = False sim.save() elif action == "1" and sim.status == False: sim.status = True sim.save() context = { "simulations_exists": True, "days_passed": sim.get_simulation_day(), "simulation_today_str": (sim.today).strftime("%d %B, %Y"), # 06/12/18 -> 12 June, 2018 "simulation_status": sim.status } return render(request, "simulation_page.html", context=context) return HttpResponseBadRequest() There is my simulation_page.html template: {% extends "base.html" %} {% block content %} <h1>Simulation</h1> <div id='simulation_info'> simulation_status: {{simulation_status}} </div> <div class='container'> {% if not simulations_exists %} <p><a href="{% url 'simulation:simulation_create' … -
Django - Logging not working in production
This issue is driving me nuts. For the longest time logging was working fine, after I changed the format a little bit and made new sub folders it won't work when running the app in prod mode (with nginx + gunicorn) but logging will work when using "runserver". The Gunicorn Log does not show any issue, the app itself works fine... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': ">>> %(asctime)s | %(levelname)s | %(name)s:%(lineno)s | %(message)s", 'datefmt': "%Y-%m-%d | %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/app/WSx.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 7, }, 'user_file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/user/User.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 30, }, 'debug_file': { 'level': 'DEBUG', # 'class': 'logging.handlers.TimedRotatingFileHandler', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 1024 * 1024 * 15B = 15MB 'filename': LOG_DIR + '/debug/WSX_DEBUG.log', 'formatter': 'verbose', # 'interval': 1, # 'when': 'midnight', 'backupCount': 7, }, }, 'loggers': { … -
How is it possible to have inlines inside inlines when using a formset in django
I want to apply in my formset the case of having a form-Case model, and in inlines having Offers - Offer model of inlines also, Yachts - Yacht model. models.py class Case(models.Model): client=models.ForeignKey(Client,null=True,verbose_name="Client",on_delete = models.CASCADE) date_created = models.DateTimeField("Date of Case Creation", null=True,blank=True, default=datetime.datetime.now) comment = models.CharField("Comments",max_length=500, blank=True, null=True) class Offer(models.Model): date_created = models.DateTimeField("Date of Offer creation", null=True,blank=True, default=datetime.datetime.now) notes=models.CharField("Offer Notes",max_length=100, blank=True) case=models.ForeignKey(Case,verbose_name="Case",on_delete = models.CASCADE) class Yacht(models.Model): name = models.CharField(max_length=50, verbose_name="Name") price_per_day=models.DecimalField("Price(€) / Day", max_digits=8, decimal_places=2, default=0,blank=True) passengers = models.IntegerField("Passengers",blank=True,null=True) class OfferHasYacht(models.Model): offer=models.ForeignKey(Offer,null=True,verbose_name="Offer",on_delete = models.CASCADE) yacht=models.ForeignKey(Yacht,null=True,verbose_name="Yacht",on_delete = models.CASCADE) In forms.py the : OfferOfferHasYachtFormSet=inlineformset_factory(Offer,OfferHasYacht,form=OfferHasYachtForm,extra=1) works fine having as form the Offer and as inlines the OfferHasYacht(excluding the offer from OfferHasYachtForm) class OfferHasYachtForm(ModelForm): yacht = ModelChoiceField(required=True,queryset=Yacht.objects.all(),widget=autocomplete.ModelSelect2(url='yacht-autocomplete')) class Meta: model = OfferHasYacht fields = ['yacht'] def __init__(self, *args, **kwargs): super(OfferHasYachtForm, self).__init__(*args, **kwargs) self.fields['yacht'].label = "Choose Yacht" but when trying to declare the formset: CaseOfferHasYachtFormSet=inlineformset_factory(Case,OfferHasYacht,form=OfferHasYachtForm,extra=1) the django complaining that: ValueError: 'intranet.OfferHasYacht' has no ForeignKey to 'intranet.Case'. How is it possible to solve that in order to have a view that I can create or update a case having offers (as inlines) and every offer having yachts (as inlines). -
Memcached works in Django shell but not for view functions
I am trying to implement view based caching using memcached in my django project. I have brew installed it in my machine and also installed python-memcached in my virtual env. Memcache works in python3 manage.py shell. >>> from django.core.cache import cache >>> cache.set('foo', 'bar', 600) >>> cache.get('foo') 'bar' But when I put the cache_page() decorator on my view function and load the view I do not get any set or get logs on memcached -vv. I have the following in my settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } Pardon me, I have very basic understanding of the caching process. I know that memcache stores cached data as key value pairs but how does it pick a key for the decorated view? If I cache the ListView will I be able to query using different filters from the cache? A few comments and links to online resources will be helpful. -
How do I access a complete row through a foreign key in Django?
guys :) Let's say I have the following code: class Model3D(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) settings_of_model = models.ForeignKey('Settings', on_delete=models.CASCADE, null=True) class Settings(models.Model): id = models.AutoField(primary_key=True) extruder_Temperature = models.PositiveIntegerField(null=True) layer_Height = models.DecimalField(max_digits=100, decimal_places=100, null=True) model_id = models.ForeignKey('Model3D', on_delete=models.CASCADE) printer_Name = models.ForeignKey('Printer', on_delete=models.CASCADE, null=True) Every model has one row in table settings with the settings for the model. How can I access this row to get it for an specific model? The following code did not work. def get_settings(id_of_model): settings_of_model = Model3D.objects.filter(id=id_of_model)prefetch_related('Settings') return settings_of_model Can you help? -
uWSGI - never sleep mod?
I have a django app, running with uwsgi behind nginx server, all on same debian and python2.7. On the first start of the application, everything goes very well, the queries are fast. If I never question the application for a long time (> 1h maybe more), the first new query takes a long time to answer and after waiting then everything reworks correctly. As if the service was in standby and make time to respawn. I would never wait, even if the service has not been solicited for several hours. That is possible ? I have tried "cheaper" configuration, same result. My ini file : [uwsgi] logto = $(APP_LOGS_DIR)/uwsgi.log chdir = $(APP_SRC_DIR) manage-script-name = true mount = /=$(APP_SRC_DIR)/wsgi.py plugins = python virtualenv = $(APP_VENV) master = true processes = 4 socket = 0.0.0.0:9001 static-map = /static=$(APP_SRC_DIR)/static/ vacuum = True buffer-size = 8192 vacuum = true cheaper-algo = spare cheaper = 2 cheaper-initial = 3 workers = 4 cheaper-step = 1 and a part my nginx conf : upstream app { server 127.0.0.1:9001; } server { [...] location / { include uwsgi_params; uwsgi_pass app ; } } -
How to write a self referencing Django Model?
I have a Django model "Inspection" which has: InspectionID (PK) PartID SiteID Date Comment Report Signiture I want to be able to have a one to many relationship between the inspection ID and date. So one ID can have inspections at many dates. How would I do this? I currently have the following: class Inspection(models.Model): InspectionID = models.IntegerField(primary_key=True, unique=True) PartID = models.ForeignKey('Part', on_delete=models.CASCADE) SiteID = models.ForeignKey('Site', on_delete=models.CASCADE) Date = models.DateField(auto_now=False, auto_now_add=False) Comment = models.CharField(max_length=255, blank=True) Report = models.FileField(upload_to='docs', null=True, blank=True) Signiture = models.CharField(max_length=255, blank=True) I thought about using models.ForeignKey but I really don't know how to implement that properly in this situation. -
How can redefine attribute in abstract model?
Hello I have two models class A(models.Model): slug = models.SlugField() class Meta: abstract = True class B(models.Model): slug = models.CharField() class Meta: abstract = True I get error AttributeError: Manager isn't available; B is abstract How do can to redefine attribute in abstract class? class A cannot be changedю -
Change Celery task rate limit and apply/reschedule immediately
I have a Django application called api and a rate-limited Celery task called email_slow_track. I use the following command to change the rate limit (on the command line): $ celery -A api control rate_limit email_slow_track 1/s -> celery@a5dac4396c0b: OK new rate limit set successfully Let's say the initial rate limit is 3/m (one every ~20sec), and I have a bunch of jobs in the queue. I then change the rate limit to 1/s. I observed that as a result, old jobs will continue to run roughly every 20 seconds, while new jobs "jump the queue" and sneak in once a second. Is there a way to get existing jobs rescheduled, so that submission order is maintained, and rate limit changes are applied to existing jobs as well? (Ideally, this would be on the command line.) -
Django pagination - for loop in all pages
I have a list of objects that I would like to display in an ul/li. For that I do the code below: <ul id="myUL"> {% for l in lpps %} <li id="lpps"><a href="#">{{ l.codeACL }} {{ l.libelle }}</a></li> {% endfor %} </ul> The problem is that in my view, I ask to display only 15 objects per page. But I want to ignore this and display all the objects on all the pages. Is there something like for l in lpps.page(all)...? -
Translating cards
i am only one month django learning. i wanna do cards with word on eng so user can send translate in form and he will get true or false result so i have card like this: class Cards(models.Model): class Meta: verbose_name = "Карточка" verbose_name_plural = "Карточки" category = models.CharField(max_length=30, db_index=True) word = models.TextField(max_length=100, db_index=True) def __str__(self): return self.title so i need to compare request from user with 'word' i have in my database field and print result so can u tell me what i need to google to do this, because i can find nothing all day -
Inspect list of Celery jobs on command line
In a Celery setup with Django, I registered two tasks, email_slow_track and email_fast_track. I would like to inspect the list of jobs for each task on the command line, but I was unable to find the right command. Here's what I tried (my application name is api): inspect registered: This appears to list registered tasks, not jobs submitted under these tasks. However, it at least shows that the connection is set up properly, and that the tasks are known. $ celery -A api inspect registered -> celery@a5dac4396c0b: OK * api.celery.debug_task * email_fast_track [rate_limit=1/s] * email_slow_track [rate_limit=10/m] inspect query_task <task_name>: Empty result. I'm not sure what this command should do, and whether this is the expected result. $ celery -A api inspect query_task email_slow_track -> celery@a5dac4396c0b: OK {} inspect query_task <task_id>: Empty result. Just thought I'd give it a try ... $ celery -A api inspect query_task cb1ecc1c-5746-4d08-ad50-4bff4d57855b -> celery@a5dac4396c0b: OK {} Note that my tasks do run properly. I'm not trying to fix task execution; the issue here is getting a list of tasks. I am able to see all jobs with Celery Flower, so things are fine in general. But can I get that information from the command line? -
Django - can I do this without a raw query
I am learning Django, and have got quite a long way using the documentation and various other posts on stackoverflow, but I am a bit stuck now. Essentially I want to query the database as follows SELECT w.wname, w.act_owner_id, wi.act_code, wi.act_provider, SUM(ft.quantity) AS "position", prices.Current, prices.MonthEnd, prices.YearEnd, cost.avgcost, sec.securityName AS "security" FROM finance_wrapperinstance as wi INNER JOIN finance_wrapper as w ON (w.id = wi.wrapperType_id) INNER JOIN finance_security as sec ON (ft.security_id = sec.id) left outer JOIN finance_transaction as ft ON (wi.id = ft.investwrapperID_id) left outer Join (SELECT hp.security_id as secid, max(Case when hp.date = '2019-11-18' then hp.price end) as 'Current', max(Case when hp.date = '2019-10-30' then hp.price end) as 'MonthEnd', max(Case when hp.date = '2018-12-31' then hp.price end) as 'yearEnd' FROM finance_historicprice as hp GROUP BY hp.security_id ) AS prices ON (prices.secid =ft.security_id) INNER JOIN (SELECT trans.security_id AS secid, trans.investwrapperID_id as iwID, SUM((CASE WHEN trans.buysell = 'b' THEN trans.quantity ELSE 0 END)* trans.price) / SUM(CASE WHEN trans.buysell = 'b' THEN trans.quantity ELSE 0 END) AS avgCost FROM finance_transaction as trans GROUP BY trans.security_id, trans.investwrapperID_id) AS cost ON (cost.secid = ft.security_id and cost.iwID = wi.id) GROUP BY w.wname, wi.wrapperType_id, wi.act_code, wi.act_provider, ft.security_id but I don't know how to use the Django … -
Is there a way to handle admin radio buttons changes?
I have model (Object) which have some fields + rating: class Object(PolymorphicModel): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, db_column='author') title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.IntegerField(default=10) created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" There is also Comment model to these objects: class Comment(models.Model): object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, db_column='author') content = models.TextField() rating = models.TextField() approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.content}" Ok here is the deal, I have approved_object and admin_seen which are represented to radio buttons in Django Admin. I want, when, some of admins, open comment, which is not approved and check radio buttons for admin_seen and approved_object the script should update ratings and average rating with Comment.objects.filter(object_id=pk).aggregate(Avg('rating'))['rating__avg'] So I found how to rewrite save method with def save_method but I don't know how to handle if radiobutton is checked or not and update ratings? admin.py: class CommentScreenAdmin(admin.ModelAdmin): raw_id_fields = ('author', 'object') def save_model(self, request, obj, form, change): #to do... -
Python Django Countdown
well I write again because I implemented a timer in my test portal, the time is defined at the time of creating the exam, use the code of http://www.keith-wood.name/countdown.html for my html and Well, I need help on how to get the exam over when the timer reaches zero. takenquiz_form.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <!--Barra de progreso--> <div class="progress mb-3"> <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria- valuenow="{{ progress }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ progress }}%"></div> </div> <!--Cronometro--> <div class="mb-3" id="defaultCountdown" style="float: right"></div> <h2 class="mb-3">{{ quiz.name }}</h2> <hr> <div class="d-md-flex flex-md-equal w-100 my-md-3 pl-md-3"> <div class=" mr-md-3 pt-3 px-3 pt-md-5 px-md-5 overflow-hidden"> <p >Contenido: {{question.category}} </p> <h5 class="lead"> <strong>{{question.number}}.</strong> {{ question.text }} ({{ question.puntaje}} puntos)</h5> <!--Audio de la pregunta--> {% if question.document == 'False' %} {% else %} {% if question.document %} <audio controls> <source src="{{ question.document.url }}" type="audio/mpeg"> </audio> {% endif %} <p></p> {% endif %} {% if question.description %} <h5 class="lead">{{ question.description }} </h5> {% endif %} <form method="post" name="takenquiz" id="takenquiz" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary redirect" href="javascript:void(0)" onClick="document.takenquiz.submit();" >Siguiente →</button> </form> </div> <div class= " mr-md-3 pt-3 px-3 pt-md-5 px-md-5 … -
How to email specific users when a new question is registered
I would like to send an email to all teachers who teach subjects related to a new question (whether it is created by the admin panel or the question creation form) so that they can approve the question. How to do this? models.py class Usuario(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,verbose_name="Usuário") USUARIO_CHOICES = ( (UM,'Aluno'), (DOIS,'Professor'), ) tipoUsuario = models.IntegerField('Tipo de Usuário',choices=USUARIO_CHOICES,default=1) class Questao(models.Model): aOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra a") bOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra b") cOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra c") dOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra d") eOpcao = models.CharField(max_length=500,null=False,blank=True,verbose_name="Letra e") settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@outlook.com' EMAIL_HOST_PASSWORD = 'Mypassword' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'MySite <myemail@outlook.com>' views.py def add_questoes(request): if request.method == 'POST': # If the form has been submitted... form = QuestaoForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass form.save() subject = 'Questão adicionada' message = 'Há uma nova questão adicionada' recepient = str(sub['Email'].value()) send_mail(subject, message, EMAIL_HOST_USER, [recepient], fail_silently = False) return redirect('/') # Redirect after POST else: form = QuestaoForm() # An unbound form return render(request, 'polls/add_question.html', {'form': form}) forms.py class QuestaoForm(forms.ModelForm): aOpcao = forms.CharField(max_length=500,label="Letra a") bOpcao = forms.CharField(max_length=500,label="Letra b") cOpcao= forms.CharField(max_length=500,label="Letra c") dOpcao = forms.CharField(max_length=500,label="Letra d") eOpcao = forms.CharField(max_length=500,label="Letra e") … -
Django REST testing - how to specify pk argument referring to the model instance created in setUp function
I have a model "Article" and I want to test if authorized user can GET an individual article. The testing class is: class TestPost(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.user = User.objects.create_user( username='Name', email='test@company.com', password='secret') self.article = Article.objects.create( author = 'Author', title = 'Article title', body = 'Body content ...') def test_detail_user(self): request = self.factory.get(reverse('article_id', kwargs={'pk': 1})) request.user = self.user response = ArticleDetail.as_view()(request, pk=1) self.assertEqual(response.status_code, 200, f'Expected Response Code 200 - OK, received {response.status_code} instead.') The URL pattern is: path('<int:pk>/', ArticleDetail.as_view(), name = 'article_id'), And when running tests I get the following error: f'Expected Response Code 200 - OK, received {response.status_code} instead.') AssertionError: 404 != 200 : Expected Response Code 200 - OK, received 404 instead. I suppose the problem is in the specified 'pk', but I cannot figure out how to specify pk without stating an exact figure of 1. How can I refer to the article created in setUp function instead? -
How to render a radio button choice in Django Modelform based on enum field defined at the model level?
I have an enum field ("type") defined at the model level like below, how should I implement the corresponding ModelForm field in my model field? Actually the rendered HTML code don't output radio button and wraps this field within an empty list. Should "replicate" the enum choices within the form class in order to populate radio button choices, is there another to take advantage of choices already defined at the model level? Rendered HTML <div class="form-group"> <label for="id_type_0">Type</label> <ul id="id_type" class="form-control"> </ul> </div> models.py class Foo(models.Model): name = models.CharField(max_length=50, blank=False, null=False) TYPE_LIST = [ ('EXT_CL', 'Customer'), ('INT_TP', 'Internal third party'), ('INT_OW', 'Owner'), ] type = models.CharField(max_length=6, choices=TYPE_LIST,default='EXT_CL') class Meta: managed = True db_table = 'foos' fields = ('name','type') def __str__(self): object_name = self.name return object_name forms.py class FooCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix = '' self.fields['name'] = forms.CharField(label='Name',widget=forms.TextInput(attrs={ 'class': 'form-control' })) self.fields['type'] = forms.ChoiceField(label='Type',required=True,widget=forms.RadioSelect(attrs={ 'class': 'form-control' })) class Meta(object): model = Foos fields = ('name','type') def clean_name(self): name = self.cleaned_data['name'] return name def clean_type(self): type = self.cleaned_data['type'] return type template.html <form id="foo-create-form" method="post" action=" " role="form"> {% csrf_token %} <div class="form-group"> {{ foo_create_form.name.label_tag }} {{ foo_create_form.name }} </div> <div class="form-group"> {{ foo_create_form.type.label_tag }} {{ foo_create_form.type }} </div> </form> -
Cannot resolve django error. "Apps aren't loaded yet."
"python manage.py runserver" Tried to run. Receive “Apps aren't loaded yet.” Fixing INSTALLED_APPS doesn't help. I checked Traceback and thought that there was a cause in "init.py", but I couldn't understand. I think that there is a mistake in the method because "model" is split. Traceback File "/Users/t.a/Desktop/apasn/apasn_rest/apasn_back/apps/models/commons/__init__.py", line 1, in <module> from .accounts import * File "/Users/t.a/Desktop/apasn/apasn_rest/apasn_back/apps/models/commons/accounts.py", line 4, in <module> from django.contrib.auth.base_user import BaseUserManager File "/Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/t.a/Desktop/apasn/apasn_rest/venv/lib/python3.7/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. settings/base.py INSTALLED_APPS = [ ... 'apps.apps.AppsConfig', ] apps/apps.py from django.apps import AppConfig class AppsConfig(AppConfig): name = 'apps' models/commons/init.py from .accounts import * apps/models/commons/accounts from django.db import models from django.utils import timezone from django.core.mail import send_mail from django.contrib.auth.base_user import BaseUserManager from django.core.validators import RegexValidator from django.utils.translation import gettext_lazy as _ import uuid as uuid_lib from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class UserManager(BaseUserManager): ... class User(AbstractBaseUser, PermissionsMixin): ... -
DateTimeField to str and read from str
I have a problem with understating how to deal DateTimeField. I have model with DateTimeField, view which returns jsons containing this field and another view which use provided data (as string) to filter result # model date = models.DateTimeField(auto_now=True) # first view return str((self.date.isoformat() for date in ...)) # f. exp: ['2019-11-19T15:22:47.788254+00:00'] # second view Row.objects.filter(data__lte=data_from_GET) If I have used 2019-11-19T15:22:47.788254+00:00 I reciver error ValidationError at /csv/ ["'2019-11-19T15:22:47.788254+00:00' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] I can not find an easy way (without string manipulation) to return data in a format acceptable by the filter method. What is interesting: 2019-11-19T15:22:47.788254-00:00 not ok 2019-11-19 15:22:47.788254+00:00 not ok 2019-11-19 15:22:47.788254-00:00 ok -
React & Django - How can I automatically reflect server changes on front-end?
Looking for a bit of advice. I have a current architecture of Django and PostgreSQL, where a whole lot of activity is happening to the data via the ORM, through scheduled jobs. The data on the backend is being processed and updated on roughly 30 second intervals. The data is available to the front-end through a bunch of DRF serialisers (basic REST API). This is just being piped to standard HTML templates at the moment. I'd like the React front-end to mirror this behaviour, and am looking for best-practice advice on how this is typically done. I know in practice how this works in other frameworks but am not certain of doing this well (namely, connecting React's DOM automation to server-side updates). (I don't want to get involved with websockets, at all.) Theoretically, I understand there is two ways to do this: Front-end AJAX polling the API for new data HTTP/2 Server Push Something built into React that will load stuff in incrementally? Appreciate the advice - (short examples would be really helpful if possible). -
How to re-initialize session variable?
I have develop a Django project with authentification app developped using Vitor Freitas's tutorials (https://simpleisbetterthancomplex.com). Now I wonder how can be my sessions variables re-initialized when user logout? Currently it does not re-initialize my sessions variables I did not develop any views for authentification so I do know how to do it -
how to upload multiple images in django
models.py from django.db import models class Ads(models.Model): business_id = models.CharField(max_length=20, blank=True, null=True) description = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) forms.py from django import forms from .models import Ads class AdsForm(forms.Form): class Meta: model = Ads fields = '__all__' view.py from .models import Ads from .forms import AdsForm from django.core.files.storage import FileSystemStorage def ads_view(request): if request.method == 'POST': form = AdsForm(request.POST, request.FILES) if form.is_valid(): business_id = request.POST.get('business_id') description = request.POST.get('description') image = request.FILES['image'] print(business_id) print(description) print(image) file_storage = FileSystemStorage() ads_obj = Ads(business_id=business_id, description=description, image=file_storage.save(image.name, image)) ads_obj.save() return redirect('/ads/') else: form = AdsForm() return render(request, 'ads/myads.html', {'form': form}) myads.html <form action="#" method="post" enctype="multipart/form-data"> <input type="text" name="business_id" class="form-control form-control" id="colFormLabelSm" placeholder=""> <textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea> <input type="file" name="image" class="form-control" id="exampleFormControlInput1" multiple> <button type="submit" class="btn btn-primary mt-5">Submit</button> </form> Here I'm trying to upload multiple images but in view i'm getting lastly selected one image only. How to get all images and save all images. Help me in this problem. -
Django "before dispatch" mixin
I am trying to define a mixin to set up a member and check for permissions before the view's dispatch is called but class hierarchy is "getting in the way". The behavior for a specific view would be: class Page1View(TemplateView): # ... def dispatch(self, request, *args, **kwargs): self.object = self.object() if not object_permission(request.user, self.object): raise PermissionDenied return super(Page1View, self).dispatch(request, *args, **kwargs) I would like to extract the bit before the super().dispatch() call into a mixin so that I can reuse it in different views: class Page1View(TemplateView, BeforeDispatchMixin): # ... class BeforeDispatchMixin(object): def get_object(self): # ... return object def dispatch(self, request, *args, **kwargs): self.object = self.object() if not object_permission(request.user, self.object): raise PermissionDenied # ??? # here we would want to call the inheriting class' dispatch method As per design doing what I am trying to do is impossible. What's an alternative here?