Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pytz.exceptions.AmbiguousTimeError: 1978-10-01 00:00:00, is there a proper way to hadle this daylight saving time?
i'm having this exception in my Django project, is there a proper way to handle this case? it's all about this specific daylight saving time. -
Django: Logging configuration location
I have on top of my views.py the following line to enable logging: logger = logging.getLogger(__name__) To change the loglevel to debug for all loggers I have put the following lines into the settings.py: if DEBUG: logging.getLogger().setLevel(logging.DEBUG) But still if I log something with loglevel INFO in my views.py it's not getting shown. Why? -
Send a request in url at a specific time in django
I want to ask for url at a certain time regardless of date. first i try like this url(r'^(?P<date>\d{4}-\d{2}-\d{2})/$', views.timer, name='timer'), I have already created the logic in views.py and can only request it. Is it a situation where I have to study more regular expressions? I have not been able to solve it for three hours now. It is so desperate. Please give me a little hint -
DJANGO importing fields to model from another model
I have the following Models and I'm try to get the vector in Especie.zonas to be a field in the model Zona. i.e. Especie.zonas is a vector of Zonas (model Zona) and I want it to have a OneToOne relationship with the model EspecieZona Models.py class Zona(models.Model): codigo = models.CharField(max_length=120) area = models.CharField(max_length=120) especies = models.ManyToManyField("Especie", blank=True) def __str__(self): return self.codigo def get_especies(self): return self.especies.all().values_list('nome', flat=True) class Especie(models.Model): nome = models.CharField(max_length=120) nome_latino = models.CharField(max_length=120) data_insercao = models.DateTimeField(auto_now_add=True) actualizacao = models.DateTimeField(auto_now=True) zonas = models.ManyToManyField("Zona",blank=True ) def get_zonas(self): return self.zonas.all().values_list('codigo', flat=True) def __str__(self): return self.nome class EspecieZona(models.Model): idEspecie = models.OneToOneField("Especie") here_is_my_problem = models.Especie.zonas() idZona = models.OneToOneField("Especie.zonas") fechado = models.BooleanField() def __str__(self): return str(self.idEspecie)+' em '+str(self.idZona) Thanks in advance! -
must be of the form 'app_label.ModelName'." % model ValueError: Invalid model reference
When I python3 manage.py makemigrations, I get bellow error: ... File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related.py", line 348, in contribute_to_class lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related.py", line 85, in lazy_related_operation return apps.lazy_model_operation(partial(function, **kwargs), *model_keys) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related.py", line 83, in <genexpr> model_keys = (make_model_tuple(m) for m in models) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/utils.py", line 23, in make_model_tuple "must be of the form 'app_label.ModelName'." % model ValueError: Invalid model reference '管理员后台.产品配置.qiyun_admin_productconfig_cloudserver.HostType But, my HostType model path is this : 管理员后台.产品配置.qiyun_admin_productconfig_cloudserver.models.HostType. The traceback less the .models in it. I don't know why. My project directory is bellow: Please PAY ATTENTION, the serializer and views(serializer view) is under the api directory. and the settings: INSTALLED_APPS = [ 'django.contrib.admin', .... '旗云管理员后台.用户管理.qiyun_admin_useradminmanage', # '旗云管理员后台.用户管理.qiyun_admin_usergroups', # '旗云管理员后台.产品配置.qiyun_admin_productconfig_common', # '旗云管理员后台.产品配置.qiyun_admin_productconfig_cloudserver', # '旗云管理员后台.财务管理.qiyun_admin_financialmanage_ordermanage', # '旗云管理员后台.财务管理.qiyun_admin_financialmanage_financialmanage', -
django-celery dump celery results to view while its runnig
I have a long running celery task(10 minutes or less) and want to populate each finished result with js. While its running I want to get results when progress is still running like, def myfunc(input): res["a"] = a(input) >> get celery result res["b"] = b(res["a"]["x"]) >> get celery result res["c"] = c(input) >> get celery result res["d"] = d(res["c"]["y"] return res def getceleryresult(taskid): res = here is that i should get the unfinished tasks results return JsonResponse({'res': res}) Is there any workaround? -
Django async send notifications
I have a notifications for a users when the admin add notification to user i want to display on user's home page like a facebook likes or activity feed is it possible with django ? models.py class Notification(BaseModel): created_user = models.ForeignKey(User) title = models.CharField(max_length=225) description = models.TextField(max_length=600) is_read = models.BooleanField(default=False) priority = models.CharField(max_length=20, choices=NOTIFICATION_STATUS, default=LOW) def __str__(self): return self.title i'm able to add a new notificiation but the notifications listing when the user refresh the page. Simply i just want to do this async like facebook like system. -
Django testing: RequestFactory() follow redirect
In Django, I have a view, which will redirect to the register page for certain users and I would like to write a test for this. The standard request.client.get used for testing doesn't allow me to specify a user (it just defaults to anonymous_user?), so I can't test the behaviour. With RequestFactory() I was able to specify request.user. However, it is not following the redirect and the test fails. from .views import my_view from django.test import RequestFactory() def test_mytest(self): user = create_guest_user() self.factory = RequestFactory() request = self.factory.get(reverse('my_view'), follow=True) request.user = user response = my_view(request) self.assertContains(response, "page where redirected should contain this") It fails on the last line with this error message: AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) Any ideas how to do this? -
I can't get ( GDAl or GIS, GEOS, ) to be all compatible and work together in Django framework . any alternative frameworks for geolocation WEB APP
I'm writing small project for the university, where i want to show the people who are moving in a city based in their location. I have some experience with python and therefore the prof ask me to write and create a Web APP with Django and that include API, REST elc... My problem here that I can't get ( GDAl or GIS, GEOS, ) to be all compatible and work together. any alternative frameworks for geolocation WEB APP , or suggestions, I'm using windows 10 and pycharm. (Python,3.6.3 .django 1.11.7). -
Django + Auth0 "a bytes-like object is required, not 'str'" python 3.5.2
I know there has been a bunch of "a bytes-like object is required, not 'str'" question around. but i've tried and tried and no one fixes my issues. it'll be very nice if you can help me out in my particular case. I'm trying to connect django 1.11 with Auth0 and got that error on this code def get_user_details(self, response): # Obtain JWT and the keys to validate the signature idToken = response.get('id_token') jwks = request.urlopen("https://" + self.setting('DOMAIN') + "/.well-known/jwks.json") issuer = "https://" + self.setting('DOMAIN') + "/" audience = self.setting('KEY') #CLIENT_ID payload = jwt.decode(idToken, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer).decode('UTF-8') i have tried to use .encode('utf-8') or the b"str" or the "rb" / "wb" but still no luck. Thanks in advance for your help ---- edit ---- using payload = jwt.decode(idToken, jwks.read().encode('utf-8'), algorithms=['RS256'], audience=audience, issuer=issuer).decode('UTF-8') bring me to other error 'bytes' object has no attribute 'encode' -
how can I specifically run an order on my Django python migration list?
I have a migration list (schema / data) 001 initial 002_XX 003_YY ..... In the list I have a data migration of a model: current_product_type, created = mymodel.objects.get_or_create () then I wanted to delete a field from the model but it will have a problem in data migration level declared before because it will not find a correspondence between the model and the database. how can I then specific an order of execution of my migration list -
Is it a good idea to create custom primary key in django models?
Is it a good idea to define a primary key like this: what are the advantages and disadvantages of the approach. Its showing error "TypeError at /adminusers/userdetail/add/", 'NoneType' object is not iterable. class UserType(models.Model): user_type_id = models.AutoField(primary_key=True, unique=True) user_type_name = models.CharField(max_length=100,null=True, blank=True) user_type_desc = models.CharField(max_length=100,null=True, blank=True) created_date = models.DateTimeField(null=True) created_by = models.CharField(max_length=100,null=True, blank=True) updated_date = models.DateTimeField(null=True) updated_by = models.CharField(max_length=100,null=True, blank=True) def __unicode__(self): return self.user_type_name class UserDetail(models.Model): # user = models.OneToOneField(User, on_delete = models.CASCADE) # user_detail_id = models.AutoField(primary_key=True) # user_type = models.ForeignKey(UserType, to_field="user_type_id") user = models.OneToOneField(User, on_delete=models.CASCADE) #null=True, blank=True) user_role = models.CharField(max_length=100,null=True, blank=True) first_name = models.CharField(max_length=100,null=True, blank=True) last_name = models.CharField(max_length=100,null=True, blank=True) email = models.EmailField(max_length=100,null=True, blank=True) mobile_number = models.CharField(max_length=100,null=True, blank=True) -
Group same QuerySet elements
I have a queryset that looks like this: Order.objects.all() <QuerySet [ <Order: 2017-11-09 Apple 2 >, <Order: 2017-11-09 Banana 1>, <Order: 2017-11-09 Pears 2 >, <Order: 2017-10-01 Berry 2> ]> As you can see there are 3 orders with the same date. How can I group this order by the date, so it will become something like this: Order: 2017-11-09 Apple 2, Banana 1, Pears 2 Oerder: 2017-10-01 Berry 2 -
User Permissions settings in Django?
I have edit form with user_permissions field. In that form I show list of permissions with checkboxes. Questions: 1) My current code right know in form template show me user permissions in next format: auth | user | Can add user. How to show only human readable name of user permission (Can add user)? I was looking for AUTH_PERMISSION table in DB and such human readable name stored in name field. When I tried to use in template {{ user_permission.name }} it show me nothing. How to solve this problem? 2) How to tick user permissions (checkboxes) which user has when open edit form? Is it correct to use ModelMultipleChoiceField with user_permissions field? forms.py: class UserEditForm(UserChangeForm): class Meta: model = User exclude = ('groups',) user_permissions = forms.ModelMultipleChoiceField( Permission.objects.filter(content_type__model__in=['custom_app', 'user']), widget=forms.CheckboxSelectMultiple, ) template: <div class="list-group"> {% for user_permission in user_edit_form.user_permissions %} <li class="list-group-item"> <div class="custom-checkbox"> <label for="{{ user_permission.id_for_label }}"> {{ user_permission.tag }} <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span> <strong>{{ user_permission }}</strong> </label> </div> </li> {% endfor %} </div> -
APScheduler job is not starting as scheduled
I'm trying to schedule a job to start every minute. I have the scheduler defined in a scheduler.py script: from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor executors = { 'default': ThreadPoolExecutor(10), 'processpool': ProcessPoolExecutor(5) } job_defaults = { 'coalesce': False, 'max_instances': 5 } scheduler = BackgroundScheduler(executors=executors,job_defaults=job_defaults) I initialize the schedule in the init.py of the app like this: from scheduler import scheduler scheduler.start() I want to start to schedule a job on a specific action, I do it like that: def AddJob(): dbid = repository.database.GetDbid() job_id = 'CollectData_{0}'.format(dbid) scheduler.scheduled_job(func=TestScheduler(), trigger='interval', minutes=1, id=job_id ) def TestScheduler(): for i in range(0,30): starttime = time() print "test" sleep(1.0 - ((time() - starttime) % 1.0)) First when I'm executing the AddJob() function in the python console it starts to run as expected but not in background, the console is blocked until the TestScheduler function ends after 30 seconds. I was expected it to run in the background because it's a backgroundScheduler. Secondly, the job never start again even when specifiying a reapeat interval of 1 minute. What am I missing? Thanks -
Elegant way of fetching multiple objects in custom order
What's an elegant way for fetching multiple objects in some custom order from a DB in django? For example, suppose you have a few products, each with its name, and you want to fetch three of them to display in a row on your website page, in some fixed custom order. Suppose the names of the products which you want to display are, in order: ["Milk", "Chocolate", "Juice"] One could do unordered_products = Product.objects.filter(name__in=["Milk", "Chocolate", "Juice"]) products = [ unordered_products.filter(name="Milk")[0], unordered_products.filter(name="Chocolate")[0], unordered_products.filter(name="Juice")[0], ] But is there a more elegant way? e.g., convey the desired order to the DB layer somehow, or return the products grouped by their name (aggregation seems to be similar to what I want, but I want the actual objects, not statistics about them). -
Django - get value of readonly field (fix readonly error)
I'm trying to edit fieldset.html template in order to add the hidden input under readonly div (in readonly case). {% if field.is_readonly %} <div class="readonly {% if field.field.name %} field-{{ field.field.name }}{% endif %}">{{ field.contents }}</div> <input id="{% if field.field.name %} id-{{ field.field.name }}{% endif %}" type="hidden" value="{{ field.field.initial }}"/> {% else %} {{ field.field }} {% endif %} My problem is that if I set a field readonly with "get_readonly_fields", I can't submit the form because hidden field is required (I think this is a big error of django that uses div instead of the hidden input). I tried to fix it with the code above but I'am not able to insert the value in to my field, because "field.field.initial" is empty for readonly field. How can I solve it? -
djano url routing for one app
I am trying to return different templates for different urls (having just one app), so basically I want to return: One template for:http://127.0.0.1:8000/projects/ Another template for:http://127.0.0.1:8000/formpage/ I have the project urls.py: `from django.conf.urls import url,include from django.contrib import admin from appone import views urlpatterns = [ url(r'^admin/', admin.site.urls), #home page url(r'^$', views.index, name='index'), url(r'^projects/', include('appone.urls')), url(r'^formpage/', include('appone.urls')), ]` And the app urls.py: `from django.conf.urls import url,include from django.http import HttpResponse from . import views urlpatterns = [ url(r'^$', views.projs, name='proj'), url(r'^$', views.form_view, name='form_view') ]` I have the views and templates , that are good, but I do not understand how can I return them based on the url, because for the moment I return the first view from app urls.py, for both urls. -
Django admin list view show external url data in custom column
we have a list view something like below Now lets say we want to add one more column in the view which doesn't exist in model. so we can do that by creating a method inside admin class. class PageAdmin(admin.ModelAdmin): list_display = ["id", "title", "slug", "author", 'updated', 'custom_field'] def custom_field(self, obj): # logic... return True # or False based on above logic This is simple. Now lets take a more complicated scenario where I need this column to be populated based on the result of goodreads.com search. I mean I'll search objects title on goodreads and find the exact title if found then will return True else False. For e.g there is a page object and title of this is hunger games so when I search this, I'll get https://www.goodreads.com/search?utf8=%E2%9C%93&query=hunger+games I'll parse the result and check if exact title exist in top 10 results. class PageAdmin(admin.ModelAdmin): list_display = ["id", "title", "slug", "author", 'updated', 'custom_field'] def custom_field(self, obj): # search on goodreads.com, parse results and match with obj.title return True # or False based on above logic The problem with this approach is that it makes admin page very slow.. since it will get data for all objects in a page(normally … -
Can anyone recommend an open source platform for workflow management?
I am about to start building a workflow platform for document management. It's a relatively simple concept requiring user accounts, form submission, and form review/approval between users (think analyst->manager->director). Documents are attached to forms, and the forms have pre-configured fields. Is there a solid opensource framework that anyone can recommend that would provide simple building blocks for this approach? I'm thinking like how Bootstrap is a great framework for CSS, is there a platform that handles user accounts and workflow basics well? I was thinking about starting with Django but would also appreciate views on other platforms. -
How to undo serialize list on Django
I serialized a list of Django models like this: serialize_list = serializers.serialize("json", my_list) and now I want to deserialize it and get back a list of Django models. Instead, when I do deserialize_list = serializers.deserialize("json", serialize_list ) I get a list of DeserializedObject models and not the original list. My question is: how can I get the original list back? -
Are Django test fixtures loaded multiple times?
In my tests, I have a Django super class with the sole purpose of setting up data and defining some utility methods used in the tests. It also has the fixtures used in the different TestCase subclasses. class MasterTest(django.test.TestCase): fixtures = ['appname/fixtures/fixture1.json', 'appname/fixtures/fixture2.json'] class TestCase1(MasterTest): pass class TestCase2(MasterTest): pass My questions is whether when running TestCase1, TestCase2 and others, the fixtures defined by MasterTest will be run multiple times (one for each case) or only one, since they are defined in the super class. If they are loaded every single time, is there a way to load fixtures only once? -
Why doesn't None put in variable?
Why doesn't None put in variable? I wrote in code like def check(request): if len(request.POST.get('access_key')) >= 25: return HttpResponse('<h1>Hello</h1>') elif request.POST.get('access_key', None) == None: id_json = {} return JsonResponse(id_json, safe=False) else: return HttpResponse('<h1>Good</h1>') Now I put anything to access_key in POSTMAN like I think in this case the program goes into elif request.POST.get('access_key', None) == None:,but now it goes into else:. I really cannot understand why the null value is not recognized as None. I wrote print(type(request.POST.get('access_key'))) and blank is printed out. I wanna make a system if no value is put, and the program should go into elif request.POST.get('access_key', None) == None:. How should I fix this? -
create custom model field in django
I want to create custom model field that accepts strings in special format then convert and store it as integer and restore and convert it to the previous format , also need to change it's form field to render as a Char Field , what should I do?! I've done it but it doesn't work correctly class JalaliEpochTimeField(models.BigIntegerField): description = "A field to save strings in Jalali date format as epoch (big int) in db" def from_db_value(self, value, expression, connection, context): if value is None: return value return epoch_to_khayyam(value) def to_python(self, value): print("to_python") if isinstance(value, JalaliEpochTimeField): return value if value is None: return value return khayyam_str_to_epoch(value) -
Error while running two django apps on different ports of a server
I'm trying to run two django apps on different ports of a server using Apache and WSGI. Here is my VehicleDataEntry.conf (listening to port 80) file: <VirtualHost *:80> ServerAdmin webmaster@example.com ServerName 104.218.50.242 DocumentRoot /website_data/sites/VehicleDataEntry/static/ WSGIScriptAlias / /website_data/django/VehicleDataEntry/VehicleDataEntry/wsgi.py Alias /static/ /website_data/sites/VehicleDataEntry/static/ </VirtualHost> WSGIPythonPath /website_data/django/VehicleDataEntry/ <Directory "/website_data/sites/VehicleDataEntry/static"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory "/website_data/django/VehicleDataEntry/VehicleDataEntry"> <Files wsgi.py> Require all granted </Files> </Directory> QuotationMaker.conf (listening on port 8080): <VirtualHost *:8080> ServerAdmin webmaster@example.com ServerName 104.218.50.242 DocumentRoot /website_data/sites/QuotationMaker/static/ WSGIScriptAlias / /website_data/django/QuotationMaker/QuotationMaker/wsgi.py Alias /static/ /website_data/sites/QuotationMaker/static/ </VirtualHost> WSGIPythonPath /website_data/django/QuotationMaker/ <Directory "/website_data/sites/QuotationMaker/static"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory "/website_data/django/QuotationMaker/QuotationMaker"> <Files wsgi.py> Require all granted </Files> </Directory> Now the VehicleDataEntry's wsgi.py file: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ["DJANGO_SETTINGS_MODULE"] = "VehicleDataEntry.settings" application = get_wsgi_application() application = DjangoWhiteNoise(application) QuotationMaker's wsgi.py file: VehicleDataEntry's wsgi.py file: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ["DJANGO_SETTINGS_MODULE"] = "VehicleDataEntry.settings" application = get_wsgi_application() application = DjangoWhiteNoise(application) The Problem: VehicleDataEntry app is running without any problem, however, when I try to access QuotationMaker on port 8080, it returns 500 Internal Server Error. When I checked the httpd/logs/error_log, I get the following error: ImportError: No module named QuotationMaker.settings I know there is something wrong …