Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting an email via Facebook graph API request with python
After getting a facebook code via this request: https://www.facebook.com/v2.12/dialog/oauth?client_id=1926xxxx50&scopes={email,first_name,name,last_name}&redirect_uri=http://localhost:8000/en/facebook/&state= I get the access token via the following request: import requests params = ( ('client_id', FACEBOOK_CLIENT_ID), ('redirect_uri', 'http://localhost:8000/en/facebook/'), ('client_secret', FACEBOOK_CLIENT_SECRET), ('code', code_token), ) response =requests.get('https://graph.facebook.com/v2.12/oauth/access_token', params=params) And finally I make the following request: PARAMS = (('fields', 'id,name,email,last_name,address,gender,first_name'),('access_token', FACEBOOK_ACCESS_TOKEN),) RESPONSE = requests.get('https://graph.facebook.com/v2.12/me', params=PARAMS).json() to retrieve id, name, email, last name, address, gender, first name. But the email is very random. I can recover it for some users but not for others. Can someone help me in this way? Thank you -
How to show link to all objects with same foreign key from Django Admin change page
I am trying to link directly from the change page of a Company Year in Django Admin to the other changepages of Company Year that have the same Company as a foreign key. Currently I have a link from the change page to the company page, and there I have links to all Company Years related to this company. However, it would be better if you could switch directly between the years without going to the company page first. class Company(models.Model): name = models.CharField(max_length=50) class CompanyYear(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) year = models.IntegerField() -
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 56-58: ordinal not in range(256)
I get the bellow error, when I request for a Chinese character name image: line 507, in handle_one_response result = self.application(self.environ, start_response) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/engineio/middleware.py", line 49, in __call__ return self.wsgi_app(environ, start_response) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 156, in __call__ request = self.request_class(environ) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 80, in __init__ path_info = get_path_info(environ) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 175, in get_path_info path_info = get_bytes_from_wsgi(environ, 'PATH_INFO', '/') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 224, in get_bytes_from_wsgi return value.encode(ISO_8859_1) if six.PY3 else value UnicodeEncodeError: 'latin-1' codec can't encode characters in position 56-58: ordinal not in range(256) the image url is: http://localhost:8000/images/qiyun_admin_websitemanage/bannerreconmend/服务器.png (and the url is exists in my database with the Chinese character) and I searched the SO, found this post. it says db.set_character_set('utf8') dbc.execute('SET NAMES utf8;') dbc.execute('SET CHARACTER SET utf8;') dbc.execute('SET character_set_connection=utf8;') In my Django project, I can not find the place to add those code. only the configuration codes there in my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_mine', 'USER':'root', 'PASSWORD':'root', 'HOST':'127.0.0.1', 'PORT':'3306', } } So, how to solve this issue? -
Django Prfetch object and only fails
I have the following code: In view: context['products']Product.objects.all().prefetch_related(Prefetch('categories', queryset=Category.objects.only('name'))) In template: {% for product in products %} {{ product.categories.all.0.name}} In this case prefetch_related is ignore, and it exeutes anew query in categories for each product. If I remove only, it executes just 2 queries Why ? -
Sum values of each key in list of dictionaries python
I have a list of dictionaries which is coming from Django query set. Like this: email_sent_count = [ { 'second_follow_count': 1, 'first_follow_count': 1, 'initial_count': 1, 'third_follow_count': 0 }, { 'second_follow_count': 1, 'first_follow_count': 0, 'initial_count': 1, 'third_follow_count': 1 }, { 'second_follow_count': 1, 'first_follow_count': 1, 'initial_count': 1, 'third_follow_count': 1 } ] Now, I want the sum of each key separately. like this: inital_contact = 3 first_followup = 2 second_followup = 3 third_followup = 2 I am trying the following solution: initial_contact = sum(map(lambda x: x['initial_count'], email_sent_count)) first_followup = sum(map(lambda x: x['first_follow_count'], email_sent_count)) second_followup = sum(map(lambda x: x['second_follow_count'], email_sent_count)) third_followup = sum(map(lambda x: x['third_follow_count'], email_sent_count)) But now, I'm getting 11 keys in all dictionaries and I'm implementing 11 lambda function so is there any good way to solve this issue rather than calling 11 times lambda function -
Django FloatField field is required on admin
I've got a field for additional_salary additional_salary = models.FloatField(blank=True, null=True) Issue is on the django admin the field keeps throwing an error if I don't fill anything as field is required I thought maybe null would fix it. I've done a migration, restarted gunicorn but the error persisted. Decided I would remove the field for now as I debugged. Removed it, did the migration and restarted gunicorn again but the field even though not visible on the form still throws an error. Not sure why but I'm starting to think django 2.0 might have lazy loaded the javascript, using nginx with it. -
I can not configure nginx + django
I can not think why incorrect works the nginx. I have the django app and I'm need show the static files, but when visit to 0.0.0.0 I see default page the nginx. I have to see the homepage of the django project. What am I doing wrong? Git: https://github.com/seferaua/testsite Docker-compose: version: '3' services: db: image: postgres web: working_dir: /app build: ./testsite command: bash -c "gunicorn testsite.wsgi -b 0.0.0.0:5000" volumes: - ./testsite:/app expose: - "5000" depends_on: - db ngnix: build: ./ngnix ports: - "80:80" depends_on: - web nginx.conf: server { listen 80; server_name 0.0.0.0; location /static/ { alias /var/www/static/; expires 3d; } location / { proxy_pass http://web:5000; proxy_set_header Host $host; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Structure project and other dockerfiles, you can see on the git -
Django bulk delete removes only hundred rows at a time
I have two models with one to many relation between them: class HomeCarrier(models.Model) short_name = models.CharField(max_length=32, unique=True) class CarrierZipCoverage(models.Model): zip_code = models.CharField(max_length=5) home_carrier = models.ForeignKey('HomeCarrier', null=True, blank=True) According to the docs You can also delete objects in bulk. Every QuerySet has a delete() method, which deletes all members of that QuerySet. According to the source comments The delete is actually 2 queries - one to find related objects, and one to delete. I suprised when I'm trying to bulk delete 27k carrier's coverage zip codes carrier.carrierzipcoverage_set.all().delete() I got one delete query for each hundred rows in database. Whereas I expected to see only one delete query in mysql log for all coverage zip codes at a time. -
In a QuerySet get the first child Model from a list of Parent Model
I have 2 models Product and Image. A Product can have multiple Image(s), so Image has a FK to product. I want to get the first image from a list of Product(s) I have the following queryset: images = Image.objects.filter(product_id__in=product_home).first() This is not working, because it return just one, and not one per product. -
Django migrations issues with foreign dependency
I am trying to deal with an "it works on my machine" type of problem. I have a django project using jenkins which fails on migrations. The step is triggered with this command: python manage.py test -v 2 --noinput and there goes traceback: Applying gloodny.0020_auto_20180314_1338... OK Applying openinghours.0001_initial... OK Applying payu_payment.0002_auto_20171222_1407... OK Applying sessions.0001_initial... OK Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle failures = test_runner.run_tests(test_labels) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/test/runner.py", line 532, in run_tests old_config = self.setup_databases() File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/test/runner.py", line 482, in setup_databases self.parallel, **kwargs File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/test/runner.py", line 726, in setup_databases serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True), File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 78, in create_test_db self.connection._test_serialized_contents = self.serialize_db_to_string() File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 122, in serialize_db_to_string serializers.serialize("json", get_objects(), indent=None, stream=out) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/serializers/__init__.py", line 129, in serialize s.serialize(queryset, **options) File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/core/serializers/base.py", line 79, in serialize for count, obj in enumerate(queryset, start=1): File "/var/lib/jenkins/workspace/papuportal/env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 118, in get_objects for obj in queryset.iterator(): … -
Django mixin to check request and add value to the context
In several classes i've to check if an object is of propery of the user (the object_id is passed in the url, so I've to make a query as the one below) and then have it in the context to be used in the rendering of the template and also in the request for some logic when storing objects. Since I'm using class based view, I was thinking of making a Mixing to do so (like the one for Logged Users), I've done this: class ObjRequired: def dispatch(self, request, *args, **kwargs): obj_id = kwargs.pop('obj_id') obj = get_object_or_404(MyModel, owner=request.user, obj_id=obj_id) request.obj = obj return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): kwargs['obj'] = self.request.obj return super().get_context_data(**kwargs) (i've just added obj everywhere to change the name) Now, in the request i can find .obj while the get_context_data it's not called and then the obj is not available in the template. Any idea why? Is there a better way to do what I've in mind? -
How to make android app for my django ecommerce website without android webview?
How to make android app for my django ecommerce website without android webview? How to start i don't have any idea. -
Why can't I install django
whenever I go to the command prompt and typepip install Django==2.0.3 I receive this in red text. Exception: Traceback (most recent call last): File "c:\program files (x86)\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files (x86)\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "c:\program files (x86)\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files (x86)\python36-32\lib\site-packages\pip\wheel.py", line 316, in clobber ensure_dir(destdir) File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir os.makedirs(path) File "c:\program files (x86)\python36-32\lib\os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'c:\\program files (x86)\\python36-32\\Lib\\site-packages\\pytz' It also tells me that my pip installer is out of date, but whenever I try to update it I just receive the same error message. -
Mongoengine orderby on two field getting error
I am new to mongoengine and Mongo. I have more than 20000 documents in mongo and also added the index on date and version and I want to order in these two fields order_by('-date', '-version') but while ordering it throwing below error database error: too much data for sort() with no index. add an index or specify a smaller limit Could you please help me out to resolve the above issue? -
Django - Admin StackedInlines displayed depending on UserModel attribute value
In my application there's two types of users. Both user types have a UserModel and UserProfileModel, and will have either the model UserTypeA or UserTypeB. The user_type attribute of the UserModel is set to either A or B depending on which form they sign up from, and from there a new, corresponding UserTypeX model is created given this user_type value X. In admin.py, how might I display StackedInline classes depending on the type of user? As an example, a user with a user type of B will only have the classes 'UserModel', 'UserProfileModel' and 'UserTypeB' displayed in the admin (since they will not need to have access to UserTypeA class). class UserAdmin(BaseUserAdmin): update_form = UserUpdateForm create_form = UserCreationForm list_display = ('email','date_joined','is_active','user_type') list_filter = ('email','date_joined','is_active','user_type') fieldsets = ( (None, {'fields': ('email','password','user_type')}), ('Permissions', {'fields':('is_admin','is_active')}), ) inlines = (UserProfileInline, ) # This should also include 'UserTypeBInline' if the user_type specified in the UserModel is equal to B, and 'UserTypeAInline' for A. add_fieldsets = ( (None, { 'classes':('wide',), 'fields':('email','password','user_type','is_admin','is_active') } ), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () def get_inline_instances(self, request, obj=None): if not obj: return list() return super(UserAdmin, self).get_inline_instances(request, obj) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(UserAdmin, self).__init__(*args, … -
When exactly ModelSerializer saves data to model?
I have this model and serializer: class User(Model): name = Charfield() is_available = BooleanField() class UserSerializer(ModelSerializer): class Meta(): model = User fields = '__all__' And I also have this view function: @api_view('GET', 'PATCH') def current_user(request): serializer = UserSerializer(request.user, context={'request': request}) if request.method == 'PATCH': serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) PATCH request returns 200 OK but doesn't change user data. It looks like calling serializer.save() is not enough te save data to model. So when exactly ModelSerializer saves data to model? -
Django 2.0 : raises unbound error
i was working with Django 1.11 and created a template that contains a formset. everything worked fine. but i've upgraded Django to Django 2.0 now and my template raises : sequence item 5: expected str instance, BoundField found i'm stucking here without knowing why would such an error accure when it was working with Django 1.11 here is my template where my form: <table style ="border-collapse: separate;border-spacing: 15px;" id="id_forms_table"> <tr><td width="5%">N P</td><td width="8%">Date d'operation</td><td width="25%">Désignation</td><td width="10%">Type tiers</td><td width="10%">Tiers</td><td width="10%">Référence de Facture</td><td width="10%">Montant Débit</td><td width="10%">Montant Crédit</td></tr> {% for form in formset %} <tr style="border:1px solid black;" id="{{ form.prefix }}-row" class="dynamic-form" > <td{% if forloop.first %} class="" {% endif %}><div class="col-xs-1"><b><p name="np1">1</p></b></div></td> <td> {% render_field form.dateOperation1 class="form-control" id="inlineFormInputName" name="designation1" %}{{form.dateOperation1.errors}} </td> <td>{% render_field form.designation1 class="form-control" id="inlineFormInputName" placeholder="Designation opération" name="datefacture1" %}{{form.designation1.errors}} </td> <td> {% render_field form.typeTiers1 class="form-control" id="inlineFormInputName" placeholder="Montant HT" %}{{form.typeTiers1.errors}} </td> <td> {% render_field form.tiers1 class="form-control" id="inlineFormInputName" placeholder="TVA" name="tiers" %}{{form.tiers1.errors}} </td> <td>{% render_field form.numfacture1 class="form-control" id="inlineFormInputName" placeholder="" name="mttc1" %}{{form.numfacture1.errors}} </td> <td>{% render_field form.montantdebit1 class="form-control" id="inlineFormInputName" placeholder="Montant" name="mttc1" %}{{form.montantdebit1.errors}} </td> <td>{% render_field form.montantcredit1 class="form-control" id="inlineFormInputName" placeholder="Montant" name="mttc1" %}{{form.montantcredit1.errors}} </td> </tr> {% endfor %}<tr> </tr></table> forms.py : class FormBanque(forms.Form): dateOperation1=forms.DateField(initial=datetime.date.today) designation1=forms.CharField() typeTiers1=MyModelChoiceField1(queryset=operation_Bancaire.objects.all(),to_field_name='type_tiers',required=False) tiers1=forms.ModelChoiceField(queryset=operation_Bancaire.objects.none()) numfacture1=forms.ModelChoiceField(queryset=client.objects.all().values_list('nom', flat=True),required=False) montantdebit1=forms.CharField() montantcredit1=forms.CharField() BanqueFormSet=formset_factory(FormBanque) Here is my view: class BanqueViews(TemplateView): … -
'ImageFieldFile' object has no attribute 'user'
I've got the following code that allows the user to create a blog post. models.py class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() thumb = models.ImageField(upload_to=upload_location, null=True, blank=True, validators=[file_size]) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) def __str__(self): return self.title views.py def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:article_list') else: context = { "form": form } return render(request, 'articles/article_create.html', context) else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', { 'form': form }) This code works perfect. The user can create an article with an image and view it in their blog. I added some code to rotate the image on the blog post based on exif data. As a result, my view.py now looks like this: def fix_orientation(filename): img = Image.open(filename) if hasattr(img, '_getexif'): exifdata = img._getexif() try: orientation = exifdata.get(274) except: orientation = 1 else: orientation = 1 if orientation is 1: pass elif orientation is 2: img = img.transpose(Image.FLIP_LEFT_RIGHT) elif orientation is 3: img = img.rotate(180) #additional elif conditions were put here for orientation of 4 - 8 img.save(filename) def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST or None, request.FILES or None) if … -
Django: ValidationError message not showing in admin changeform
I am working on a webapp where user can be a member of one (and only one) organisation - this is done with a foreignkey in the Profile model, which in turn has a one-to-one link with the default django.auth.user model. We also want to make sure that each email address is only used once within each organisation. To do this we added the following function to the Profile model: def clean(self): if self.organisation and Profile.objects.filter( user__email=self.user.email, organisation_id=self.organisation.id ).exists(): raise ValidationError({'user': _('The email address from this user is already used within this organisation!')}) return super(Profile, self).clean() However, when I add a user through the Django admin using an duplicate email address all that gets displayed is a generic please fix the errors below message at the top of the form. No text is displayed near the email field and the ValidationError text isn't displayed at all - thus giving the admins no information on what actually went wrong. Does anyone know why the ValidationError message isnt being displayed in the admin, and what steps we can take to rectify this? -
TypeError at /admin/jobs/job/add/ 'tuple' does not support the buffer interface
Actually i am just making a simple blog in Django2.0.2 where i can upload my recent jobs in which i can upload a image and a summary! My Jobs model looks like this: ` from django.db import models class Job(models.Model): image = models.ImageField(upload_to='images/') summary = models.CharField(max_length=200)` And i also edited the settings to which the image should be saved: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media'), MEDIA_URL ='/media/' the admin.py of the app looks like: from django.contrib import admin from .models import Job admin.site.register(Job) Please help What should i do to fix this and upload a pic and summary successfully! -
how do I use django GROUPs correctly via extending this model to another model
I am building an ERP system and at some point I have created a class Designations that inherits from django groups and is shown below: I intend to use the designations to categorize users with permissions to do certain actions within the system. I am not sure where this method that I have implemented is a proper. I really need suggestions on how to use the inbuilt django GROUP to classify user(employee) designations and permissions. Can I also use django GROUPS for DEPARTMENTS? class Department(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Designation(Group): class Meta: proxy = True db_table = 'main_designation' verbose_name = 'designation' verbose_name_plural ='designations' -
How to connect Django with Apache server in windows for web application?
When I am trying to install apache module by using mod_wsgi in windows, It produces some error like **Command "python setup.py egg_info" failed with error code 1 in d:\users\dhanasekaranm\appdata\local\temp\pip-build-imiilg\mod-wsgi** Help me to rectify this error. Thanks in Advance.. -
In django and redis, How can I set cache permanently?
I'm using django and django-redis: https://niwinz.github.io/django-redis/latest There is permanent cache(which means that not be deleted by timeout) in cache argument(: https://docs.djangoproject.com/en/2.0/topics/cache/#cache-arguments) and fragment cache document(: https://docs.djangoproject.com/en/2.0/topics/cache/#template-fragment-caching). But in per-view cache document(: https://docs.djangoproject.com/en/2.0/topics/cache/#the-per-view-cache), I can't find out anything about permanent cache. Is it okay if I use permanent cache as below? @cache_page(None, key_prefix="site1") def my_view(request): ... or urlpatterns = [ path('foo/<int:code>/', cache_page(None)(my_view)), ] -
How to code a django site efficiently while accessing database using MySQLdb?
Now i am developing a website in django. But i used MySQLdb to connect with the database instead of django ORM since django ORM doesn't support multiple keys. I will explain my question with a example, consider i am writing a dictionary to database having type longtext. Hence i have used json.dumps() method to write database. I am reading those field using another url, hence while coding view function for reading i have used json.loads() method to get the dictionary back and here is my question arise. Whether i need to handle the exception when database field hold a non json string. If database field hold a non json string json.loads() will produce ValueError. Whether i need to catch those type of error since chance of having database with non json string is very little. -
Django form do nothing on hosting?
I have form in my django app, that send_email in ajax. But when i have deployed this on my hosting, it doesn't react for submit... i even dont understand how i can debug it. I have remove function send_mail and just trying to make redirect or even just HttpResponse to submit, but when clicking submit it doest work and dont showing any errors to my console.. Here is code: forms.py from django import forms class ContactForm(forms.Form): user_name = forms.CharField(label='name', max_length=128, required=True) email = forms.EmailField(label='Email', max_length=128, required=True) subject = forms.CharField(label='subject', max_length=128, required=True) message = forms.CharField(label='message', widget=forms.Textarea, required=True) views.py from django.shortcuts import render, HttpResponse, redirect from .forms import ContactForm def contacts(request): form = ContactForm(request.POST or None) if form.is_valid(): user_name = request.POST.get('user_name', '') email = request.POST.get('email', '') subject = request.POST.get('subject', '') message = request.POST.get('message', '') return HttpResponse('Success!') ctx = { 'form': form, } return render(request, 'contacts.html', ctx) contacts.html <form method="post" id="contact-form"> {% csrf_token %} {% bootstrap_form form %} <div class="form-group"> <input type="submit" class="btn button"> </div> </form> Sorry for bad english.