Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ensure that there is at least one instance of my nested serializer in Django Rest Framework for creation?
Rather than a long explication, some code : My main serializer OrderSerializer and the nested serializer OffersSerializer: class OffersSerializer(serializers.Serializer): id = serializers.IntegerField(min_value=0) quantity = serializers.IntegerField(min_value=0) class OrderSerializer(serializers.Serializer): offers = OffersSerializer(many=True, required=True) With that I can POST data like this : { "offers": [] } This is valid for DRF, but I would like to check there is at least one offer, so for example: { "offers": [{"id": 1, "quantity": 200}] } How can I ensure that there is at least one offer ? Thank you -
Displaying ManyToManyField in Django Detail Generic View
In my Django project I have two models - Program and Cycle - which are linkedin by a ManyToMany Relationship, so that one program can have many cycles and at the same time cycles can be part of many different programs. From a Generic List View, the user can select one program and access the Detail View of that programs, where I am supposed to show all the cycles included in the selected program. views.py class AllProgramsView (generic.ListView): template_name = 'programs/index.html' context_object_name = 'programs_list' def get_queryset(self): return Program.objects.all() class ProgramDetailView (generic.DetailView): model = Program template_name = 'programs/program.html' #defining the variabile sp, selected program sp = Program.objects.get(self.id) def get_queryset(self): return sp.cycles.all() in models.py class Cycle(models.Model): cycle_name = models.CharField(max_length=150) cycle_description = models.CharField(max_length=250) steps = models.ManyToManyField(Step) def __str__(self): return self.cycle_name + " -- " + self.cycle_description class Program(models.Model): program_name = models.CharField(max_length=50) program_description = models.CharField(max_length=250) cycles = models.ManyToManyField(Cycle) is_favourite = models.BooleanField(default="False") def get_absolute_url(self): return reverse('programs:program', kwargs={'pk': self.pk}) def __str__(self): return self.program_name In the html template, program.html <div class="bg-white"> <div class="container text-center text-muted"> <div class="row"> {% if sp %} {% for cycle in cycles %} <div class="col-sm-4 py-4"> <div class="card"> <p><h5>{{ cycles.cycle_name }}</h5></p> <p class="card-text">{{ cycles.cycle_description }}</p> <a href="" class="btn btn-secondary">Modify it</a> </div> {% endfor … -
Getting error while generating the unique id using Python
I am getting some error while generating the unique id using uuid in Python. I am explaining those error below. Error: Exception Type: TypeError Exception Value: coercing to Unicode: need string or buffer, UUID found I am explaining my code below. import uuid filename='+uuid.uuid4()+'.csv' Here I need to put the file name as some unique id but getting the above error. Please help me to resolve this error. -
How can I judge the object if is exists in the templates?
In the template: <h4> {% if data.wine_one %} {{ data.wine_one.title }} {% elif data.news_one %} {{ data.news_one.title }} {% endif %} </h4> I promise the data.wine_one is exists, because in the views.py I have print out it. But in the templates it do not shows up the data.wine_one.title, and I use the data.wine_one != None can not judge it too. -
Edit groups in user edit form in Django
I not use admin apps in django, and i want to edit the user with form, but when i edit the groups to the users, django doesnt save my choice and user have no groups. Views.py def useredit(request, pk): user = get_object_or_404(User, pk=pk) if request.method == "POST": form = EditUserForm(request.POST, instance=user) if form.is_valid(): user.save() messages.success(request, 'Utilisateur édité avec succés !') return HttpResponseRedirect('/user') else: form = EditUserForm(instance=user) return render(request, 'compta/users/edit.html', {'form': form}) Form.py class EditUserForm(UserChangeForm): class Meta: model = User fields = '__all__' def save(self, commit=True): user = super().save(commit) self._save_m2m() return user Thanks. -
How download file and save it inside the upload folder using Django and Python
I need some help. I am trying to write the content in CSV file and Here I need to download that file and save that same file into upload folder. I am explaining my code below. if request.method == 'POST': param = request.POST.get('param') report = Reactor.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+uuid.uuid4()+'.csv' writer = csv.writer(response) writer.writerow(['Name', 'Status', 'Date']) for rec in report: if rec.status == 1: status = 'Start' if rec.status == 0: status = 'Stop' if rec.status == 2: status = 'Suspend' writer.writerow([rec.rname, status, rec.date]) #return response u = urllib.URLopener() f = u.open(param) open("down.txt","w").write(f.read()) pers = User.objects.get(pk=request.session['id']) root = [] user_name = pers.uname count = 1 root.append( {'username': user_name, 'count': count }) return render(request, 'plant/home.html', {'user': root, 'count': 1}) Here I am setting the database values inside one CSV file and that file is named as unique id. Here I need to save that file inside Upload folder and that folder path will set inside settings.py file and also same file will be downloaded as well. Please help me. -
HTTP 400 error on server side? (Django and React)
I'm getting 400 HTTP errors in server(Django RESTful Framework). I guess I put the wrong headers in axios post? I didn't have any problem with testing api with Postman. What's wrong with this axios post request? Error: Request failed with status code 400 at createError (createError.js:16) at settle (settle.js:18) at XMLHttpRequest.handleLoad (xhr.js:77) at XMLHttpRequest.dispatchEvent (event-target.js:172) at XMLHttpRequest.setReadyState (XMLHttpRequest.js:538) at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:381) at XMLHttpRequest.js:485 at RCTDeviceEventEmitter.emit (EventEmitter.js:181) at MessageQueue.__callFunction (MessageQueue.js:260) at MessageQueue.js:101 export const doAuthLogin = ({ username, password }) => async dispatch => { axios.post(`${ROOT_URL}/rest-auth/login/`, { username, password }).then(response => { console.log(response); // Save Token post is Already await. AsyncStorage.setItem('auth_token', response.token); dispatch({ type: AUTH_LOGIN_SUCCESS, payload: response.token }); }) .catch(response => { console.log(response); dispatch({ type: AUTH_LOGIN_FAIL, payload: response.non_field_errors }); }); }; Thanks -
got an unexpected keyword argument 'pk' on genric view
I am trying to use Built-in UpdateView & DeleteView, And I am keep getting TypeErrors, with the Exception Value: get() got an unexpected keyword argument 'pk' views.py class SeqRunUpdate(LoginRequiredMixin, UpdateView): form_class = Sequencing_RunsForm model = Sequencing_Runs class SeqRunDelete(LoginRequiredMixin, DeleteView): model = Sequencing_RunsForm success_url = reverse_lazy('seq_run-private') urls.py url(r'^private/Samples/(?P<pk>[0-9]+)/$', views.SampleUpdate.as_view(), name='sample-update'), url(r'^private/Samples/(?P<pk>[0-9]+)/del$', views.SampleUpdate.as_view(), name='sample-delete'), models.py class Sequencing_Runs(models.Model): seq = models.CharField (max_length=250, unique=True, verbose_name='Sequence') date= models.DateField (auto_now=False, verbose_name='Date') classifaction = models.IntegerField(choices=CLASSIFACTION_CHOICES, default=1) def get_absolute_url(self): return reverse('table:seq_run-add') def __str__(self): return self.seq Template <td><form action="{% url 'table:seq_run-update' seq.pk %}" method="get" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-edit"></span> </button> </form></td> <td><form action="{% url 'table:seq_run-delete' seq.pk %}" method="get" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-trash"></span> </button> </form></td> -
Django serializing objects with GenericForeignKey
I am attempting to integrate GenericForeignKeys for my Order object, however I run into the problem of serializing this data. I can store either object A or object B as foreign key. I am getting data with the PK of the object and what type/model it is. The model: class Order(models.Model): .... product_id = models.PositiveIntegerField() product_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) product = GenericForeignKey('product_type', 'product_id') I have this serializer: class ProductRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, A): serializer = ASerializer(value) elif isinstance(value, B): serializer = BSerializer(value) else: raise Exception() return serializer.data class OrderSerializer(serializers.ModelSerializer): .... product_id = serializers.IntegerField() product_type = ProductRelatedField(read_only=True) So the primary key is there, and I will have store a ContentType object on the project, which will be an instance of either A or B. However, I will have to put a queryset parameter or read_only=True on this field. Point is that the queryset is unknown (because it could be from either object), and read_only results in the field being excluded in when creating the object. How should this be solved? -
serialization issue in django
i am new to django and i an trying to add serialized responses following is my models.py class Student(models.Model): name = models.CharField(max_length = 50) degree = models.CharField(max_length = 50) numofsubs = models.IntegerField() namesofsubs= models.CharField(max_length = 50) details = models.CharField(max_length = 50) class Meta: db_table = "student" here is my serializer.py from rest_framework import serializers from models import Student class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('name' ,' degree',' numofsubs' , 'namesofsubs', 'details') following is my code for views.py def addStudent(request): if request.method == 'POST': serializer = StudentSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) def getAllStudents(request): objects = Student.objects.all() serializer = StudentSerializer(objects, many=True) return Response(serializer.data) i have added 'rest_framework' in INSTALLED_APPS in setting.py now when ever i hit the url to add new student ar to get a list of all the students server gives Server Error(500) in response. Any help would be appriciated -
init MultipleChoiceField with queryset
In django 1.9 i can init MultipleChoiceField with forms.py class MyForm(forms.Form): city = forms.MultipleChoiceField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].choices = City.objects.values_list('id', 'name') self.initial['city'].initial = \ City.objects.filter(some_flag=True).values_list('id', flat=True) In django 1.11 it doesn't work because I have to put tuple or list on Queryset self.initial['city'].initial = \ list(City.objects.filter(some_flag=True).values_list('id', flat=True)) I found out, that django.forms.widgets has new class ChoiceWidget with method format_value def format_value(self, value): """Return selected values as a list.""" if not isinstance(value, (tuple, list)): value = [value] return [force_text(v) if v is not None else '' for v in value] Why? In my opinion checking Iterable is better way, def format_value(self, value): """Return selected values as a list.""" from collections import Iterable if not isinstance(value, Iterable): value = [value] return [force_text(v) if v is not None else '' for v in value] So solution 1: put list() on queryset with values_list('id', flat=True) solution 2: monkey patching Widget for MultipleChoiceField Or somebody knows another solution? PS. Yes, I know, that ModelMultipleChoiceField exists but I have above logic for many fields and don't want refactor all code now. -
Syncronize website page to another website
Suppose, My website names are 'x','y','z' and 'django-cms' . x,y,z websites have home page . Now I want to create home page from django-cms wesite and connect to this home page to any of my website how can i do that. for example one user creates a home page through djagno-cms and this page should be reflacted in 'x' website's home page. anothour user create a home page through djano-cms and this page should be refalcted in 'y' website's home page. -
Django integration with onlyoffice
I am trying to integrate onlyoffice with my Django UI. I have hosted community server on my local network 192.168.2.103. script is follows for opening the doc: <script type="text/javascript"> config = { "document": { "fileType": "docx", "key": "apiwhV2mE0Z44ImHxbibRMdwd_", "title": "Example Document Title.docx", "url": "https://d2nlctn12v279m.cloudfront.net/assets/docs/samples/demo.docx", }, "documentType": "text", "editorConfig": { "callbackUrl": "http://192.168.2.103/url-to-callback.ashx" } }; window.docEditor = new DocsAPI.DocEditor("placeholder", config); </script> My question is : Unable to open my local document in onlyoffice ui which is available on "http://localhost:8000/static/mydoc.docx" while "https://d2nlctn12v279m.cloudfront.net/assets/docs/samples/demo.docx" is working fine. (both the docs are downloadable from link) What is the use of "key" and how to find or generate it ("key": "apiwhV2mE0Z44ImHxbibRMdwd_"). How I will integrate the doc which is created on my server (192.168.2.103). Unable to get the direct file link for it. How i will control its editing if it it shared with some specific only office users on my portal. -
if only can I block the green nav (use the `{% block %}`), then can get the effect?
You see the green nav is a div, on it there are several items. Now all the templates contains the green nav. When the page is index/, the first item is selected, when the page is productlist/ the second item is selected. realize the effect is by css(like <li class="on"><a href="/index/" name="index">网站首页</a></li>). Now, if only can I block the green nav (use the {% block %}), then can get the effect? If do not use the block, if should every template contains the green nav code? -
django + own database switch MySQL error
Hello Im changed my database in settings.py from default sqlite to mysql and I got problem. I installed mysqlclient, mysql-python on virtualenv and it's doesnt work My example database connection DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'dev.website.eu', 'USER': 'name', 'PASSWORD': 'password', 'NAME': 'database_name', }, 'sqlite': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } When I changed database i got a error in terminal django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: libmysqlclient.so.20: cannot open shared object file: No such file or directory. Did you install mysqlclient or MySQL-python? Anyone know how to change that error? If I put those data in mysql-connector it's work but when I want connect via settings.py it doesnt work -
Django get_absolute_url queries
I use get_absolute_url in a sitemap template. Not the sitemap.xml, but a page in the site layout displaying all links. I basically get all page objects, and iter over them in the template, using get_absolute_url. I discovered that for every link the database is hit one time. How do I reduce the queries? I thought of two solutions, but I don't know which way is the best: use the sitemap framework from Django. I know the sitemap framework uses the get_absolute_url as well. I was not able to check the amount of queries when a sitemap.xml is generated (debug toolbar doesn't show up). write a custom save method, and save the url in the database, using get_absolute_url -
Django 1.11 How to display template variable from within HTML saved in model for CMS Site
Within a template, I need to render a {{ variable }} from HTML content saved in a model instance. Below are the stripped down parts of the code. page.html {% load static %} <html> <head> <styles, links, etc.> <title>{{ object.title }}</title> </head> <body> <div>{{ object.html_content }}</div> </body> </html> Model class Page(models.Model): title = models.CharField(max_length=30) html_content = models.TextField() GlobalMixin # Used site wide for Global information. class GlobalMixin(object): def get_context_data(self, *args, **kwargs): context = super(GlobalMixin, self).get_context_data(*args, **kwargs) context['variable'] = "A Global piece of information" return context View from .mixins import GlobalMixin from .models import Page PageView(GlobalMixin, generic.DetailView): model = Page template_name = "my_app/page.html" def get_context_data(self, *args, **kwargs): context = super(PageView, self).get_context_data(*args, **kwargs) return context Admin & HTML Content Field I then enter admin, add new Page, enter my HTML content into html_content Field "Html Content" as per the following example. <p>This is {{ variable }} that I need to display within my rendered page!</p> Then SAVE. BROWSER RESULTS This is {{ variable }} that I need to display within my loaded page! I know there is Django Flat Pages, but it doesn't look like it works for me as I require Global variables in my templates that flat pages doesn't offer. … -
How to use multiple form in one view in django
I am new in django.I created two models. class article(models.Model): title = models.CharField(max_length=250) disc = models.TextField() posted = models.DateTimeField(auto_now_add=True, editable=False) updated = models.DateTimeField(auto_now=True) cat = models.CharField(max_length=100) class category(models.Model): cat_id = models.ForeignKey(article, on_delete=models.CASCADE) cate = models.CharField(max_length=100) I want to create a form template where user select category in drop down list and then write title, disc etc and submit form.when form is submit the data should save in article model and the selected category also save in cat field in article model. What can i do ? please give me proper and easy way to do this. -
Django file upload using Form
Hy there, my first question on this website, so sorry for my english. So i try to upload a file on a model in Django framework. class banner(models.Model): #id is made by Django name = models.CharField(max_length=255) created_by = models.CharField(max_length=255) company = models.CharField(max_length=255) register_date = models.DateField(auto_now_add=True) file = models.FileField(null=True, blank=True) file_name = models.CharField(max_length=255) this is the model class BannerForm(forms.Form): name=forms.CharField(max_length=255) created_by=forms.CharField(max_length=255) company=forms.CharField(max_length=255) data_type=forms.CharField(max_length=255) register_date=forms.DateField() file=forms.FileField() file_name=forms.CharField(max_length=255) this is the form def add_form(request): form=BannerForm() last=models.banner.objects.all().last() if request.method == "POST": form = forms.BannerForm(request.POST, request.FILES or None) if form.is_valid(): form.cleaned_data['created_by'] new_banner=models.banner() new_banner.id=last.id+1 new_banner.name=form.cleaned_data['name'] new_banner.register_date=form.cleaned_data['register_date'] new_banner.company=form.cleaned_data['company'] new_banner.file=form.cleaned_data['file'] new_banner.file_name=new_banner.file.name new_banner.created_by=form.cleaned_data['created_by'] new_banner.save() return render(request, "add_banner.html",{"form":form}) this is the view.Now every time i try to add a banner.I browse the file, but after i push submit, it is that the file must be chose, like it don't recongnize what i browse to the form button.Any suggestion? -
Django - can't do migrations, MySQL 5.7.19, Py 3.6.2
Help I'm stuck in Django hell! I'm trying to learn Django and I'm trying to set up a test site on my own computer (MacOS 10.12.6). My version of Python is 3.6.2 with Django 1.11.4 and MySQL 5.7.19. I am at the point where I want to do: python manage.py migrate BUT... it doesn't work... I have installed mysql-connector 2.1.6 and that particular version seems to have a bug which is documented here. The error posted looks like mine. MySQL said the bug was fixed in version 2.1.7, but I can't download that with pip and I don't see it anywhere. The only other version higher that pip sees is 2.2.3 and that doesn't install at all. I found other instructions that suggested using mysqlclient (and here), but even that doesn't work. I get this error... pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/d9/z3yxpfl505s_jwtty_x3576h0000gn/T/pip-build-8vj20eqa/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/d9/z3yxpfl505s_jwtty_x3576h0000gn/T/pip-build-8vj20eqa/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/d9/z3yxpfl505s_jwtty_x3576h0000gn/T/pip-build-8vj20eqa/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config … -
How reorder list items by drag and drop?
In my Django project I show list of books. I am trying to reorder list items by drag and drop. I use next code below but it raise error. Can someone help me to fix it? I am confused. My aim: Change position field's value when user drag and drop list item. models.py: class Book(models.Model): title = models.CharField(max_length=200, help_text='Title', blank=False) position = models.IntegerField(help_text='Position', default=0, blank=True) class Meta: ordering = ['position', 'pk'] urls.py: url(r'^book/sorting/$', BookSortingView.as_view(), name='book_sorting') JS: $("#books").sortable({ stop: function(event, ui) { book_order = {}; $("#books").children().each(function(){ book_order[$(this).data('pk')] = $(this).index(); }); $.ajax({ url: "{% url 'book_sorting' %}", type: "post", contentType: 'application/json; charset= utf-8', dataType: 'json', data: JSON.stringify(book_order), }); } }); views.py: (P.S. I use the mixins of django-braces app) class BookSortingView(CsrfExemptMixin, JsonRequestResponseMixin, View): def post(self, request): for pk, position in self.request_json.items(): Book.objects.filter(pk=pk).update(position=position) return self.render_json_response({'saved': 'OK'}) ERROR: P.S. It seems to me that problem is in this line: Book.objects.filter(pk=pk).update(position=position) in views Traceback (most recent call last): File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/envs/Project/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/srv/envs/Project/lib/python3.6/site-packages/django/utils/decorators.py", line 67, in _wrapper return … -
What kind of search should be used
I'm working on a online store using Django, the question is simple, for a simple model named Product with "name" and "description" fields, should I try a full text search using PostgreSQL or a simple query using "icontains" field lookup? -
Invalid block tag on line 9: 'static', expected 'empty' or 'endfor'. in the Django Block
I use the templates inherit with block: I copy the index.html to base.html: And add the block to the main content: So the base.html is this: <!DOCTYPE html> <html lang="zh-cn"> <head> <title>{{ data.info.winery_name }}</title> <meta charset="UTF-8"> {% load static %} <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="format-detection" content="telephone=no"> <meta name="renderer" content="webkit"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"> <meta http-equiv="Cache-Control" content="no-siteapp" /> <link rel="alternate icon" type="image/png" href="{% static 'images/favicon.png' %}"> <link rel='icon' href='favicon.ico' type='image/x-ico' /> <meta name="description" content="" /> <meta name="keywords" content="" /> <link rel="stylesheet" href="{% static 'css/default.min.css' %}" /> <!--[if (gte IE 9)|!(IE)]><!--> <script type="text/javascript" src="{% static 'lib/jquery/jquery.min.js' %}"></script> <!--<![endif]--> <!--[if lte IE 8 ]> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <script src="http://cdn.staticfile.org/modernizr/2.8.3/modernizr.js"></script> <script src="{% static 'lib/amazeui/amazeui.ie8polyfill.min.js' %}"></script> <![endif]--> <script type="text/javascript" src="{% static 'lib/handlebars/handlebars.min.js' %}"></script> <script type="text/javascript" src="{% static 'lib/iscroll/iscroll-probe.js' %}" ></script> <script type="text/javascript" src="{% static 'lib/amazeui/amazeui.min.js' %}"></script> <script type="text/javascript" src="{% static 'lib/raty/jquery.raty.js' %} "></script> <script type="text/javascript" src="{% static 'js/main.min.js?t=1' %}"></script> </head> <body> <header> <div class="header-top"> <div class="width-center"> <div class="header-logo "><img src="{% static 'images/logo.png' %}" alt=""></div> <div class="header-title div-inline"> <strong>{{ data.info.winery_name }}</strong> <span>{{ data.info.winery_pinyin }}</span> </div> <div class="header-right"> <span>全国咨询热线</span> <span>{{ data.info.country_tel }}</span> </div> </div> </div> <div class="header-nav"> <button class="am-show-sm-only am-collapsed font f-btn" data-am-collapse="{target: '.header-nav'}">Menu <i class="am-icon-bars"></i></button> <nav> <ul class="header-nav-ul am-collapse am-in"> <li class="on"><a href="/index/" name="index">网站首页</a></li> <li><a href="/product/" name="show">经营酒类</a></li> … -
django urlpatterns - reverse hits wrong url
I am still working with the polls app, but made a few changes to allow multiple questions to be answered on each page with a common 'submit' button. After these changes, a weird bug emerged. view.index is a simple list of questions, with links to a link-redirect view that just captures username and then loads a page with the questions and that users data. (might not be the best way, but it was working). class IndexView(generic.ListView): template_name = 'polls/_index.html' context_object_name = 'question_set' def get_queryset(self): return Question.objects.filter(man_index__gte='1').order_by('man_index') @login_required(redirect_field_name=None) def qlink(request, man_index): user_id = request.user.username question = get_object_or_404(Question, man_index = int(man_index)) page_ref = question.man_page return HttpResponseRedirect(reverse('polls:page', args=(user_id, page_ref))) The bug first emerged with the redirect throwing a 'user not identified' after trying to load a url that was polls//, but it had not hit the 'qlink' view at all - instead the error was coming from views.answer, the view that handles the answers. From my urls.py: app_name = 'polls' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^qlink/(?P<man_index>[0-9]+)/$', views.qlink, name='qlink'), url(r'^(?P<man_index>[0-9]+)/results/$', views.results, name='results'), url(r'^analytics/(?P<question_id>[0-9]+)/(?P<n>[0-9]+)/$', views.analytics, name='analytics'), url(r'^hashtags/(?P<question_id>[0-9]+)/$', views.page_hashtag_detail, name='hashtags'), url(r'download/$', views.write_out, name = 'download'), url(r'^(?P<user_id>\w+)/pg(?P<page_num>[0-9]+)/$', views.pageView, name='page'), url(r'^(?P<user_id>\w+)/$', views.answer, name='answer'), #url(r'^(?P<user_id>\w+)/(?P<man_index>[0-9]+)/short_answer/', views.short_answer, name='short_answer'), #url(r'^(?P<user_id>\w+)/(?P<man_index>[0-9]+)/vote/', views.vote, name='vote'), #url(r'^(?P<user_id>\w+)/(?P<man_index>[0-9]+)/long_answer/', views.long_answer, name='long_answer'), url(r'^charts/contribution$', views.contribution_chart, name='contribution_chart'), url(r'^(?P<user_id>\w+)/(?P<man_index>[0-9]+)/answer_delete/', views.answer_delete, … -
Render radio buttons without UL in Django 1.11
I need to render a radio button group without UL. In Django 1.9, I used this answer, and I use this in many places. I'm upgrading to Django 1.11, and RadioFieldRenderer is no longer supported. How can I accomplish what I'm doing right now in Django 1.11?