Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrate Django app as Page in Mezzanine Admin interface
I have existing apps in Django. I want to integrate them with mezzanine project in a way that the apps are available in form of pages. I followed this method. The steps I followed- I created a fresh vanilla mezzanine project- it works! Then I created theme for website- it works! From admin interface if i add a page, the page renders along with website theme. Copy pasted the Django apps in mezzanine project. Added the app names in mezzanine project's settings.py file at the beginning of INSTALLED_APPS. Added corresponding URL patterns in mezzanine project's urls.py file The related code snippets (example app, About Us)- testproject/aboutus/views.py from django.shortcuts import render def aboutus(request): context=locals() #context=page(about) template = 'aboutus/aboutus.html' return render(request,template,context) testproject/aboutus/urls.py import mezzanine from django.conf.urls import url from aboutus import views from mezzanine.conf import settings urlpatterns = [ url(r'^aboutus.html',views.aboutus,name='aboutus'), ] testproject/urls.py from __future__ import unicode_literals import mezzanine from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.views.i18n import set_language from mezzanine.core.views import direct_to_template from mezzanine.conf import settings from aboutus import views urlpatterns += [ url("^$", direct_to_template, {"template": "index.html"}, name="home"), url(r'^',include('aboutus.urls')), url("^", include("mezzanine.urls")), ] I'm missing out on something minute but very important. We want the existing … -
MultiDict Error Django
Im using Django and trying to get a response by using AJAX. I have two forms, the first one works just fine. Though I use the same logic in my second form handling it does not work well. models.py class AskMe(models.Model): name = models.CharField(max_length=1000) views.py def AskMeQ(request): if request.method == POST: name = request.POST['name'] AskMe.objects.create(name=name) urls.py url('r^askmeQ/$', views.AskMeQ) ERROR Traceback: File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__ 77. list_ = super().__getitem__(key) During handling of the above exception ('name'), another exception occurred: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pc/Django_Projects/vikas/vikas/views.py" in askmeQ 40. name = request.POST['name'] File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__ 79. raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /askmeQ/ Exception Value: 'name' The logic I use above used to work in all the previous forms, but here it throws me an error. The SQLite3 table has been created as projectname_model.name. How can I correct this? -
python social_auth facebook can't get extra scopes
I'm using social_auth in my django project in order to provide facebook login. I'm trying to get the user email. Note that i'm testing it locally. I can see the email being supplied from facebook in the popup but it appears to be empty in my custom pipeline. in kwargs: { [some stuff], 'username': 'xxx','email': '', 'last_name': 'xxx'}) Here is my configuration in settings.py (I tried everything) : SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', ] SOCIAL_AUTH_PROTECTED_USER_FIELDS = ['email',] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {'fields': 'id,name,email,first_name,last_name'} -
AttributeError with Django Rest nested serializer
I'm following the Django Rest documentation for writing nested serializer but it is giving me attribute error. Here are my models: class Objects(TimeStampModel): projects = models.ForeignKey(Projects,related_name='proj_obj',on_delete=models.CASCADE) object_name = models.CharField(max_length=50) object_description = models.TextField() object_main_table = models.CharField(max_length=50) object_primary_key = models.CharField(max_length=50) object_age_field = models.CharField(max_length=50) date_format = models.CharField(max_length=50) def __str__(self): return self.object_name class ObjectDefinition(TimeStampModel): ATTRIBUTE = 'Attribute' RELATION = 'Relation' TYPE_CHOICES = ( (ATTRIBUTE, 'Attribute'), (RELATION, 'Relation'), ) obj = models.ForeignKey(Objects,related_name='obj_def',on_delete=models.CASCADE) from_table = models.CharField(max_length=50) from_table_field = models.CharField(max_length=50) to_table = models.CharField(max_length=50) to_table_field = models.CharField(max_length=50) relation_type = models.CharField(max_length=50,choices=TYPE_CHOICES) relation_sequence = models.CharField(max_length=50) value_field = models.CharField(max_length=50, blank=True, null=True) Here is my serializers.py snippet: class ObjectDefinitionSerializer(serializers.ModelSerializer): class Meta: model = ObjectDefinition fields = ('from_table','from_table_field','to_table','to_table_field','relation_type','value_field') class ObjectSerializer(serializers.ModelSerializer): definition = ObjectDefinitionSerializer(many=True) object_description = serializers.CharField(required=False, allow_null=True, allow_blank=True ) class Meta: model = Objects fields = ('projects','object_name','object_description','object_main_table','object_primary_key','object_age_field','date_format','definition') def validate(self, data, *args, **kwargs): date_format = data.get('date_format') if date_format not in ['YYYYMMDD', 'DDMMYYYY']: msg = ('Date format is incorrect') raise serializers.ValidationError({'error_msg': msg}) return super(ObjectSerializer, self).validate(data, *args, **kwargs) def create(self, validated_data): definition_data = validated_data.pop('definition') obj = Objects.objects.create(**validated_data) for data in definition_data: ObjectDefinition.objects.create(obj=obj, **data) return obj My views.py: class CreateObject(CreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = ObjectSerializer After hitting POST, objects.create works fine for both the models but at return obj, it throws me this error: Exception Value: … -
Django Form save - circular dependency
I have 2 models Account and User. An Account can have multiple users. When the first User(Owner) is created at the same time the Account will be created. Because User have a ForeignKey to Account, I need first to create the Account, and after the User. But Account had a field created_by which is request.user. So is a circular problem. I think I need to create first the Account and created_by to be a superuser(first) and than create the User, and update the Account with the new user. class Account(MetaData): name = models.CharField(max_length=255) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE) class User(AbstractBaseUser): account = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='owner') How can I do that ? I need this only first time, for the first user, because after that for the other users the Account will exist. -
Python dict, extracting values
I am having trouble to query my database maybe someone could give me a hand. I am using a django application so I guess Sqlite3 >> and the output I would like to get is the score value b = Answer.objects.get(id = 23) which give me an output of : <Answer: Answer to questionID '4' : AnswerID '23'> when I do : b.values I get a dict in the form : ['{ "1)Long descriptive text":Score, "2)Long descriptive text":Score, "3)Long descriptive text":Score, "4)Long descriptive text":Score }'] with score beeing an Integer from 0 to 100 so for example "Long descriptive text":85 I need to extract the score using a query but I can't manage to do it Normaly for a Dict[key:value] I would do a Dict[key] but here I do not know how to do it could you give me a hand Thx you very much -
"rotating" columns and unique_together
I have a django model: class ShortestRoads2(models.Model): start_node = models.ForeignKey('Nodes', related_name='start_node2', null=True) end_node = models.ForeignKey('Nodes', related_name='end_node2', null=True) map = models.ForeignKey('project.MapProject', null=True) def __str__(self): return str(self.start_node) + ' to ' + str(self.end_node) class Meta: unique_together =(("start_node", "end_node", "map"),) class Nodes(models.Model): number = models.IntegerField(null=True, unique=True) geom_node = models.PointField(spatial_index=True) Is it possible to create another unique_together contraint, where "start_node" and "end_node" fields are switched? Explained: obj = ShortestRoads2() obj.start_node = Nodes.objects.create(number=x1) obj.end_node = Nodes.objects.create(number=x2) obj.save() # Object created obj2 = ShortestRoads2() obj2.start_node = Nodes.objects.create(number=x1) obj2.end_node = Nodes.objects.create(number=x2) obj2.save() # Raising as expected: IntegrityError obj3 = ShortestRoads2() obj3.start_node = Nodes.objects.create(number=x2) #Notice varible change obj3.end_node = Nodes.objects.create(number=x1) #Notice variable change obj3.save() # Object created I want a exception raised when I'm saving obj3. But how to? -
HTML layout object doesn't work
I quite new with Django Crispy Form and I have tried to add a HTML object in my form but it's not working. All the other elements are rendered but not the HTML. This is my form: forms.py class MyUserRegistrationForm(forms.ModelForm): class Meta: model = MyUser fields = ['title', 'privacy_disclaimer_accepted'] def __init__(self, *args, **kwargs): super(MyUserRegistrationForm, self).__init__(*args, **kwargs) helper = FormHelper() helper.form_method = 'post' helper.form_class = 'form-horizontal' helper.label_class = 'col-sm-2' helper.field_class = 'col-sm-6' helper.form_error_title = 'Form Errors' helper.error_text_inline = True helper.help_text_inline = True helper.html5_required = True helper.form_tag = False helper.layout = Layout( Fieldset('Information', 'title'), HTML(""" <div id="iframe" class="mt-5"> <h6>Notice/Disclaimer:</h6> <div class="privacy-policy"> {% if privacy_disclaimer %} {{ privacy_disclaimer }} {% else %} {% include "registration/privacy_policy.html" %} {% endif %} </div> </div> """), Fieldset('Privacy Statement', 'privacy_disclaimer_accepted', ) ) I have a basic HTML file, where I have the normal html, header and body tags. This is the HTML registration page: register.html {% extends "base.html" %} {% block title %}Create an account{% endblock %} {% block content %} <div class="registration-page"> <h3 class="text-center">Create an account</h3> <div class="registration-page__form"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-error"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} … -
Invalid block tag: 'else' - 'extends' inside a if statement
I'm trying to extends a template depending of the the existence of the 'custom_nav' variable: {% if 'custom_nav' %} {% extends custom_nav %} {% else %} {% extends "playexo/default_nav.html" %} {% endif %} But I get: Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? It's probably a dumb error but I can't figure it out, I'm wasting my time on it for 1h now... I've searched for similar problem and it seems like an old one: Django Invalid block tag: 'else' -
The Django make ORM query
class Task(models.Model): subject = models.CharField(max_length=256) description = models.TextField(max_length=1024) reward = models.PositiveIntegerField() begin_date = models.DateField() number_of_people = models.PositiveIntegerField(default=1) class TaskDetail(models.Model): user = models.ForeignKey(User, related_name='tasks') task = models.ForeignKey(Task, related_name='tasks') This is a simple task assignment system model designed by me. and I have a question.I attempt to make a user report that include the number of task user've done.but I don't know how to make ORM query. users = User.objects.all Does anyone know how to solve this issue? Thx -
Modify django Admin forms
I have the following model form which I inherit in the majority of my models. class UserStamp(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='%(app_label)s_%(class)s_updated_by', on_delete=models.CASCADE) class Meta: abstract = True Where I construct my own forms I use form.instance.created_by = self.request.user and everything is ok. But not in admin (expecting staff users) because he uses his own forms. What is the simplest way to make the admin forms work properly(something tha I don't need to do each of them from zero). -
Cannot get PyCharm Django project to read and display Django Templating Language Tags
I have been pulling my hair out over this, am new to using Django for web development and I have never setup a Django project in PyCharm. It is Django v2.0 and PyCharm 2017.3. I have a basic project which consists of two apps, for examples sake lets call one Test and one TestProj. Test is the core of the site where settings.py is located, and TestProj is where I wish to add templates. The Test urls.py points to the TestProj urls.py, which when requested, serves a html file to the root url of the site. This content is located in a folder again called Test which is located in a templates folder in TestProj Essentially the directory structure is as follows: Test > settings.py etc TestProj > templates > Test > index.html header.html other python files are here! The index.html file is served fine but the problem occurs when I try to use Django templating to link in another html file. This is index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> <div> {% block content %} {% endblock %} </div> </body> </html> And this is header html which is located in the same templates directory: {% … -
django + uwsgi in docker
What is the best way to deploy Django apps inside a docker. I have looked into couple of blogs and it seems in most of the examples everyone is trying to put nginx + django + uwsgi in one container. But container should have one process only. so i am trying django and uswgi in one container and nginx is in another container or on host machine itself. Could some please suggest me best approach. P.S:- My django app is just providing me REST API results. and i am not using Django template for my static contents. I am also looking for enabling all these with https. Please share a blog or github link if someone already have achieved similar way of django app hosting. -
Data is not being read directly from the database instead of buffer on 2nd call
I have the following piece of code in my model that ensures that user will be not able to modify a record that was modified by someone else after he has opened it. def save(self, *args, **kwargs): on_disk = Lease.objects.get(pk=self.id) self.full_clean() if on_disk.version == self.version: error = 0 #do nothing else: raise ValidationError('Record have been modified by another user, please reopen and edit again') # self.version = self.version + 1 return super(Lease, self).save(*args, **kwargs) There is mechanism implemented(Django concurrency package) that ensures that after each save version value will be modified. However, this piece of code doesn't work it appears to me that on_disk value is not being populated with the most recent value from the disc but get it from some buffer and as result this code check is useless. Any idea how to make it work? -
Django: Get model fields in wrapper function
I want to create log data in which I want to show the previous data in the table according to primary key. After that I want to show the updated data which I am able to log. Please help in fetching the database data fields according to whatever primary key has been provided. Making another function to fetch queryset in the wrapper function is also not happening. views.py def func_detail(func): @wraps(func) def func_wrapper(*args, **kwargs): logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) logging.getLogger(__name__) print("Inside wrapper. Calling method %s now..." % (func.__name__)) changed = [field for field in (args[1].data).__dict__] print(changed) if func.__name__ == 'list': logging.info("This is all the list of objects created by you in table") elif func.__name__ == 'create': logging.info("New user added in database & table:{}".format(dict(args[1].data))) elif func.__name__ == 'update': logging.info("With pk:{}".format(list(kwargs.values()))) logging.info("previous data in model fields"??) logging.info("Updated model fields from table:{}".format(dict(args[1].data))) elif func.__name__ == 'partial_update': logging.info("In pk:{}".format(list(kwargs.values()))) print("Updated partial data from table in fields:{}".format(dict(args[1].data))) r = func(*args, **kwargs) return r return func_wrapper class UsersViewSet(viewsets.ViewSet): @func_detail def list(self, request): queryset = Mytable.objects.all() if request.GET.get('name'): queryset = queryset.filter(name=request.GET.get('name')) serializer = CheckSerializer(queryset, many=True) return Response(serializer.data) @func_detail def update(self, request, pk=None): users = get_object_or_404(Mytable, name=pk) serializer = CheckSerializer(users, data=request.data) if serializer.is_valid(): serializer.save() return … -
Typeerror: view must be callable
when i run my server i get a type error message telling me that 'my view must be callable or a list/tuple' and from what i gathered django version differs an for clarity sake,am using django latest version...anyways here's my views.py and urls.py for my project url.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^login/$', 'django.contrib.auth.views.login',name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout',name='logout'), url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login',name='logout_then_login'), ] views.py from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import authenticate, login from .forms import LoginForm from django.contrib.auth.decorators import login_required def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'],password=cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) @login_required def dashboard(request): return render(request, 'account/dashboard.html',{'section': 'dashboard'}) -
Django + WSGI: When is wsgi.py called?
I deployed my Django-project via Apache2 on a server. The problem I have is that I have two setting-modules: settings.py which are my local development settings and settingsprod.py which are my productive settings. I found the following line in the WSGI.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") Is this module only called when using WSGI? And if yes is this a good place to use my production settings like so? os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settingsprod") For local development I use the development server like so: python3 manage.py runserver Does this still defaults to settings.py then? -
How complete web application architecture work?
I am newbie in Web Development. I am Backend developer. I'm using Python-Django web framework. I understand what is Server and What is Client. Recently I have heard lot of new terms like Apache web server, Nginx, AWS, WSGI, Gunicorn. I don't understand how they fit in complete web application architecture. I write the backend code in Python (with Django framework) and called it as a server. How my server (My Python code) is different from Apache web server? How my code is using Apache or Nginx? What's the role of WSGI and Gunicorn? I didn't understand anything. I didn't understand web architecture. Can someone push me in right direction? How can I understand all terminology? Any help would be appreciated. Thanks. -
ListApiView returning only one set of object
I am trying to make an autocomplete api. Where based on one keyword, will return two separate object. But always returning one object and other one is always empty. What am i doing wrong ? My code class HotelAutoComplete(ListAPIView): serializer_class = HotelSerializer permission_classes = [] def list(self, request): city_list = [] hotel_list = [] if request.GET.get('q', None): city_list = Hotel.objects.filter( city__name__icontains=request.GET.get('q') ).values('city__name', 'city__country__name') hotel_list = Hotel.objects.filter( name__icontains=request.GET.get('q') ).values('name', 'slug') return Response({'city_list': city_list, 'hotel_list': hotel_list}, status=200) -
deploy django on tomcat
List item I am using Django 1.8 on jython in windows 10. I am beginner to Django and jython. Have created a simple Django project following the tutorial https://docs.djangoproject.com/en/1.8/intro/tutorial01. After packaging using buildwar(including jars), when I deploy the mysite.war archive in tomcat, I get error. My project name is mysite, I have referenced the jython path in web.xml. My project structure is -mysite -WEB-INF -lib -jruby-extras-fileservlet.jar -jython.jar -lib-python -django -doj -polls -application_settingspy.class -application_settings.py -eggs.pth -web.xml -wsgi Error is Traceback (most recent call last): File "D:\jython27\Lib\modjy\modjy.py", line 80, in service self.exc_handler.handle(req, resp, wsgi_environ, mx, (typ, value, tb) ) File "D:\jython27\Lib\modjy\modjy.py", line 76, in service self.dispatch_to_application(req, resp, wsgi_environ) File "D:\jython27\Lib\modjy\modjy.py", line 92, in dispatch_to_application app_callable = self.get_app_object(req, environ) File "D:\jython27\Lib\modjy\modjy_publish.py", line 68, in get_app_object return self.get_app_object_old_style(req, environ) File "D:\jython27\Lib\modjy\modjy_publish.py", line 120, in get_app_object_old_style return self.load_object(source_filename, callable_name) File "D:\jython27\Lib\modjy\modjy_publish.py", line 142, in load_object self.raise_exc(NoCallable, "Error loading jython callable '%s': %s" % (callable_name, str(x)) ) File "D:\jython27\Lib\modjy\modjy.py", line 121, in raise_exc raise exc_class(message) modjy.modjy_exceptions.NoCallable: Error loading jython callable 'application': No module named mysite I don't know what have I missed, the application_settings file shows: from mysite.settings import * CONTEXT_ROOT = "mysite" Can anyone help me on this issue and share any project structure? -
Django Allauth: Customize Forms (Label, Fields, Order)
im new to Django and even newer to Allauth. My Problem is i want to customize the Forms (Login,SignUp etc) but i'm unable to find a good Tutorial and couldn't find anything in the Documentation or in Forums that helped me. First of all i want to make a Custom SignUp Form, adding new Fields is working for me but i'm not able to Change the Labels and Placeholder or the Order. My forms.py looks like this: from django import forms class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label='Voornaam') email = forms.EmailField(max_length=30, label='Email Adresse') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.email = self.cleaned_data['email'] user.save() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'] = forms.EmailField(label='Label') I'm thankful for every help, and maybe some links with more infos for customizing Allauth. -
Django Creating a Custom User with the Django Rest Framework
I'm trying to create a custom user using the Django Rest Framework. I got it to the point to where I can create a regular user, but I'm unsure on how to extend it to the custom user model. models.py: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) languages = ArrayField(models.CharField(max_length=30, blank=True)) serializers.py: from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password') def create(self, validated_data, instance=None): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user views.py: @api_view(['POST']) @permission_classes((AllowAny,)) def create_user(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) How do I extend the languages field to the UserSerializer to where it can process it? Would it be better to create a signal for every time a user is created it then creates a userprofile automatically? -
Django: HttpResponseRedirect is not defined
I finally managed to POST data from a form to a database in django, however when I press the submit button on my form I get the error: Request Method: POST Request URL: http://127.0.0.1:8000/post_url/ Django Version: 1.11.2 Exception Type: NameError Exception Value: name 'HttpResponseRedirect' is not defined Exception Location: /home/xxxx/Desktop/123/src/exercises/views.py in post_treasure, line 26 Python Executable: /home/xxxx/Desktop/123/bin/python Relevant views.py: def post_treasure(request): form = TreasureForm(request.POST) if form.is_valid(): treasure = Treasure(name = form.cleaned_data['name'], value = form.cleaned_data['value'], material = form.cleaned_data['material'], location = form.cleaned_data['location'], img_url = form.cleaned_data['img_url']) treasure.save() return HttpResponseRedirect('/numbers/') Relevant urls.py: urlpatterns = [ url(r'^post_url/', post_treasure, name='post_treasure'), url(r'^admin/', admin.site.urls), url(r'^numbers/', numbers, name="numbers"), url(r'^about/', about, name="about") ] Other note: The data is successfully posted if I press the back button to view the new updated data passed from the model to the template, or if I use the admin interface to simply view the data -
How Open YouTube Video by clicking link in Django
I am trying to open my videos if user click on any given link but a am not able to do this whenever i clicked on any link then i got 404 error here i have added some screen short please tell me what should i do This is my html page -
Get Value From 'param' Of 'views.py' In Javascript Django
In views.py def website(request, pk=None): if not model_utils.check_admin_permission(request): return loginAndContinuosRequest(request) if pk: obj = get_object_or_404(Website, pk = pk) form = WebsiteForm(instance=obj) fields = obj.get_manage_payment_accounts() else: obj = None form = WebsiteForm() fields = [] if request.POST: if pk: form = WebsiteForm(request.POST, request.FILES, instance=obj) else: form = WebsiteForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("views_manage_websites")) params = { 'obj':obj , 'form':form, 'fields': fields, 'test': 'test', } return render(request, TEMPLATE_PATH + 'website.html', params) In script in template (.html), <script> $(document).ready(function() { alert({{ obj.id }}); //(1) alert({{ obj.pk }}); //(2) alert({{ obj.site_name }}); //(3) alert ({{ test }}); //(4) }); </script> The alert (1) and (2) is shown. But the alert (3) and (4) isn't shown. Can you explain for me. Thanks.