Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: Cannot import name 'DurationField'
I am trying to run an application that uses django (version 1.6.5) rest framework ( python version 3.4.5 ) .However am getting the import error "cannot import name DurationField".How do i resolve this error ? File "/usr/src/app/Lab/models.py", line 8, in from Lab import logic, common File "/usr/src/app/Lab/logic.py", line 16, in from Rest import viewsAppComm File "/usr/src/app/Rest/viewsAppComm.py", line 7, in from rest_framework.response import Response File "/usr/local/lib/python3.4/site-packages/rest_framework/response.py", line 13, in from rest_framework.serializers import Serializer File "/usr/local/lib/python3.4/site-packages/rest_framework/serializers.py", line 19, in from django.db.models import DurationField as ModelDurationField ImportError: cannot import name 'DurationField' -
Gunicorn giving syntax error for my configuration file
my config file [loggers] keys=root, gunicorn.error, gunicorn.access [handlers] keys=console, error_file, access_file [formatters] keys=generic, access [logger_root] level=INFO handlers=console [logger_gunicorn.error] level=INFO handlers=error_file propagate=1 qualname=gunicorn.error [logger_gunicorn.access] level=INFO handlers=access_file propagate=0 qualname=gunicorn.access [handler_console] class=StreamHandler formatter=generic args=(sys.stdout, ) [handler_error_file] class=logging.FileHandler formatter=generic args=('/tmp/gunicorn.error.log',) [handler_access_file] class=logging.FileHandler formatter=access args=('/tmp/gunicorn.access.log',) [formatter_generic] format=%(asctime)s [%(process)d] [%(levelname)s] %(message)s datefmt=%Y-%m-%d %H:%M:%S class=logging.Formatter [formatter_access] format=%(message)s class=logging.Formatter My command to execute gunicorn --env DJANGO_SETTINGS_MODULE=myproject.settings myproject.wsgi --log-level debug --log-file=- -c file:gunicorn_log.conf Getting this error Failed to read config file: gunicorn_log.conf Traceback (most recent call last): File "/home/jameel/django-env/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 93, in get_config_from_filename execfile_(filename, cfg, cfg) File "/home/jameel/django-env/local/lib/python2.7/site-packages/gunicorn/_compat.py", line 91, in execfile_ return execfile(fname, *args) File "gunicorn_log.conf", line 27 class=StreamHandler ^ SyntaxError: invalid syntax I was followed as per their example in github link -
How can I make image fit in div (django)?
I'm trying to make my uploaded image(MEDIA not STATIC) fit certain div element. It seems like I found a solution from here : How do I auto-resize an image to fit a div container But it doesn't work for me. The size of dive is different depending on the size of image uploaded. This is my css for img img { padding: 0; display: block; margin: 0 auto auto 0; max-height: 100%; max-width: 100%; } and part of html. <ul class="items col-3 gap"> {% for album in albums %} <li class="item thumb {{ album.day }}"> <figure> <div class="icon-overlay icn-link"> <a href="{{ album.get_absolute_url }}"><img src="{{ album.get_image_url }}" /></a> </div><!-- /.icon-overlay --> <figcaption class="bordered no-top-border"> <div class="info"> <h4><a href="{{ album.get_absolute_url }}">{{ album }}</a></h4> </div><!-- /.info --> </figcaption> </figure> </li><!-- /.item --> {% endfor %} </ul><!-- /.items --> How can I show my images with consistent size? Need your help -
Which one I have to use to read image in Django, StringIO or BytesIO?
I'm trying to compress the image file before uploading in my django application. I found nice code snippet site : https://djangosnippets.org/snippets/10460/ but It doesn't work in python3. I think the problem is about str or byte. Someone advise to use BytesIO instead of StringIO. So, I edit my code like this. from django.db import models from django.core.urlresolvers import reverse from django.utils import timezone from django.utils.text import slugify from django.core.files.uploadedfile import InMemoryUploadedFile from PIL import Image as Img from io import StringIO, BytesIO def upload_location(instance, file_name): return "{}/{}/{}/{}".format( "album", instance.day, instance.week, file_name ) class Album(models.Model): DAYS = ( ('Sun', '일요일'), ('Mon', '월요일'), ) name = models.CharField(max_length=50) description = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to=upload_location) day = models.CharField(max_length=3, choices=DAYS) week = models.IntegerField() slug = models.SlugField(unique=True, allow_unicode=True) date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['day', 'week'] def __str__(self): return "{} - {}주차".format(self.get_day_display(), self.week) def get_absolute_url(self): return reverse( "album:album_detail", kwargs={ "slug": self.slug } ) def save(self, *args, **kwargs): if not self.id: self.slug = self.slug + "주차" if self.image: img = Img.open(BytesIO(self.image.read())) if img.mode != 'RGB': img = img.convert('RGB') img.thumbnail((self.image.width/1.5,self.image.height/1.5), Img.ANTIALIAS) output = BytesIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.image= InMemoryUploadedFile( output,'ImageField', "%s.jpg" %self.image.name.split('.')[0], 'image/jpeg', output.len, None ) super().save(*args, **kwargs) But … -
How to send a variable field name in icontains on django
I want to search in a field given by user. I have this so far: def search_engine(model, given_field, text): # Stuff result = model.objects.filter(given_field__icontains=text) return result The "given_field" inside filter would be the parameter given in the function, which is a variable. -
How to move singup\signin templates into dropdown menu?
I have a fixed navigation and I want to add dropdown box where users can singup\in (as Twitter uses). I tried: # project/tempates/signup.html {% load i18n %} {% load account socialaccount %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ signupform.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> {% endblock %} # project/tempates/base.html # ... a lot of basic stuff <li class="dropdown"> <a class="dropdown-toggle" href="#" data-toggle="dropdown">Sign In <strong class="caret"></strong></a> <div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;"> {% include './signup.html' %} # ... rest stuff and in dropdown box I see just the text, link to signin, and the button for confirmation of the registration. There are no fields to enter email and passwords. As I understand, this is because no access to the form, what usually is a views' jobs. How can I get workable dropdown forms? -
How to pass off file uploads to a worker process when using FileField on a model in Django
I am trying to allow larger files (30MB) to upload to S3 from my Django app. I'm using Heroku and these larger file timeout before being uploaded. From all the research I have done I think that I need to have a custom FileUploadHandler. I created one and it is processing, but I can't figure out where to place the code for handing off the upload process to a worker. Here is my code: models.py from django.db import models from storages.backends.s3boto import S3BotoStorage import pdb import uuid from rq import Queue from worker import conn from django.core.files.uploadhandler import * from django.core.files.uploadedfile import TemporaryUploadedFile class QueueUploadFile(TemporaryFileUploadHandler): def __init__(self, *args, **kwargs): super(QueueUploadFile, self).__init__(*args, **kwargs) def new_file(self, *args, **kwargs): super(QueueUploadFile, self).new_file(*args, **kwargs) self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset, self.content_type_extra) def receive_data_chunk(self, raw_data, start): self.file.write(raw_data) def file_complete(self, file_size): self.file.seek(0) self.file.size = file_size return self.file def data_file_path(instance, filename): result = '_'.join(['%06d' % uuid.uuid4(), filename]).replace(" ","-") return result # Create your models here. class music(models.Model): def __str__(self): return self.title FILE_TYPE_CHOICES = [(1,'Single Song Sheet'), (2,'Songbook'), (3,'Teaching'), ] music_file = models.FileField(null=True, upload_to=data_file_path, storage=S3BotoStorage(location='music_files'), help_text='') file_type = models.IntegerField(null=False, choices=FILE_TYPE_CHOICES, default=1) Here is the view view.py @csrf_exempt @login_required def upload(request): if request.method == 'POST': request.upload_handlers.insert(0, QueueUploadFile()) form = UploadForm(request.POST, … -
'module' object is not subscriptable
here is very simplified version of my code , so pleas ignore syntax errors i have a helper function basically reading a row from database using django orm and doing some validation finally return it using a dictionary modVerify.py def verify(request): try : req = Request.objects.get(id=request.POST.get('id')) except : return({'stat':'er' , 'error':-12}) return({'stat':'ok' , 'req':req}) here is where i get the error when im trying to use this above app import modVerify.view def verify(request): result = modVerify.views.verify(request ) if(result['status'] == 'ok'): req = modeVerify['req'] else : print('ERROR !') here is my error TypeError at /api/verify 'module' object is not subscriptable Request Method: POST Request URL: site.com/api/verify Django Version: 1.9.7 Exception Type: TypeError Exception Value: 'module' object is not subscriptable Exception Location: /home/somedomain/project/api/views.py in verify, line 98 Python Executable: /usr/local/bin/python3 Python Version: 3.4.4 which points to this line req = modeVerify['req'] so why im getting this and is there a way around it or should i return row id back instead and read it again from database in the caller function ? -
DJANGO CMS - CHILD TEMPLATE NOT OVERRIDING BASE.html
here is my base.html after the header and before the footer here is my child template. the new block content and additional block are not being displayed on my page that has the child template set as its template -
AJAX Form won't update after being submitted
I have been toubleshooting an ajax request for a contact form. The form will load field errors with an ajax request, but it wont submit the form after the response. One thing to note is that I am trying to submit the form with a button outside the form tag, but even with one inside the tag it only submits once. My ajax script: $('#modal-form').submit(function(e) { e.preventDefault(); var form = $(this); $.ajax({ url: form.attr('action'), type: form.attr('method'), data: form.serialize(), success: function(data) { if (!(data['success'])) { // Here we replace the form, for the form.replaceWith(data['form_html']); $('#modal-form').off("submit"); } else { // Here you can show the user a success message or do whatever you need $('#myModal').modal("hide"); } }, error: function () { $('#error-div').html("<strong>Error</strong>"); } }); }); My form: {% load crispy_forms_tags %} <div class="container"> <!-- Modal --> <div class="modal fade container-fluid" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4><span class="glyphicon glyphicon-envelope"></span> Email Me</h4> <div id="success-div"></div> </div> <div class="modal-body"> <div class="row-fluid"> <div id="form"> <form id="modal-form" class="form-horizontal" method="POST" action="{% url 'emailme_success' %}"> {% csrf_token %} {% crispy emailme_form emailme_form.helper %} </form> </div> </div> </div> <div class="modal-footer"> <div id="error-div" class="pull-left"> </div> <button name="submit" type="submit" class="btn btn-success pull-right" id="modal-submit" … -
Django drf-nested-routers - model object has no attributed related field
I am creating an API using the drf-nested-routers application for Django Rest Framework. This application is a tracker where users have sessions and tasks. Each user can have three active tasks and can work on each of these tasks in a given session. My (abbreviated) models are: #models.py class User(models.Model): name = models.Charfield() class Task(models.Model): start_date = models.Datefield() task_title = models.Charfield() user = models.ForeignKey(User, on_delete=models.CASCADE) class Session(models.Model): session_date = models.Datefield() user = models.ForeignKey(User, on_delete=models.CASCADE) task_one = models.ForeignKey(related_name="task_one") task_one_attempts = models.IntegerField() task_two = models.ForeignKey(related_name="task_two") task_two_attempts = models.IntegerField() I have created the following (abbreviated) Serializers for these models: #serializers.py class TaskSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(many=False) class Meta: model = Task fields = ('start_date', 'task_title', 'user') class SessionSerializer(serializers.ModelSerializer): user = Serializers.StringRelatedField(many=False) class Meta: model = Session fields = ('session_date', 'user', 'task_one', 'task_one_attempts', 'task_two', 'task_two_attempts') class UserSerializer(models.ModelSerializer): sessions = SessionSerializer(many=True) tasks = TaskSerializer(many=True) sessions = SessionSerializer(many=True) class Meta: model = Users fields = ('name', 'sessions', 'tasks') I also have my views.py and urls.py set up to do the routing properly. I can navigate to the sessions and tasks API views just fine. However, whenever I try to navigate to the user view, it throws the following error: 'User' object has no attribute 'tasks'. What's really … -
Django - LOCALHOST missing despite other views working
BACKGROUND: Worked through Django's tutorial and created multiple views: /admin /app Currently having issues with "localhost:8000" despite localhost/app and localhost/admin views working (see below): CODE Folder Structure (virtualenv): main/ db.sqlite3 manage.py app/ _init_.py admin.py apps.py models.py tests.py views.py urls.py migrations/ _init.py main/ _init_.py settings.py urls.py wsgipy ../main/app/views.py: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the app index.") ../main/app/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] ../main/main/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^app/', include('app.urls')), ] ISSUES/QUESTIONS: localhost/app or localhost/admin shows a rendered page. However, "localhost:8000" does not show the original, django landing page (despite it working before). What am I missing? Do you recommend any other folder structure? From my understanding, it's poor-form to put /main/main in the location that it currently is. Do you have recommendations on a new folder structure? -
How to re-generate tables in Django
I'm new in Django. Here is how i do: Create app by : python manager.py startap test and i add serveral model, then execute: python manager.py maiemigrations python manager migrate It will generate tables automactilly. Then i dropped the table in database by: drop table table_name execute again: python manager.py makemigrations python manager.py migrate but there is no table generated in database, and i got the message "no changes detected", how should i do to have these table? Pls help me`` -
Django-tastypie: utf8 is incorrect
class ActionResource(ModelResource): class Meta: queryset = ActionInfo.objects.all() resource_name = 'action' def dehydrate(self, bundle): bundle.data['name'] = bundle.obj.name bundle.data['expect_time'] = bundle.obj.expect_time bundle.data['type'] = bundle.obj.type bundle.data['price'] = bundle.obj.price bundle.data['additional'] = bundle.obj.additional return bundle This code from resource.py. Charfields that have russian letters print incorrect, for example: name: "Солянка". I've added at the top of the resource.py: # -*- coding: UTF-8 -*- from __future__ import unicode_literals import sys reload(sys) sys.setdefaultencoding('utf-8') and return string from django models: class ActionName(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class ActionInfo(models.Model): name = models.ForeignKey(ActionName, related_name="title", on_delete=models.CASCADE, null=True, blank=True) expect_time = models.ForeignKey(ActionDuration, related_name="duration",on_delete=models.CASCADE, null=True, blank=True) type = models.ForeignKey(ActionType, related_name="type", on_delete=models.CASCADE, null=True, blank=True) available = models.NullBooleanField(null=True, blank=True, default=True) price = models.ForeignKey(ActionPrice, related_name="price", on_delete=models.CASCADE, null=True, blank=True) --------------------------------------------- returned json: { additional: " 280 г ", available: true, comments: null, discription: "", expect_time: null, id: 120, name: "Солянка", photo: "/images/83913-220-184-solyanka_2.jpg", rate: null, resource_uri: "/api/v1/action/120/", type: "Первые блюда", } Who knows how to fix it?) -
Unusual error when using Class-Based Views with Python3, Django Rest Framework, and Django 1.10
I've been in the process of running through the tutorials on Django Rest Framework to build a simple todo list app. When I transitioned from a function-based view to a class-based view, I started getting a stack trace to Django and all http calls started failing. I'm using virtualenv to isolate dependencies, and using Python 3.5.2. Anyone have any ideas about what's going on, or how to resolve this error? I'm chalking this up to a configuration error or a version mismatch, but I'm not sure where to start. Endpoint, in /views.py: from django.http import Http404 from list.models import List from list.serializers import ListSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class ListsView(APIView): """ List all lists. """ def get(self, request, format=None): lists = List.objects.all() serializer = ListSerializer(lists, many=True) return Response(serializer.data) ... Input: curl http://localhost:8000/lists/ Trace: Internal Server Error: /lists/ Traceback (most recent call last): File "<pwd>/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "<pwd>/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "<pwd>/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "<pwd>/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [29/Aug/2016 … -
Django return objects to HTML from view with queryset?
I trying to show some info in HTML from query set in Django. But I don't know the best way to do it. The idea is when I open the page this show me the name of user and the competitions related with it. The user can create competition in admin of Django. My url is that. url(r'^home/(?P<company_name>\w+)', HomeView.as_view(), name='home'), The model. class Competition(models.Model): name = models.CharField(max_length=200,null=False) image = models.CharField(max_length=200, null=False) url = models.CharField(max_length=200, null=False) startingDate = models.DateTimeField(null=False) deadline = models.DateTimeField(null=False) description = models.CharField(max_length=200, null=False) user = models.ForeignKey(User, null=False) In views.py class HomeView(ListView): model = User, Competition template_name = 'home.html' context_object_name = 'company' def get_queryset(self, **kwargs): company = self.kwargs['company_name'] try: queryset = User.objects.filter(username__exact=company).get() except User.DoesNotExist: queryset = None return queryset The code above return me the User, when I write in url something like this: http://127.0.0.1:8000/home/diego/ The HTML home show me the name of User for example: {% if company %} <div class="jumbotron"> <div class="container"> {{company.username}} </div></div> {% endif %} But, I need to show the competitions created by the User with a 'for' in HTML. I tried with chains return the two query set but I don't work it. Also this. queryset2 = Competition.objects.filter(user__username__exact=company).get() The get() show me the … -
Django doesn't load static files from S3
I finally made it to run 'python manage.py collectstatic' to upload staticfiles to my S3 bucket. But after running 'sudo service apache2 restart', my page doesn't load staticfiles although my S3 Bucket has 'static' directory including all static files. How can I solve this problem? I include static files like below : {% load compress %} {% load static from staticfiles %} {% compress css %} <link rel="stylesheet type="text/css" href ="{% static 'bower_components/.../bootstrap.css' % /} ... {% endcompress %} My settings.py is below: STATIC_URL = S3_URL + '/static/' # which is the path of the static directory included in my S3 Bucket STATIC_ROOT = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/'), ) Is there anything I'm missing now? -
Django ValueError: ModelForm has no model class specified
I have the following code which complains about the following error: ValueError: ModelForm has no model class specified. from django import forms from straightred.models import StraightredTeam from straightred.models import UserSelection class SelectTwoTeams1(forms.Form): campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1] currentCampaignNo = campaignnoquery[0].campaignno cantSelectTeams = UserSelection.objects.filter(campaignno=currentCampaignNo) currentTeams = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)) team_one = forms.ModelChoiceField(queryset = currentTeams) team_two = forms.ModelChoiceField(queryset = currentTeams) class SelectTwoTeams(forms.ModelForm): used_his = forms.ModelMultipleChoiceField(queryset=UserSelection.objects.filter(user__id=1)) def __init__(self, user, *args, **kwargs): super(SelectTwoTeams, self).__init__(*args, **kwargs) self.fields['used_his'].queryset = User.objects.filter(pk = user.id) Any help would be greatly appreciated. Many thanks, Alan. -
Making sense of Django templates folder structure
I'm sure someone have asked the same question. So hopefully you can point me to it. I have a problem with the default templates folder structure. I have a project 'mysite' and an app 'polls' in it. Now according to the documentation the templates for the polls app should be in mysite/polls/templates/polls/index.html for me, it should just be mysite/polls/templates/index.html or mysite/templates/polls/index.html The reason given is that if another app say 'books' has the same template index.html, django would get confused and choose the first one. But I don't get it. If you go by my way, the folders are logically arranged, then why use another structure so that the machines could understand. Shouldn't it be the other way around ? Its one of the quirky things you cannot get out of your head. -
How do I use python 3.4 with django 1.9 in my virtualenv?
I am trying to use python 3.4 in my django 1.9 app because python 3.5 is to new and doesn't work with packages that I need. I tried this virtualenv -p /usr/bin/python3.4 venv from here but when Itried that i got this error message The executable /usr/bin/python3.4 (from --python=/usr/bin/python3.4) does not exist How canI make this work? thanks -
Django admin panel showing users from a different django site
I worked on a django site 2 years ago, and I now started working on another django site. But when I go to the admin page of this new site and click on the users category, I see a whole bunch of users that were created from my previous django site? Why is this happening and how can I reset it so it doesn't show those? -
Upgrade django-allauth to newer version maintaining migration
I was using django alluth with django 1.7. Now we shifted to django 1.10, and and we need to upgrade django allauth to 0.27. I can do it by reinstalling the package with pip but I am concerned about the migration files already present there. What should be the ideal way to upgrade it to a new version without losing the migrations? -
django_content_type error in django seo2
I am working on a Django(1.8) project. I am trying to implement django-seo2. Integrated Travis CI on GitHub for continuous integration. I keep getting the following error on Travis: ProgrammingError: relation "django_content_type" does not exist On my local machine: python manage.py showmigrations account [ ] 0001_initial [ ] 0002_email_max_length admin [ ] 0001_initial auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 authtoken [ ] 0001_initial [ ] 0002_auto_20160226_1747 contenttypes [ ] 0001_initial [ ] 0002_remove_content_type_name payment [ ] 0001_initial profiles [ ] 0001_initial [ ] 0002_auto_20160610_1309 sessions [ ] 0001_initial sites [ ] 0001_initial socialaccount [ ] 0001_initial [ ] 0002_token_max_lengths [ ] 0003_extra_data_default_dict webpages (no migrations) If I migrate before implementing django-seo2 and then I migrate after implementing django-seo2 no error occurs. But if new database is used and after implementing django-seo2, I try python manage.py migrate , the same error occurs: django.db.utils.ProgrammingError: relation "django_content_type" does not exist -
Celery flower not recognising the worker
I am developing a django application where I have the following: My main application with celery Redis server Celery worker All of these 3 are on different machines. My main application pushes the task queue into redis server. Celery worker gets the task queue and performs the tasks. I also have a celery flower (monitoring tool for celery) running on my main application machine (1). My problem is that my celery doesn't recognise the worker. I know that my main application and redis is working alright because if I run worker locally, everything works fine. Celery just doesn't recognise the worker on another machine. Any idea whats going on? Please note that the only connection happening between worker and my main application is through my redis server. There is no other connection between my main application celery and my celery worker. I mean do I need any? or How? -
How could I use Django i18n/setlang without form select and submit button?
I need to render a language selector as an unordered list in Django such as: <ul> ... <li><a href="???">EN</a></li> <li><a href="???">FR</a></li> <ul> I'm using Django i18n/set_language without i18n_pattern and it works very well if I use the form below, given in the documentation: {% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go" /> </form> I'd like to continue using i18n/set_language, but with the <li> structure, without the form <select> and the submit button. Is it possible? How could I do this?