Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to access and print Binary string type data from DynamoDB using python?
I have put an item in AWS DynamoDB which is in Binary form . I mean my data is encrypted and when I try to access that data to print or assign then I am not able to dousing python import boto3 import base64 dynamodb = boto3.resource('dynamodb', region_name='us-west-2') table = dynamodb.Table('xyz') response = table.get_item( Key={ 'id': "2", } ) item = response['Item'] dec_otp=item['otp'] print(dec_otp) #not able to print a=dec_otp #not able to assign print(type(dec_otp)) print(item) output:- Traceback (most recent call last): File "aws_kms3.py", line 23, in <module> 'name': 'otp' File "/home/vinit/Desktop/kms/venv/lib/python3.6/site-packages/botocore/client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/vinit/Desktop/kms/venv/lib/python3.6/site-packages/botocore/client.py", line 586, in _make_api_call api_params, operation_model, context=request_context) File "/home/vinit/Desktop/kms/venv/lib/python3.6/site-packages/botocore/client.py", line 621, in _convert_to_request_dict api_params, operation_model) File "/home/vinit/Desktop/kms/venv/lib/python3.6/site-packages/botocore/validate.py", line 291, in serialize_to_request raise ParamValidationError(report=report.generate_report()) File "/home/vinit/Desktop/kms/venv/lib/python3.6/site-packages/botocore/validate.py", line 95, in generate_report error_messages.append(self._format_error(error)) File "/home/vinit/Desktop/kms/venv/lib/python3.6/site-packages/botocore/validate.py", line 112, in _format_error ', '.join(additional['valid_types'])) TypeError: __str__ returned non-string (type bytes) output2:- Traceback (most recent call last): File "aws_kms3.py", line 25, in <module> CiphertextBlob=bytes(base64.b64decode(dec_otp)) File "/home/vinit/Desktop/kms/venv/lib/python3.6/base64.py", line 80, in b64decode s = _bytes_from_decode_data(s) File "/home/vinit/Desktop/kms/venv/lib/python3.6/base64.py", line 46, in _bytes_from_decode_data "string, not %r" % s.__class__.__name__) from None TypeError: argument should be a bytes-like object or ASCII string, not 'Binary' output3:- Binary object is not itterable -
Tracking likes Django application
I am attempting to make a site that keeps track likes(pokes) on a table that appends the number of pokes by 1 for every click of the poke button.At the same time I want users to be able to who poked them and how many times that user has poked them. Here is my code. html: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <a href="/logout">Logout</a> <form action="/home" method="GET"> {% csrf_token %} <h1>Welcome! {{request.session.name}} People have poked you {{%for stick in pokes%}} {{stick.first_name}} {{%endfor%}} </h1> </form> </head> <body> <p>People who you may want to poke</p> <table> <thead><th>Name</th><th>Alias</th><th>Email Address</th><th>Poke History</th><th>Action</th></thead> {%for stick in poke%} <tr><td>{{stick.first_name}}{{stick.last_name}}</td> <td>{{stick.first_name}}</td> <td>{{stick.email}}</td> <td>{{stick.}}</td> <td><form action="/poke" method="POST"><button>Poke</button></form></td></tr> {%endfor%} </table> </body> Models -- coding: utf-8 -- from future import unicode_literals from django.db import models import bcrypt import re from datetime import * import datetime EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') NAME_REGEX = re.compile(r'^[aA-zZ\s]+$') # Create your models here. class UserManage(models.Manager): def validate(self, postData): errors = {} if len(postData['first_name']) < 2: errors["First name field can be left blank"]="first_name" elif not NAME_REGEX.match(postData['first_name']): errors["This is not a valid first name. Try again."]="first_name" if len(postData['last_name']) < 2: errors["Last name cannot be left blank"]="last_name" elif not NAME_REGEX.match(postData['last_name']): errors["This is not a valid last name. Try again."]="last_name" … -
OperationalError Could Not Connect To Server -- Django/Heroku/AWS/Postgres
Im having an odd problem when trying to run my website on my local machine. If I type in python manage.py runserver, I get the following error and my site won't load. I tried to restart my Postgres database on my local machine and restarted the computer but having the same problems. My site is built in Python/Django hosted on Heroku with files served via Cloudfront/AWS. System check identified 1 issue (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x072D7780> Traceback (most recent call last): File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\postgresql\base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on host "ec2-107-20-188-239.compute-1.amazonaws.com" (107.20.188.239) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", … -
Add current site's domain to template dirs
What is the correct way to prepend an extra, site-specific templates directory to the template dirs setting in Django? TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ <PREPEND SITE-BASED TEMPLATE DIR IN HERE> str(APPS_DIR.path('templates')), ], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] I obviously can't use Site.objects.get_current() in there. I could write my own template loader which uses it but is that "correct"? Or should I be using an extended version of the settings files or something? -
how to return redirect to previous page in Django after POST request
I'm coding a news website,in the detail news page ,there is a comment fountain,if people want to post comment they need to login first.And I want to make it that,after they login in successfully ,the page can return to previous news page. Here is my views.py: def newsDetailView(request, news_pk): news = News.objects.get(id=news_pk) title = news.title author = news.author_name add_time = news.add_time content = news.content category = news.category tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) comment_form = CommentForm(request.POST or None) if request.method == 'POST' and comment_form.is_valid(): comments = comment_form.cleaned_data.get("comment") comment = NewsComments(user=request.user, comments=comments, news=news) comment.save() return render(request, "news_detail.html", { 'title': title, 'author': author, 'add_time': add_time, 'content': content, 'tags': tags, 'category': category, 'all_comments': all_comments, 'comment_form': comment_form }) Here is my news_detail.html: {% if user.is_authenticated %} <form method="POST" action="">{% csrf_token %} <div class="form-group"> <label for="exampleFormControlTextarea1"><h5>评论 <i class="fa fa-comments"></i></h5> </label> <textarea id="js-pl-textarea" class="form-control" rows="4" placeholder="我就想说..." name="comment"></textarea> <div class="text-center mt-3"> <input type="submit" id='js-pl-submit' class="btn btn-danger comment-submit-button" value="Submit Comemmt"> </input> </div> </div> </form> {% else %} <span>Please Login or register first</span> <a class="btn btn-primary mb-5" href="{% url 'login' %}?next={{ request.path }}">登录</a> <a class="btn btn-danger mb-5" href="{% url 'register' %}?next={{ request.path }}">注册</a> {% endif %} And I have a login.html and register.html.They works very well. Anybody know how … -
Can't import from file of external library, Django
I have Django application. And I use dj_anonymizer as external library. I wonder why I cannot import anything from dj_anonymizer.command file. dj_anonymizer files tree: dj_anonymizer |-- dj_anonymizer | |-- __init__.py | |-- anonym_field.py | |-- anonymizer.py | |-- defaults.py | |-- register_models.py | |-- command.py Link to dj_anonymizer (GitHub) The 1st import works just fine. The 2nd import is not working __init__.py: from dj_anonymizer.register_models import AnonymBase # [1st] from dj_anonymizer.command import CommandAnonymize # [2nd] ... -
Different User proxy model per app in request object
Current situation I have 3 apps in my Django project: auth, polls and school. AUTH_USER_MODEL in my settings is auth.models.User, and it is shared between all apps. the login/ URL in urls.py is also shared between the 3 apps. What I need to do I want to add some methods only to the users of the school app. To do this, I created a school.models.User model with proxy = True meta. This model inherits from auth.models.User. Problem When a user logs in, request.user contains a "base" auth.models.User object, independently of which app the user is using. How can I populate request.user with a different user model, depending on the app? I tried using a custom Authentication Backend as suggested in Django - User proxy model from request, but I have no way to detect which app the user is using, so I can't seem to discriminate between polls and school in the authentication backend. -
Django doesn't send password rest email
I'm trying to make a password reset form and I added next urls: path('reset-password/', password_reset, name='reset_password'), path('reset-password/done/', password_reset_done, name='password_reset_done'), url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', password_reset_confirm, name='password_reset_confirm'), Also I added next lines to my settings.py file: EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'my_gmail_email@gmail.com' SERVER_EMAIL = 'my_gmail_email@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_gmail_email@gmail.com' EMAIL_HOST_PASSWORD = 'my_gmail_password' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I get all forms correctly and when I type in email of a user it shows that email with reset password link was sent but it doesn't. -
Single post page url django
I have a blog app in django and i want to make a template for each post but it is just not working . What can be the error Here's my code Views.py from django.shortcuts import render, render_to_response , get_object_or_404 from .models import Post # Create your views here. def index(request): posts=Post.objects.all() return render(request, 'Index.html', {"posts": posts}) def post(request, slug): print(slug) return render_to_response('post.html', {'post': get_object_or_404(Post, slug=slug)}) urls.py ... urlpatterns = [ path('post/(.*)', product_views.post), path('', product_views.index), path('admin/', admin.site.urls), ] -
ajax POST for data which contains an array with jQuery and Django
So I'm looking to take data for checkboxes which have been checked, and I'm pushing these values to an array: var interestedIn = []; $(":checked").each(function() { interestedIn.push($(this).val()); }); I'm then passing this array as data to be POSTED by ajax call with some other variables: $.ajax({ type: "POST", dataType: "json", url: "{{ request.path }}", data: { 'email': values['email'], 'name': values['name'], 'interestedIn': interestedIn } }) I'm trying to then access the interestedIn variable with a Django views.py file: if request.POST and request.is_ajax(): interestedin = request.POST.get('interestedIn') When printing the interestedin variable to inspect, this is coming back as None. Does anyone know how you post arrays and variables simultaneously? -
Receive "detail": "not found" for detail view with Django Rest Framework
I am trying to create an api using django rest framework. I need one view to list all items in the datatable and another view that outputs the data for an individual person based on their id. The list view works at 'api/bios/'. However, I receive the following error when adding an id to the url: HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } views.py from rest_framework.response import Response from rest_framework import status from rest_framework import generics, mixins from api.models import Playerbios from api.serializers import USASerializer class USAListView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'trackmanid' serializer_class = USASerializer def get_queryset(self): return Playerbios.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class USAView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'trackmanid' serializer_class = USASerializer def get_queryset(self): return Playerbios.objects.all() serializers.py from rest_framework import serializers from api.models import Playerbios class USASerializer(serializers.ModelSerializer): class Meta: model = Playerbios fields = '__all__' lookup_field = 'trackmanid' main/urls.py from django.contrib import admin from django.urls import path, include from api.views import USAView, USAListView urlpatterns = [ path('admin/', admin.site.urls), path('api/bios/', include('api.urls')), path('api/bios/<trackmanid>/', include('api.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', include('webapp.urls')), ] api/urls.py from django.conf.urls import url, include from .views import USAView, USAListView urlpatterns = … -
Django: Parsing data from multiple identical forms in one POST request
I have a basic form class form, and a page which generates multiple form with a single submit button (since every individual form is required). Everything works as intended. When a user clicks submit, all of the data from all of the forms is sent as a POST. This means, given form x3, the POST data can look something like: request.POST.getlist('number') = [1, ,,2] request.POST.getlist('animal') = ['dog', 'cat', 'pig'] request.POST.getlist('name') = ['charles',,,] I can restructure things so that this kind of information retrieval is easy, but then form-validation doesn't work too hot. Right now I'm doing something like this: submitted_forms = [] for ii in range(len(request.POST.getlist('number'))): tmp_values = {} for key in request.POST: if key != "csrfmiddlewaretoken": tmp_values[key] = request.POST.getlist(key)[ii] submitted_forms.append(Form(tmp_values)) # Validate all forms for form in submitted_forms: if form.is_valid(): form.save() This'll work great if things are all nice and clean, but it doesn't pop up w/ the validation messages (I believe it's because, in recreating the forms this way, I lose the association between the empty form the user is filling in and the form that gets posted). -
How to get pre-populated form using edit button
I'm trying to get a pre-populated form using "edit" button that i'm using in my table. I've tried everything but i'm not able to get pre-populated form. I'm using only one form to add as well as edit. this is my views.py edit function: def edit_row(request, rowid): item = get_object_or_404(Studentapp, id=rowid) print item if request.method=="POST": form = EntryForm(request.POST, instance=item) if form.is_valid(): post=form.save(commit=False) post.save() return HttpResponseRedirect(reverse('studentapp:index'),rowid.id) else: form=EntryForm(instance=item) return render(request, 'index.html',{'form':form}) This is the form that i'm using: <div class="modal fade" id="addform" role="dialog"> <div class="modal-dialog"> <div class = "modal-content"> <div class = "modal-header"> <button type = "button" class = "close" data-dismiss="modal">&times;</button> <h3 class="modal-title"><b>Add Student</b></h3> </div> <div class = "modal-body"> <form action = "{% url 'studentapp:addstudent' %}" id="addform" method = "POST"> {% csrf_token %} <div class = "form-group"> <label for = "your_name">Your name: </label> <input class = "form-control" id="new_name" type = "text" name="your_name" value="{{ current_name }}" placeholder="Enter your name"> </div> <div class="form-group"> <label for = "course_name">Course: </label> <input id="new_course" class = 'form-control' type = "text" name="course_name" value="{{ current_course }}" placeholder="Enter your course"> </div> <div class = "form-group"> <label for = "rollno">Roll No.: </label> <input id="new_rollno" type = "text" class = 'form-control' name="rollno" value="{{ current_roll }}" placeholder="Enter your roll number"> </div> <div class … -
ChartJS line chart drag and zoom
Is it possible to add drag and zoom on ChartJS? I would like to do something similar like here. Here is how I draw my line chart: <canvas class="square_margin_less" id="myChart" width="100" height="30" > </canvas> <script> new Chart(document.getElementById("myChart").getContext('2d'), { type: 'line', data: { labels: {{ data.labels|safe }}, datasets: [{ label: 'x', data: {{ data.x }}, borderColor: 'rgba(233,105,118,1)', }, { label: 'y', data: {{ data.y }}, borderColor: 'rgba(96,143,239,1)' }, { label: 'z', data: {{ data.z }}, borderColor: 'rgba(144,247,136,1)' }] }, }); </script> There is some way of personalizing this? -
Django: How to set a integer field max value based on Foreign Key atribute?
I have the following model: class Atividades_cumpridas(models.Model): id_atividade = models.ForeignKey(Atividade, on_delete=models.CASCADE) id_jogador = models.ForeignKey(Jogador, on_delete=models.CASCADE) pontos_xp_ganhos = models.IntegerField() def __str__(self): str = self.id_atividade.nome_atividade + ' - ' + self.id_jogador.nome_jogador return str and i want to set the pntos_xp_ganhos max value based on Atividade.pontos_XP_maximo. How can I do that and show the max value on the admin editing page? -
Apple iCloud authentication in django application
I want to set Django authentication with Apple iCloud. Is there any link for it. Help appreciated. Thank you. -
Django, filtering a foreign field in queryset array and adding it serializing it
I want to return a json in my response containing several fields, one of the fields is a Foreign Key to a model which I want to access its name property. I am unable to construct the filter query correctly as I am unable to access the obj2 while iterating over the array containing my model objects. Also how do I add treatment_name to serializers.serialize correctly? def get(self, request): try: user = request.user crisis_ = Crisis.objects.filter(user_crisis = request.user) json_to_send = [] crisis_treatment_list = [] # itertate over Crisis_ array and append crisis_treatment objects for cri in crisis_: cri_tret = Crisis_Treatment.objects.filter(crisis = cri.id) crisis_treatment_list.append(cri_tret) # itertate over crisis_treatment list and find treatment name and send back json for obj2 in crisis_treatment_list: **# Here is my problem and how to add treatment_name to my json response?** treatment_name = Treatment.objects.filter(pk= ????).order_by('-id')[0] print (treatment_name.name) json_to_send.append(serializers.serialize('python', (obj2), fields=('rating_VR','id','comment_VR','created', 'treatment.name????'))) return Response(json_to_send, status=200) except IntegrityError: return Response(status=500) Here are my Models: class Crisis_Treatment(models.Model): """ Relation table to connect crisis and treatment, holding the index of the treatment. """ crisis = models.ForeignKey(Crisis, on_delete=models.CASCADE) treatment = models.ForeignKey(Treatment, on_delete=models.CASCADE) created = models.DateTimeField(auto_now=True) rating_VR = models.IntegerField(default=5) comment_VR = models.CharField(default="", max_length=50) last_treatment_time = models.DateTimeField(default=datetime.now) class Treatment(models.Model): """ model to hold treatment … -
Editing a personal profile in Django
I am creating a web application that allows a users to edit certain fields on their personal profile. The application uses Django forms to update the information. When a users enters in the new information however, the user is sent back to their profile but, the information remains unchanged. Below is how I tried to implement the functionality. Form class UpdateProfile(forms.ModelForm): age = forms.IntegerField(required=False) height = forms.IntegerField(required=False) weight = forms.IntegerField(required=False) class Meta: #Here are the fields that i want editable model = User fields = ('age', 'height', 'weight') Views def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('account/profile.html')) else: form = UpdateProfile() args['form'] = form return render(request, 'account/edit_profile.html', args) HTML {% block body %} <div class="container"> <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> <br> </div> {% endblock %} -
554, Transaction failed: Illegal address - Amazon SES with Django
I am using Amazon SES for sending out transactional mails using SMTP. I have verified the domain name and e-mail address. I am able to send the emails to the recipients, but after the mail is sent I get an SMTP exception - 554, Transaction failed: Illegal address. I have integrated configurations in Django settings.py file as given below: EMAIL_DEBUG = True EMAIL_TEMPLATE_DIR = 'emails' EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = 'A***********************' EMAIL_HOST_PASSWORD = 'Aq******************************' DEFAULT_FROM_EMAIL = 'T**G***y.com <no-reply@t****g****y.com>' SERVER_EMAIL = 'T****yG****y.com <no-reply@t****yg****y.com>' EMAIL_PORT = 587 EMAIL_USE_TLS = True Please let me know if I am doing anything wrong. Thanks in advance! -
Multiple Instances of Django(Python) and Postgresql
We have a physical server with a static IP in our premise, and we want to use it to host 4-5 projects. All of these projects are Django(Python3) based with Postgresql as the database. How should I run them on the same physical device? I am not expecting the complete set of instructions, but some direction to get started. Side Note: I have already checked out multiple Sources, like this and have a very low level of understanding of how servers work. -
Django rest model m2m sequentially store
I have a model Task and I want to create another model Sequence which will hold ordered sequence of tasks e.g. sequence1 -> Task1, Task3, Task 7 ; sequence2 -> Task1, Task2, Task4, Task7 etc. A sequence can have many Tasks and a task can be in multiple sequences. How to create such a model to make sure it holds ordered sequence? -
django rest_framework select foreignKey model in CreateAPIView
I want to create new ServiceArea instance using django rest framework, but can't figure out how to set a supplier foreignKey field in CreateApiView. I'm trying to do it using PrimaryKeyRelatedField, but when i set queryset attribute equals to Supplier.objects.all() it gives error 'ServiceArea' object has no attribute 'suppliers'. How i can get access to suppliers in CreateApiView? My code: models.py class Supplier(models.Model): title = models.CharField('Название', max_length=60) email = models.EmailField(verbose_name='Почта') phone_number = models.CharField('Номер телефона', max_length=15) address = models.CharField('Адрес центрального офиса', max_length=120) class Meta: verbose_name = 'Поставщик' verbose_name_plural = 'Поставщики' def __str__(self): return self.title class ServiceArea(models.Model): title = models.CharField('Название области', max_length=120) poly = geo_models.PolygonField('Область', null=True) supplier = models.ForeignKey(Supplier, related_name='areas', on_delete=models.CASCADE, null=True) class Meta: verbose_name = 'Сервисная зона' verbose_name_plural = 'Сервисные зоны' def __str__(self): return self.title serializers.py class SupplierSerializer(ModelSerializer): class Meta: model = Supplier fields = [ 'id', ] class ServiceAreaSerializer(GeoFeatureModelSerializer): suppliers = PrimaryKeyRelatedField(many=True, queryset=Supplier.objects.all()) class Meta: model = ServiceArea geo_field = 'poly' fields = [ 'id', 'title', 'suppliers', ] views.py class ServiceAreaListApiView(ListAPIView, CreateAPIView): queryset = ServiceArea.objects.all() serializer_class = ServiceAreaSerializer -
django models.DateField prevent past
I am looking for ways to prevent user from entering past dates in in django admin page. Something like this: Django: How to set DateField to only accept Today & Future dates My model looks like this: class MyModel(models.Model): date = models.DateField(null=True, blank=True, default=None) -
Can Django-Rest-Framework (DRF) Views and Serializers replace Django native views and forms
I am developing a website where i have to show 1) web pages with html content-type 2) also provide api json end points to develop web or mobile apps. Presently for html web pages i have used djangos views and forms. And for api i was using Django rest frameworks views and serializers. But after going through DRF i have found that DRF can render multiple formats. HTML & Forms REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates. http://www.django-rest-framework.org/topics/html-and-forms/ You can use TemplateHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. http://www.django-rest-framework.org/api-guide/renderers/#templatehtmlrenderer Since with one view (one endpoint) i can get both the html and api will that not make my coding efforts less. I am planning to use only DRF views and searializers instead of DJango forms and views for any type of content. What will be the setbacks if I only use DRF. -
Initialize django CheckboxSelectMultiple with everything unchecked?
I have a model form that is rendering a ModelMultipleChoiceField as a CheckboxSelectMultiple class VisitForm(ModelForm): def __init__(self, queryset=None, *args, **kwargs): super(VisitForm, self).__init__(*args, **kwargs) if queryset: self.fields['students'] = forms.ModelMultipleChoiceField( queryset=queryset, widget=forms.CheckboxSelectMultiple() ) It's rendered very simply in the template right now: <div class="form-group"> {{field.label}} {{field}} </div> It initializes okay with the selections I expect to be there - but by default both options are checked I am trying to figure out how to intialize the boxes so they are unchecked by default. What is the best way to accomplish this? It's initialized in the view like this: visitor = Visitor.objects.get(unique_id=unique_id) students = Student.objects.filter(parents__unique_id=unique_id) form = VisitForm(initial={'visitor':visitor, 'students':students}, queryset=students)