Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Doesn't Serialize id of the model
I have a simple class : class Item(models.Model): name = models.CharField(max_length=250) I need to serialize it to JSON with the ID as part of the JSON, but the ID never gets serialized when called in the view: items_json = serializers.serialize('json', item_list) The item_list json as received by the browser contains only name, not the ID. I need the ID for the processing on the client side which returns to the server later. 1) I'd like to avoid creating another ID if possible 2) I haven't created a Serializer Class. I am not sure where and how to do that. -
Django - updating application after adding rows to database?
I have a Django web application which is synced to a PostgreSQL database. After adding some rows to a couple of tables (using pgAdmin, not the Django application itself) i started experiencing some problems with the application. For example, i would get the following error in some tables: Duplicate key value violates unique constraint "some_key_pkey" DETAIL: Key (id)=736284 already exists. My assumption is that i had to let the Django application know somehow that i have added new rows to the database. Could that really be the case? If so, how can i solve it? -
Django-Postgres: how to group by DATE a datetime field with timezone enabled
I am having this problem with prostgresql and django: I have a lot of events that were created on a certain date at a certain time which is stored in a datetime field created . I want to have aggregations based on the date part of the created field. The simplest examples is: how many event are in each day of this month?. The created field is timezone aware. So the result should change depending on the timezone the user is in. For example if you created 2 events at 23:30 UTC time on 2017-10-02 if you view them from UTC-1 you should see them on 3rd of October at 00:30 and the totals should add for the 3rd. I am struggling to find a solution to this problem that works with a lot of data. So doing for each day and SQL statement is not an option. I want something that translates into: SELECT count(*) from table GROUP BY date Now I found a solution for the first part of the problem: from django.db import connection truncate_date = connection.ops.date_trunc_sql('day', 'created') queryset = queryset.extra({'day': truncate_date}) total_list = list(queryset.values('day').annotate(amount=Count('id')).order_by('day')) Is there a way to add to this the timezone that should … -
Cant' serv static css file with Django, Heroku and whiteNoice
I'm trying to serv static files with Django and Heroku. Right now there is only a single .css file. I followed the Heroku example settings, but it doesn't work. I'm in production, so DEBUG is set to False and I'm trying to use whitenoise. If I comment out this line in my settings.py (please find the whole thing below): STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' The page is loaded bug no css is loaded. If it's not commented out I get a 500 error : raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'styles.css' Statics are in a folder named static in the same folder as settings.py index.html {% load staticfiles %} ... <link rel="stylesheet" href="{% static 'styles.css' %}"> settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') SECRET_KEY = 'my_secret' SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True DEBUG = False ALLOWED_HOSTS = ['myapp.herokuapp.com'] INSTALLED_APPS = [ 'my_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
How do I manually assign values to a Django Serializers fields?
I am writing a Django REST API server that will return token/credentials information from Yelp. I have URL mapped this to an endpoint for testing purposes but I don't know how to fill my serializer's fields with the information returned from the call to Yelp. When I connect to the endpoint I get the response below - there is no information... I assume this is because I need to set the values in the serializer's fields. { "client_id": "", "client_secret": "", "token_path": "", "grant_type": "", "token_type": "", "expires_in": null, "access_token": "" } My view is... from rest_framework import generics from .serializers import YelpAuthenticationSerializer from .models import YelpAuthentication # Create your views here. class AuthView(generics.ListCreateAPIView): queryset = YelpAuthentication.objects.all() serializer_class = YelpAuthenticationSerializer def perform_create(self,serializer): pass And the YelpAuthentication class is #yelp.com/developers/documentation/v3/authentication class YelpAuthentication(models.Model): #fields necessary to authenticate url = models.CharField(max_length=200, blank=False, default='https://api.yelp.com/oauth2/token') api_host = models.CharField(max_length=100, blank=False, default='https://api.yelp.com') token_path = models.CharField(max_length=100, blank=False, default='/oauth2/token') grant_type = models.CharField(max_length=200, blank=False, default='client_credential') client_id = models.CharField(max_length=200, blank=True,default='N/A') client_secret = models.CharField(max_length=300, blank=True, default='N/A') #respone body elements after authentication access_token = models.CharField(max_length=200, blank=False, default='N/A') token_type = models.CharField(max_length=7, blank=False, default='bearer') expires_in = models.BigIntegerField() def authenticate(self): #some code that works ... return token What I would like to do is...when my Serializer … -
Testing applications with dotted path name in django
All custom apps in my django project are in apps folder and I want to run tests on all the apps folder. myproject apps/ app1/ apps2/ custom_app/ settings/ manage.py When I run python manage.py test --settings=myproject.settings.test it only runs the tests in custom_app. Here is my base_settings.py INSTALLED_APPS = [ ** list of all the django default apps ** ] USER_APPS = [ 'cutoms_app', 'apps.app1', 'apps.app2'] INSTALLED_APPS = INSTALLED_APPS + USER_APPS Any help is much appreciated. Thanks -
Django - custom file uploads based on criteria
I am currently struggling to find the best way to approach the following problem: I have user registration implemented using django-registration and I want each user to be able to upload different set of documents. Each user will have an "agency", that require some extra documents, however those documents might be different. So my User base class will have a one-to-one relation with all those base documents required for each user, however I am not sure how to let each agency define their own set of documents and how to tie it to the User. Thanks. -
How to use google fusion tables as my Django project database?
Ive just started using google fusion tables to handle our data. And I'm just wondering if it's possible to use web database (google fusion tables here, ofcourse) as my Django project backend. And if so, what's the script to configure DATABASE on settings.py ? Your help greatly appreciated. -
Passing multiple parameters to Django URL - unexpected keyword argument
I wanted to document this question as much as possible in order to be able to detail the origin of the problem. I have the following model named LodgingOffer, to create a lodging offer and detail their information class LodgingOffer(models.Model): # Foreign Key to my User model created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ad_title = models.CharField(null=False, blank=False, max_length=255, verbose_name='Título de la oferta') slug = models.SlugField(max_length=100, blank=True) # ... Another fields ... def __str__(self): return "%s" % self.ad_title def get_absolute_url(self): return reverse('host:detail', kwargs = {'slug' : self.slug }) # I assign slug to offer based in ad_title field,checking if slug exist def create_slug(instance, new_slug=None): slug = slugify(instance.ad_title) if new_slug is not None: slug = new_slug qs = LodgingOffer.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug # Brefore to save, assign slug to offer created above. def pre_save_article_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_article_receiver, sender=LodgingOffer) For this model, I have a DetailView named HostingOfferDetailView . An important objective I want to pursue and for which I ask this question is that in the detail view of an LodgingOffer object, I should be able to contact the owner of that offer (object … -
Django order approval flow
Hello guys i'm new to django,i have tried a lot but didn't get any solution.My task is 'order approval form' .There are 'N' no.of users and user has to fill form with requirements,after filling and submitting its that form data/notification should sent to manager/admin,he can check/delete /approve,if he approves it should go to next state/stage of flow how to do this workflow ? -
Django shell plus invalid arguments in virtualenv
I created a virtualenv to set up for Django upgrade to version 1.8. but when trying to run shell plus I am getting an error about invalid arguments: py manage.py shell_plus Trace: Traceback (most recent call last): File "manage_sched_dev.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 382, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') File "c:\python27\Lib\optparse.py", line 1018, in add_option raise TypeError, "invalid arguments" TypeError: invalid arguments I have no clue why this is happening. I tried installing ipython in the virtualenv because I know shell plus uses ipython, but that didn't seem to help. -
Application not able to access the profile pic and posts using DjangoAllAuth
I am trying to access the profile picture and posts of the user using Django-AllAuth. Here is the template where I am trying to load the profile image: <html> <body> Welcome back {{ user.first_name }} {{ user.age }} <img src={{user.cover.source}} height="60" width="60"> <a href="/">Home</a> </body> </html> Here is the view.py def fb_personality_traits(request): # logger.debug('FB Page Loaded') return render(request, 'home/facebook_personality_traits.html') Settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = '/facebook_personality_traits/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'public_profile', 'user_photos'], # 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'cover', 'posts', 'age', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } ACCOUNT_LOGOUT_ON_GET = True Here I am not getting the image. See the below result: What I want to achieve? 1) I want to display the profile image on the screen. 2) I want to get the posts of the user loggedin in the view.py and send it on the screen to display on the template. -
Django-storages save images webp as octet-stream
when I try to save pillow images using django-storages to store in S3, webp images save them as octet-stream. You should also save images in JPG. I leave below my configuration of django-storages AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'public, max-age=2592000', } AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='WEBP', optimize=False, ) So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='JPEG', optimize=False, ) Thanks! -
Django different types of user
I want to build a simple website with Django, and so far I have made a sign-up form that everyone can sign up and publish some announcement. For next stage I want to make the user can only view the announcement by default, I also want to have another type of user can view and create an announcement. How should I build my user model and sign up forms? Should I use things like permission or AbstractUser? the current sign up forms.py I am using is like from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model class UserCreateForm(UserCreationForm): class Meta: fields = ("username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" and the views about the announcement is like #show all announcement class AnnouncementListView(ListView): ... #show a specific announcement class PostDetailView(DetailView): ... #create a announcement class CreatePostView(LoginRequiredMixin,CreateView): ... Thanks! -
How to redirect when loading a FormView?
Using the class based view FormView I want to redirect to a different page if a user is already activated. So I've tried overriding the get_form_kwargs function: class UserActivateView(AnonymousRequiredMixin, FormView): ... def get_form_kwargs(self): .... if profile.activated: # User is already activated an can log in messages.info( self.request, 'You are already activated. ' 'Login or click forgot password if you have forgotten' ) redirect(to=reverse_lazy('auth_login')) .... return kwargs Using this method the message is added but the redirect is never done. Am I doing this redirect at the correct place, I've been using ccbv as a reference -
Django migration issue: dynamic_forms missing migration as a dependency
One of my migrations specify a particular dynamic_forms migration as a dependency: dependencies = [ ('dynamic_forms', '0004_auto_20170110_1645'), # other deps ] But that file doesn't exist in the migrations directory under the lib's instalation path. The migrations for the version of dynamic_forms I am using, 0.3.3, are: 0001_initial 0002_auto_20140124_1844 0003_auto_20140916_1433 Since the dependency migration doesn't exist, when running migrate, showmigrations, or any other migration-related task, I am logically getting the following error: django.db.migrations.graph.NodeNotFoundError: Migration some_app.0001_initial dependencies reference nonexistent parent node (u'dynamic_forms', u'0004_auto_20170110_164 5') I tried updating the package to its most recent version, 0.5.3, but it didn't help either because it doesn't have that migration file. I tried faking the migrations for dynamic_forms just to see if it helped somehow: py manage.py migrate dynamic_forms --fake But it didn't even go through because the same missing dependency error occurred. I am not sure how to deal with this and although about I did find some information about missing migrations in the dynamic_forms package I couldn't learn how to solve the issue. -
django-import-export : getting post_export to update models
Please how do i updated exported Company model below using post_export signal. I don't want to export items not exported before. So the best thing is using signals. However, if i print the model in the signal at the end of the code below, I get a type class e.g <class 'app.models.Company'> I know am doing something wrong by saving a model but can't find my way arround. Maybe I'm not understanding the documentation of django-import-export library which is found here. #models.py class Company(models.Model): class Meta: verbose_name_plural = "Companies" company_name = models.CharField(max_length=254, blank=True) website = models.URLField(max_length=254, unique=True) address = models.CharField(max_length=254, blank=True, null=True) imported = models.BooleanField(default=False) exported = models.BooleanField(default=False) user = models.ForeignKey(User) def __str__(self): if self.company_name: return self.company_name return self.domain #admin.py from django.dispatch import receiver from import_export.signals import post_import, post_export class CompanyResource(resources.ModelResource): class Meta: model = Company fields = ('website', 'user', 'country', 'source', 'industry') @admin.register(Company) class CompanyAmin(ImportExportModelAdmin): resource_class = CompanyResource list_display = ('domain', 'website', 'exported', 'added_on') list_filter = ('user', 'country', 'imported', 'exported', 'added_on') import receiver from import_export.signals import post_import, post_export @receiver(post_export, dispatch_uid='ss1') def _post_export(model, **kwargs): print(model) model.exported = True model.save() # This line when included raises Error: "save() missing 1 required positional argument: 'self'" so code breaks here -
How to use model's default value in the serializer?
I have a serializer defined by model's fields in the following way: class MyModel(models.Model): f1 = models.CharField(max_length=10, default='abc') class Serializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['f1'] Bit, running: Serializer({}).data Return an empty object. So how can I use the default value declared in the model? I know I can repeat the field in serializer, like that: class Serializer(serializers.Serializer): f1 = serializers.CharField(default='abc') Serializer({}).data This will return the expected {'f1' : 'abc'}, but I do not want to repeat myself. -
error while using makemigration in django
i am working on a development server running python3.6 and django 1.11 with virtualenv when I use "python manage.py makemigrations" i get this error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.core.management.base import ( File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/core/management/base.py", line 17, in <module> from django.db.migrations.exceptions import MigrationSchemaMissing File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/db/migrations/__init__.py", line 1, in <module> from .migration import Migration, swappable_dependency # NOQA ImportError: No module named 'django.db.migrations.migration' please help me -
Django annotate Avg on model field
I have these models: class Agency(models.Model): pass class User(models.Model): agency = models.ForeignKey(Agency) class Feedback(models.Model): rating = models.DecimalField() user = models.ForeignKey(User) and I want to annotate a queryset with the average of all ratings. I expected this to work: Feedback.objects.annotate(avg_rating=Avg('rating')).values('rating', 'avg_rating') but it just outputs this: <QuerySet [{'rating': 0.8, 'avg_rating': 0.8}, {'rating': 0.2, 'avg_rating': 0.2}, {'rating': 0.6, 'avg_rating': 0.6}, {'rating': 1.0, 'avg_rating': 1.0}, {'rating': 0.4, 'avg_rating': 0.4}]> As you can see the average should be 3.0. Where am I going wrong? For a bit of clarity, I'm trying to do something like this: agencies = Agency.objects.annotate( avg_rating=Coalesce(Subquery( Feedback.objects.filter(user__agency_id=OuterRef('pk')) .values('rating') .annotate(avg_rating=Avg('rating', output_field=DecimalField())) .values('avg_rating') ), 0) ) where the average rating is per agency. Any ideas? -
Makemigrations error : django.db.utils.OperationalError: no such table
when I makemigrations i get the following error: django.db.utils.OperationalError: no such table: django_site Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\campaign\models.py", line 5, in <module> from sinUser.models import sinUser, sinUserCategories File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\sinUser\models.py", line 4, in <module> from functionUtility.sendEmails import sendEmailFunctionIsError File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\functionUtility\sendEmails.py", line 12, in <module> HOSTNAME = Site.objects.get_current().domain File "C:\Python27\lib\site-packages\django\contrib\sites\models.py", line 63, in get_current return self._get_site_by_id(site_id) File "C:\Python27\lib\site-packages\django\contrib\sites\models.py", line 35, in _get_site_by_id site = self.get(pk=site_id) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 374, in get num = len(clone) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 232, in __len__ self._fetch_all() File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 894, in execute_sql raise original_exception django.db.utils.OperationalError: no such table: django_site I am newbies python programming some one can help me thank you -
Django 1.11 EmailMultiAlternatives: ValueError: need more than 1 value to unpack
Iam trying to send an email using EmailMultiAlternative. Using Django 1.11, Python 3.4. However I am getting ValueError. Am using the SMTP backend.This is the code: subject = "Hi {} !".format(user.username) sender = settings.DEFAULT_FROM_EMAIL recipients = [user.email, ] html_content = render_to_string('email/hello.html', {'url': url, 'first_name': user.first_name, 'last_name': user.last_name, 'static': HOST + settings.STATIC_URL,}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, sender, recipients) msg.attach_alternative(html_content, "text/html") msg.send(). However I am get the following error: ValueError: need more than 1 value to unpack Complete traceback here: Traceback (most recent call last): File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/edit.py", line 183, in post return self.form_valid(form) File "/home/george/george/project/new_beco/applications/accounts/views.py", line 87, in form_valid msg.send() File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/backends/smtp.py", line 123, in _send from_email = sanitize_address(email_message.from_email, encoding) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/message.py", line 136, in sanitize_address nm, addr = addr ValueError: need more than 1 value to unpack -
Image size change by URL Request like Instagram style
I noticed that Avatar in Instagram (sorry I cant post links): thumbnail (150 x 150) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s150x150/e15/11821182_168255950173048_11130460_n.jpg low_resolution (320 x 320) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s320x320/e15/11821182_168255950173048_11130460_n.jpg standard resolution (640 x 640) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s640x640/sh0.08/e35/11821182_168255950173048_11130460_n.jpg When we change the dimenstion in URL (s640x640 -> s128x128), the dimension of image change automatically. What is it and How can I handle this in Python Django? Is there any package to do this? Thank you! -
Custom inclusion templatetag with djangoCMS render_model
I have created a website with djangoCMS and make heavy use of apphooks, cms plugins, wizards, etc. We have a simple app with just one model holding the core data that should be displayed on the homepage. models.py from django.db import models from django.utils.text import slugify from django.urls import reverse from cms.models.fields import PlaceholderField from djangocms_text_ckeditor.fields import HTMLField class Programme(models.Model): name = models.CharField(max_length=60, unique=True) slug = models.SlugField() icon = models.CharField(max_length=50, unique=True) introduction = HTMLField() overview = PlaceholderField( 'programme_overview', related_name='programmes_overview' ) def __str__(self): return self.name def get_absolute_url(self): return reverse( 'programmes:programme-detail', kwargs={'slug': self.slug} ) def save(self, *args, **kwargs): if not self.pk: self.slug = slugify(self.name) super(Programme, self).save(*args, **kwargs) I decided to create a custom inclusion templatetag for this purpose. templatetags/programmes_tags from django import template from ..models import Programme register = template.Library() @register.inclusion_tag('programmes/programme_list.html') def programme_list(): programmes = Programme.objects.all() return {'programmes': programmes} In the template I use render_model from the cms_tags, because the editors should be able to edit the contents in the frontend. Here is the template: templates/programmes/programme_list.html {% load cms_tags %} {% for programme in programmes %} <div class="col-lg-2 col-md-4 col-sm-6 col-xs-12 text-center flex-item"> <div class="service-box"> <i class="fa fa-4x {{ programme.icon }} wow bounceIn text-primary" style="visibility:visible;"></i> <h3> <a href="{% url 'programmes:programme-detail' programme.slug %}"> … -
Django Form Fields won't show in my template
The form field won't show up in the browser. There is only the submit button showing up. views.py code: def vote(request, pk): # check if request is post if request.method == 'POST': # create a form and populate it with data from request form = forms.Vote(request.POST) if form.is_valid(): fact = Fact.objects.get(pk=pk) fact.votes += int(form.cleaned_data['vote']) fact.save() return HttpResponseRedirect(reverse( 'facts:detail', args=(pk,) )) else: form = forms.Vote() return render(request, 'facts/fact_detail.html', {'form': form}) template(fact_detail.html) code: <form method='POST'> {% csrf_token %} {{ form }} <input type="submit" value="vote" /> </form> Form class(forms.py) code: VOTE_CHOICES = [ (1, 'upvote'), (0, 'downvote') ] class Vote(forms.Form): vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect())