Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how get the content of BrowsableAPIView in django channels (or ajax)
I use Django Channels to retrieve the data from Django Restful (DRF) serializer (I use channels because database is large and if I call for the data directly it results in a server timeout). What I struggle with (perhaps I don't understand something about how DRF works), is how to get the html representation of Browsable API. So basically what I need to do is to send back as html a response based on BrowsableAPIRenderer when a person connects via WebSocket: def connect(self, message, **kwargs): myobj = MyObj.objects.filter(code=self.obj_code) serializer = MyObjSerializer(myobj, many=True) self.send(Response(serializer.data)) But that results in an error Response is not JSON serializable. -
Memory issue with django-imagekit
I am working on a news aggregator and use django-imagekit to create news article thumbnails. The application is hosted on Heroku. Over time, I noticed the application consumes more and more memory. Currently, there are about 8000 images in the database and the application consumes about 3 times more memory in comparison to a staging application which has about 100 images in the database. I believe the problem has to do with django-imagekit. If I call the original images in the templates, instead of images processed by django-imagekit, the memory drops down to a normal level. The models: class Article(models.Model): title = models.CharField(max_length=255) … photo = models.ForeignKey(Photo, blank=True, null=True, related_name='+', on_delete=models.SET_NULL) … class Photo(models.Model): name = models.TextField() … photo = models.ImageField(upload_to='user/photos/%Y/%m/%d', max_length=255) … thumb = ImageSpecField(source='photo', processors=[resize.ResizeToFit(131, 131),], options={'quality': 90}) thumbnail_image = ImageSpecField(source='photo', processors=[resize.ResizeToFill(100, 100),], options={'quality': 90}) news_small = ImageSpecField(source='photo', processors=[resize.ResizeToFill(125, 94),], format='JPEG', options={'quality': 90}) … Template example: <a href="{{ item.get_absolute_url }}"><img src="{{ item.photo.news_small.url }}" alt=""></a> Settings.py redis_url = urlparse(os.environ.get('REDIS_URL')) CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'DB': 0, 'PARSER_CLASS': 'redis.connection.HiredisParser', 'PASSWORD': redis_url.password } } } On the homepage, about 25 thumbnails are shown. But the memory jumps also on a page where … -
Django 2 TestCase assertQuerysetEqual
Maybe I am misunderstanding the implementation of the assertQuerysetEqual, but I am trying to build a test that would verify that my model meta ordering is working as expected. Of all the info I found, I think this is what I should do: models.py class Name(models.Model): first_name = models.CharField( "First Name", max_length=100, ) middle_name = models.CharField( "Middle Name or Initial", max_length=100, default='', ) last_name = models.CharField( "Last Name", max_length=200, ) class Meta: ordering = ['last_name', 'first_name', 'middle_name'] tests.py from django.test import TestCase from .models import Name class NameModelTest(TestCase): @classmethod def setupUpTestData(cls): # test_name_1 Name.objects.create( first_name='Anny', middle_name='Ann', last_name='Anvil', ) # test_name_2 Name.objects.create( first_name='Anny', middle_name='B', last_name='Anvil', ) # test_name_3 Name.objects.create( first_name='Banny', last_name='Anvil', ) # test_name_4 Name.objects.create( first_name='Banny', last_name='Banvil', ) def test_meta_ordering_last_first_middle(self): test_name_1 = Name.objects.get(pk=1) test_name_2 = Name.objects.get(pk=2) test_name_3 = Name.objects.get(pk=3) test_name_4 = Name.objects.get(pk=4) expected_qs = list(test_name_1, test_name_2, test_name_3, test_name_4 ) test_qs = Name.objects.all() self.assertQuerysetEqual(test_qs, expected_qs) -
Django: serve admin statuc files with whitenoise and site's files from S3
I have a working Django site where I've been using whitenoise to serve static files. I've then switched to S3 storage for both site static and media. And it works really well. I have one problem with this setup though: collecting the admin static files (select2, tinyMCE, etc) takes lots of times and regularly fails in Heroku. So here's my ideal scenario: - keep everything as is BUT - DO NOT upload the admin static files to S3 (during collectsatic) and serve them from the app server using whitenoise Here's the relevant excerpt from my settings file ENVIRONMENT = os.environ.get('DJANGO_ENVIRONMENT', 'dev') IS_PROD = ENVIRONMENT == 'production' IS_DEV = not IS_PROD BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = bool(os.environ.get('DJANGO_DEBUG', IS_DEV)) # Static files (CSS, JavaScript, Images) and media STATIC_URL = '/static/' STATIC_ROOT = '.static' if IS_PROD: AWS_STORAGE_BUCKET_NAME = os.environ.get('S3_BUCKET', '') AWS_S3_REGION_NAME = os.environ.get('S3_REGION', '') AWS_ACCESS_KEY_ID = os.environ.get('S3_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.environ.get('S3_SECRET', '') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'Expires': 'Thu, 31 Dec 2100 20:00:00 GMT', 'CacheControl': 'max-age=94608000', } STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/' TINYMCE_JS_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/tiny_mce/tiny_mce.js' else: MEDIA_URL = '/media/' MEDIA_ROOT = '.media' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] -
Troubles with running django app via wsgi on ubuntu 17
I need your help. I have an error when trying to run on wsgi my django project. I'm using Ubuntu 17, Apache2, Django 2.0, Python 3.6 When I running from manage.py, everything is working, but when via wsgi got the next error : AH01276: Cannot serve directory /var/cardsite/cardsite/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive And don't know why, because I guess set everything correct. Bellow my configuration : apache.conf <VirtualHost *:80> CustomLog /var/log/apache2/cardsite-access.log common ErrorLog /var/log/apache2/cardsite-error.log DocumentRoot /var/cardsite/cardsite/ Alias /static /var/cardsite/cardsite/static/ <Directory /var/cardsite/cardsite/static> Require all granted </Directory> <Directory /var/cardsite/cardsite> <Files wsgi.py> Require all granted </Files> </Directory> RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] WSGIDaemonProcess cardsite python-path=/var/cardsite/ python-home=/var/venv_python36/ WSGIProcessGroup cardsite WSGIScriptAlias / /var/cardsite/cardsite/wsgi.py </VirtualHost> wsgi.py import os import sys PROJECT_DIR = '/var/cardsite' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cardsite.settings") def execfile(filename): globals = dict( __file__ = filename ) exec( open(filename).read(), globals ) activate_this = os.path.join( '/var/venv_python36/bin', 'activate_this.py' ) execfile( activate_this ) from django.core.wsgi import get_wsgi_application application = get_wsgi_application() P.S. Permissions I have give on folder and all which inside. P.S.S. Packages like "libapache2-mod-wsgi-py3" or "mod-wsgi" via pip3 also installed. Thank you all for the any suggestion what's it can be -
Docker - psql: django.db.utils.OperationalError: FATAL: role "admin" does not exist
I've configured docker and postgres for my Django project. When I do python manage.py runserver 0:8000, it gives me this error: django.db.utils.OperationalError: FATAL: role "admin" does not exist However, I've been used the same configs with my previous projects and everything seems fine in those. Here is my docker-compose.yml file version: '3' services: db: image: postgres environment: - POSTGRES_DB=myproject - POSTGRES_USER=admin - POSTGRES_PASSWORD=admin_pass container_name: myproject_postgress volumes: - ./data/db:/var/lib/postgresql/data myproject: build: ./myproject container_name: myproject env_file: - .env command: "tail -f /dev/null" volumes: - ./myproject:/web ports: - "8000:8000" depends_on: - db links: - db:postgres environment: - DJANGO_SETTINGS_MODULE=myproject.settings.local And here is my Database section in my settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'admin', 'PASSWORD': 'admin_pass', 'HOST': 'postgres', 'PORT': '', } } These are the SAME with the ones in the docker-compose.yml When I connect my database from command line, I can see that there is user 'admin'. (locally of course) Without docker, it wont give any error. So what I am doing wrong with the docker? PS: In my previous projects, I passed the env file to the docker using env_file instead of using environment section in the docker-compose.yml I did try that too, but its not … -
get all objects containing a specific key django
I have a model called deployed contracts model which looks like following from django.db import models class DeployedContracts(models.Model): house_no = models.CharField(max_length=200, blank=False, default='') rent = models.IntegerField(blank=False) security_deposit = models.IntegerField(default=0, blank=False) house_owner = models.CharField(max_length=100, blank=False, default='') house_tenant = models.CharField(max_length=100, blank=False, default='') deployed_contract_address = models.CharField(max_length=100, blank='', default='') def save(self, *args, **kwargs): super(DeployedContracts, self).save(*args, **kwargs) where house_owner and house_tenant contains the email of house owner and house tenant and it's serializer looks like following from rest_framework import serializers from deployedcontracts.models import DeployedContracts class DeployedContractsSerializer(serializers.ModelSerializer): class Meta: model = DeployedContracts fields = ('house_no', 'rent', 'security_deposit', 'house_owner', 'house_tenant', 'deployed_contract_address') i want to write an API view which a contains a get method which takes an email as parameter and returns all the objects of DeployedContract where either house_owner or house_tenant's email is equal to the email provided in parameter. How can i do that in django? -
Integrity Error after submission of Registration using Django 2.0
I keep on getting an Integrity Error (FOREIGN KEY constrain failed) after registration.. Please i really need an urgent solution to this error.. Thanks in advance from django.db import models from .user import User from django.core.validators import RegexValidator from django.db.models.signals import post_save from django.dispatch import receiver class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(upload_to='media/pictures/', blank=True) regex = RegexValidator(r'^\d{2}/\d{4}', message='Required. 7 characters or fewer. This value must contain only numeric and slash.') matric_no = models.CharField(validators=[regex], blank=False, max_length=7, unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list address = models.CharField(max_length=150, blank=True) birth_date = models.DateField(null=True, blank=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=False, default='M',) forms.py class StudentProfileForm(forms.ModelForm): avatar = forms.ImageField() class Meta: model = Student fields = ('avatar', 'phone_number', 'address', 'gender', 'matric_no') views.py class StudentRegistrationView(CreateView): model = Student form_class = StudentProfileForm template_name = 'registration.html' def student_registration(request): if request.method == "POST": form = StudentProfileForm(request.POST, request.FILES) if form.is_valid(): register = form.save(False) register.save() return redirect('home') else: form = StudentProfileForm() return render(request, 'accounts/registration.html', {'form': form}) What i think the problem might probably be is matric_no field or what did … -
Asynchronous task Django
I am writing a django app with machine learning. In the views file i have a index function that executes rendering functionality. def index(request): return render(request, 'posts/index.html' , { 'title':'Latest Posts' }) I also have my machine learning algorithm function(it is lots of code but it works) def cnn(prediction): # Initialising the CNN classifier = Sequential() # Step 1 - Convolution classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) # Step 2 - Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer classifier.add(Conv2D(32, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full connection classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 1, activation = 'sigmoid')) # Compiling the CNN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Part 2 - Fitting the CNN to the images from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory(r'C:\Users\kkals\Desktop\Programms\django-python\mysite\posts\dataset\training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory(r'C:\Users\kkals\Desktop\Programms\django-python\mysite\posts\dataset\test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') classifier.fit_generator(training_set, steps_per_epoch = 8000/32, epochs = 20, … -
Many to Many model with a dropdown in Django Rest Framework?
I am trying to create a Many to Many relation with a model in between, I have a Client model, and a Zone model, each client may have access to different zones, and each zone may have multiple clients. Therefore I created a model called Access Permission, that stores said relation, and I want to show a dropdown selector in the post form that shows the existing clients and zones, or to ask for the Id of an existing object, instead of showing the form to create new ones. These are my models: class Zone(models.Model): name = models.TextField() created = models.DateTimeField(auto_now=True) def __str__(self): return '%s' % (self.name) class Client(models.Model): name = models.TextField() birthDate = models.DateField() created = models.DateTimeField(auto_now=True) def __str__(self): return '%s' % (self.name) class AccessPermission(models.Model): idClient = models.ForeignKey(Client, on_delete=models.CASCADE, null=False) idZone = models.ForeignKey(Zone, on_delete=models.CASCADE, null=False) And these my current serializers: class ZoneSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Zone fields = ('name',) class ClientSerializer(serializers.HyperlinkedModelSerializer): zones = ZonesSerializer(source='accesspermission_set', many=True, read_only=True) class Meta: model = Client fields = ('name', 'birthDate', 'zones') class AccessPermissionSerializer(serializers.ManyRelatedField): idClient = ClientSerializer(many=False) idZone = ZoneSerializer(many=False) class Meta: model = AccessPermission fields = ('idClient', 'idZone') Is there any way to ask for the Id of an existing object, or show … -
Django Form object, change HTML attribute outside python code/models
I'm looking to understand a way to change attribute of my html code generate by the django's template system, especially for Form html code. So I found some stuff to change class from some models like that class AuthorForm(ModelForm): class Meta: model = Author fields = ('name', 'title', 'birth_date') widgets = { 'name': Textarea(attrs={'cols': 80, 'rows': 20}), } coming from here. It's fine and it could works. But actually django, if I understand almost well, use a templates system which can be read by someone else, a front-end developper for a simple example. Now, Boostrap come whith the need to manipulate class attribute to work on the style. When we work on a loop, it's not a problem, but when whe generate the HTML code from a class who inerhit Form and just display it in a template, it will be be quickly harder for someone else to manipulate html balise. For sure they can do that with javascript, it's the solution that I've in mind, but it seem not really nice. There is an alternativ way to do that ? Thanks for suggestion, I hope I was relatively clear. -
How to select parents with specific set of children (many-to-one) django?
In a many-to-one relationship in django such as the following: class Parent(model.Model): name = models.CharField(max_length=50) class Child(model.Model): parent = models.ForeignKey(Parent) name = models.CharField(max_length=50) hobby = models.CharField(max_length=50) age = models.IntegerField(default=0) If I have N different criteria of children records, for example let N=2 and criteria be: Child__name='Bob' Child__hobby='Skiing' Child__age__gt=16 Child__name='Billy' Child__hobby__icontains='read' Child__age__gte='21' How can I filter out Parents if they don't have at least one child meeting each of the criteria described above? I am preferably looking to write this in a way such that I can apply one filter at a time so I can optionally check what criteria were not met by which parents. -
Group List of Dics by one key of Dict
So, I'm working with Django (python) and I want to manipulate a data structure in the serializer. I have this: "week_task_schedule": [ { "id": 3, "week_number": 2, "task": 1 }, { "id": 2, "week_number": 1, "task": 2 }, { "id": 1, "week_number": 1, "task": 1 } ] I I want to get this: "weeks": [ { "week_number": 1, "tasks": [ { "id": 2, "task": 2 }, { "id": 1, "task": 1 } ] }, { "week_number": 2, "tasks": [ { "id": 3, "task": 1 } ] } ] What should be my approach to this problem? -
Django redirect() with additional parameters
Why is it that when I try to pass additional parameters, I get the error: The below works fine! (Without parameters) def first(request): return redirect(request, 'confirm') def confirm(request): return render(request, 'template.html') However this is what I need, which doesn't work as expected, and I get the error: Don't mix *args and **kwargs in call to reverse()! def first(request): return redirect(request, 'confirm', email='some_email') def confirm(request, email): return render(request, 'template.html', { 'email': email} ) -
Django-star-ratings: Calculating average ratings from different model
I've got two models: class Series(models.Model): name = models.CharField(max_length=140) slug = models.SlugField(max_length=140, unique=True) class Issue(models.Model): title = models.CharField(max_length=140, blank=True) series = models.ForeignKey(Series, on_delete=models.CASCADE) I'm using django-star-ratings to allow the user to rate the individual issues. I'd like to get an average rating for the series based on the issues that have been rated, but haven't been able to come up with a decent solution after reading the documentation. Any help or suggestions would be greatly appreciated! -
Display thumbnail in form or formset
What's the easiest way to display the image that has been uploaded to the form in addition to or rather than just the filepath of the image within a form or formset. Really struggling with this one. Thanks! -
Use ugettext and ugettext_lazy in the same file in Django project
I'm working on translating a Django project. Nearly everything works fine. I just can't get django to collect strings marked with something else than _ (underscore). Let me explain a bit more : so as the doc stipulates, I'm using ugettext and ugettext_lazy. I think I've understood well enough why and where I should use ugettext_lazy but in some models I can use ugettext at one place and ugettext_lazy at another place (e.g. because the first is in a function requested only when a user makes a request and the second is part of the model definition (e.g. a field name) ). So I'm doing it like this from django.utils.translations import ugettext as _ from django.utils.translations import ugettext_lazy as _l class MyModel(): myfield = CharField(..., verbose_name=_l("My Field"), ...) # Here it is needed to use the lazy version def edit_my_model(): msg = _('You are going to edit this model') # For performance, I prefer to use the non-lazy version when I can .... Everything works fine as long as I have my .po files with all the translations. But my problem is to have those translations in the .po files. Indeed when I run django-admin makemessages to collect all marked … -
Python ebay sdk - how to add item specifics dynamically?
I am using ebay-python-sdk I created the myitem object, so I can api.execute('VerifyAddItem', myitem) it. But I need to add ItemSpecifics, and here I encounter problems. I have an array of item specifics made of tuples: a = [('Occasion', 'Casual'), ('Brand', 'Ralph Lauren'), ('Style', 'Polo Shirt')] and i want to add it to 'myitem'. so i use: for p in a: ar.append([{"Name":p[0]}, {"Value":p[1]}]) myitem["Item"]["ItemSpecifics"]["NameValueList"] = ar but i get error 'KeyError: 'ItemSpecifics'' What do I need to change in my code to add it correctly? If I write this code to myitem object, it is ok. I just don't know how to add it dynamically. "ItemSpecifics": { "NameValueList": [ {"Name": "Occasion", "Value": "Casual"}, {"Name": "Brand", "Value": "Ralph Lauren"}, {"Name": "Style", "Value": "Polo Shirt"}, {"Name": "Sleeve Style", "Value": "Short Sleeve"} ] }, Can you point me to the right direction? Thanks in advance. -
Problems trying to display JSON data in a django-tables2 table
I have django-tables2 set up and working well. I have set my table to be able to update checkbox columns directly from the displayed list. However when my displayed table paginates and I update a value it refreshes the entire page thus sending me back to the first page and I then have to click 'next' to get back to where I was. So I thought it might be a good idea to throw knockout.js into the mix to bind my individual columns to the corresponding data in my postgres database. According to the blurb this would allow me to simply refresh the item clicked on without having to refresh the entire page. I read the tutorial for knockout.js and all seems great and exactly what I am looking for. I've modified my views and written my js file etc and I am almost there. I have the JSONResponse from my views.py returning the correct number of rows, however, my django-tables2 tables are rendering each record as a header (ie th) in my table instead of the data as a row (ie td). Feeling like I've fallen at the last hurdle, I was wondering if anyone can shed any light … -
Django viewset has not attribute 'get_extra_actions'
I am working with Django for a first time and I'm trying to build an API and I am following some tutorials and examples and it works right, but I am running the project now in a Raspberry Pi after install all the requirements and the project is failing with the following error: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0xb547adb0> Traceback (most recent call last): File "/home/pi/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/pi/.local/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/pi/.local/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/pi/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/pi/.local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/pi/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pi/.local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/pi/.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in … -
Django: Error while importing a model in custom services file
celery.py import os from celery import Celery from django.conf import settings from twitterdata.services import TwitterService os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TwitterApiProxy.settings') app = Celery('TwitterApiProxy') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): print("calling load_tweets task") sender.add_periodic_task(10.0, TwitterService.load_tweets.s(), name='add every 10') Tweet.py model from django.db import models class Tweet(models.Model): id = models.BigIntegerField title = models.CharField image = models.CharField url = models.CharField @classmethod def create(cls, tweet_id, dictionary): print(dictionary) tweet = cls(id=tweet_id, title=dictionary['title'], image=dictionary['image'], url=dictionary['url']) return tweet services.py import twitter import requests from celery import shared_task from twitterdata.models import Tweet class TwitterService: @staticmethod @shared_task def load_tweets(): print("Loading Tweets") error Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, … -
Django - signals for two differents type of user
I have customuser model with two boolean type of user: class User(AbstractUser): """User model.""" username = None email = models.EmailField(unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$') phone = models.CharField(validators=[phone_regex], max_length=17) is_trainer = models.BooleanField(default=False) is_client = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] objects = UserManager( And also two differents models with OneToOneField. The fields of any modells is not similar. Trainers models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') ... *and more then 20 another fields* ... Client model: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='client') .... .... I want when new user is sign up, depending on which profile he chose (trainer ore client) in SignUpForm an appropriate model was created. For that I maked signal @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: if sender.is_trainer: profile = Profile.objects.create(user=instance) else: profile = Client.objects.create(user=instance) instance.profile.save() But always created User + Trainers. How can I fixed it? -
Process Django JSONField as YAML
In Django currently Postgres JSONField model field is shown as plain JSON text in CharField form field. I'd like to present data in CharField as YAML text (while keeping it in JSON format internally) and while saving convert it back to JSON like: yaml.dump(json.loads(value)) How to accomplish that? Thanks. -
Django: Wrong HTML output of template
In my base.html template I have this code snippet: <div class="content"> {% include "messages_snippet.html" %} {% block content %}{% endblock %} </div> And my "message_snippet.html" contains: {% if messages %} {% for message in messages %} <div class="alert {{ message.tags }}" role="alert"> {{ message|safe }} </div> {% endfor %} {% endif %} And finally in my login.html: {% extends "base.html" %} {% block title %}Login{% endblock %} {% block content %} <p>In case you do not have an account yet please <a href="{% url 'account:register' %}">register</a>.</p> {% if form.errors %} ... My problem now is that when I go to my login page I get this output: <div class="content"> <p>In case you do not have an account yet please <a href="/account/register/">register</a>.</p> <div class="alert alert-info" role="alert"> Message </div> <form method="post"> ... Note here that the message is AFTER the "In case you do not have ..." paragraph. I do not understand why because the order in my base.html is different. What's wrong here? -
Django comments, how to add?
I have a Post model : class Post(models.Model): STATUS_CHOICES = ( ("draft", "Draft"), ("published", "Published"), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date="publish") author = models.ForeignKey(User, related_name="blog_posts", on_delete=models.CASCADE) tag = models.ManyToManyField(Tag, related_name="blog_tag", blank=True) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="draft") image = models.ImageField(upload_to="blog/%Y/%m/%d", blank=True) class Meta: ordering = ("-publish",) def __str__(self): return self.title def get_absolute_url(self): return reverse("blog:post_detail", args=[self.publish.year, self.publish.strftime("%m"), self.publish.strftime("%d"), self.slug]) And I want let user add comments , how can I do this? Do I have to use django-comments-xtd from github, or better to write app by myself ? I need some example of what i have to do.