Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django file upload: Upload form has no save method
I got the following situation: model.py class DocumentUploadForm(forms.Form): file = forms.FileField( validators=[validate_file_extension], required=True ) author = forms.CharField(required=True) class Meta: model = Document fields = ['file', 'author'] forms.py class Document(models.Model): file = models.FileField(upload_to='documents/') author = models.CharField(max_length=50) date = models.DateField(auto_now=False, auto_now_add=True) imported = models.BooleanField(default=False) views.py if request.method == "POST": form = DocumentUploadForm(request.POST, request.FILES) if form.is_valid(): # author = request.POST.get('author', None) # if author is None: # return HttpResponseRedirect("/") # document = Document(file=request.FILES['file'], author=author) # document.save() form.save() # no save() method !! Error: 'DocumentUploadForm' object has no attribute 'save' I don't like the way by creating a document object by my self and fill in all the necessary information. This leads to a lot of error handling that I don't want to have. So I had a look at https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/#handling-uploaded-files-with-a-model They describe the exact way I implemented but I don't know why I get the AttributeError. Any help would be nice! aronadaal -
RequestDataTooBig Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE
I'm trying to send a base64 encoded image from a client to a django server , but when an image is bigger than 2.5 MB I'm getting : Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 170, in __call__ response = self.get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 76, in response_for_exception response = debug.technical_500_response(request, *sys.exc_info(), status_code=400) File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 84, in technical_500_response html = reporter.get_traceback_html() File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 316, in get_traceback_html c = Context(self.get_traceback_data(), use_l10n=False) File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 293, in get_traceback_data 'filtered_POST': self.filter.get_post_parameters(self.request), File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 167, in get_post_parameters return request.POST File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 128, in _get_post self._load_post_and_files() File "/usr/local/lib/python2.7/dist-packages/django/http/request.py", line 310, in _load_post_and_files self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict() File "/usr/local/lib/python2.7/dist-packages/django/http/request.py", line 268, in body raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.') RequestDataTooBig: Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. [31/Dec/2016 12:33:50] "POST /chat_photo/ HTTP/1.1" 500 59 … -
Django Sorl - no thumbnail created
Ive recently installed Sorl and im not seeing any thumbnails generated for my photos below: settings.py - has the media root and sorl installed ... INSTALLED_APPS = ( 'home.apps.HomeConfig', 'django.contrib.staticfiles', 'django.contrib.humanize', 'debug_toolbar', 'twitter_bootstrap', 'bootstrap_pagination', 'sorl.thumbnail', ) ... MEDIA_URL = '/media/' MEDIA_ROOT = "/var/www/infternal/media/" model ... from sorl.thumbnail import ImageField ... class SiteFiles(models.Model): site_data = models.ForeignKey(SiteData,verbose_name="Site") site_image = models.ImageField(blank=True,upload_to=site_files_path) new_site_image = ImageField(blank=True,upload_to='media/site_files/') site_file = models.FileField(blank=True,upload_to=site_files_path) file_name = models.CharField(max_length=200,verbose_name="File Name") file_type = models.CharField(max_length=100 ,verbose_name='File Type',choices=settings.FILE_TYPE) template code {% load thumbnail %} ... <h3>Photos</h3> <div class="flex-images"> {% get_file_type Files 'Cabinet Photo' as photos %} {% for file in photos %} <div class="item" data-w="200" data-h="150"> <div class="img"> <a class="image-float-left" id="" href="{{ MEDIA_URL }}{{ file.new_site_image }}" target="_blank"> {% thumbnail file.new_site_image "200x150" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} </a> </div> <div class="over"> {{ file.file_name }} </div> </div> {% endfor %} </div> and this is the final code the template renders, the url works fine, just no image is loaded... <div class="item" data-w="200" data-h="150" style="width: 169px; height: 127px; display: block;"> <div class="img"> <a class="image-float-left" id="" href="/media/site_files/GQ0SKX-31-12-12-17-24.jpeg" target="_blank"> </a> </div> <div class="over"> LI-01 Cabinet Photo </div> </div> -
Why doesn't the following code update the database?
I am trying to update the contents of my database using bootstrap modal form with ajax code.but my database does not get updated with the inputs provided in the form. the form works perfectly fine but i don't see the contents updated in the database. what is wrong ??? please help as i searched whole internet and got nothing :( html code: <div class="container"> <h1> {{ username }} </h1> <h2>Modal Example</h2> <!-- Trigger the modal with a button --> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <form id="new_user_form"> {% csrf_token %} <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <div class="form-group" > <label for="usr">Username:</label> <input type="text" name="username" class="form-control input-lg" id="username"> <label for="passwordd">Password:</label> <input type="password" name="password" class="form-control input-sm" id="password"> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default" id="submit">Submit</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </form> <script type="text/javascript" src="/static/bootstrap 3/js/bootstrap.min.js"></script> Ajax code: <script> $(document).on('submit','#new_user_form',function(e){ e.preventDefault(); $.ajax({ type: "POST", url: "/testapp/registered/", data: { username: $('#username').val(), password: $('#password').val(), csrfmiddlewaretoken:$ ('input[name=csrfmiddlewaretoken]').val () }, sucess: function(){ alert("Registeration successfully.") } error: function(jqXHR, textStatus, errorThrown) { alert(textStatus, errorThrown); } }); }); </script> views.py : from … -
Badly affecting performance in populating ManyToMany field values in rest api (using django rest framework)
As I'm using django rest framework for building my product api. Here is my model in models.py class Tag(models.Model): tag = models.CharField(max_length=10, unique=True) class Product(models.Model): product_name = models.CharField(max_length=100) tag = models.ManyToManyField(Tag, blank=True, default=None, related_name='product_tag') serializers.py : class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class ProductSerializer(serializers.HyperlinkedModelSerializer): tag = TagSerializer(many=True, read_only=True) class Meta: model = Product fields = '__all__' views.py : class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer I have given the url for ProductViewset, so when I hit the api it gives me the results as well but it takes too much time to load, it takes around 2 minutes to give me the response. I'm having 2000 product objects in database which needs to be populated. When I exclude the 'tag' field in "ProductSerializer", response comes very fast with all 2000 records. Please suggest where is the loophole, why its affecting performance so much especially when I add this ManyToMany field. -
How to use stream-django with djangorestframework
I'm new to django and I'm currently working on a small project using djangorestframework. I was having issues creating an activity stream but I stumbled on getstream.io(stream-django) and I've been unable to wrap my head around it. I'll like to see a example of how an activity stream can be created using DRF and stream-django. I'll just drop the model and serializer i'm working with. Many thanks. Models.py class Imprest(models.Model, Activity): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() amount = models.PositiveIntegerField() is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(default=datetime.now) def __str__(self): return 'Raised by: {}'.format(self.user) serializers.py class ImprestSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, required=False) class Meta: model = Imprest fields = '__all__' def get_validation_exclusions(self, instance=None): exclusions = super(ImprestSerializer, self).get_validation_exclusions(instance) return exclusions + ['user'] views.py class ImprestViewSet(ModelViewSet): queryset = Imprest.objects.all() serializer_class = ImprestSerializer permission_classes = permissions.IsAuthenticated, def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return permissions.AllowAny(), return permissions.IsAuthenticated(), def perform_create(self, serializer): instance = serializer.save(raised_by=self.request.user) -
Database to store models with variable number of fields
I'm implementing grammatical vocabulary, each part of speech in different languages has different number of fields. Currently I use Postgresql. For example, class EnNoun(Model): word = CharField(max_length=75) class FrNoun(Model): singular_masculine = CharField(max_length=75) plural_masculine = CharField(max_length=75) singular_feminine = CharField(max_length=75) plural_feminine = CharField(max_length=75) Note that there are many languages and many parts of speech. Next, I have Translation table, where I store translations. class Translation(Model): from_word_id = UUIDField() part_of_speech = CharField(max_length=25) # (noun, adjective etc.) to_word_id = UUIDField() from_lang = CharField(max_length=2) # (en, fr, it etc.) to_lang = CharField(max_length=2) # (en, fr, it etc.) The problem is with searching translation. If user enters "look" and wants to translate from English into French, then I need to query all tables (en tables to be precise) to determine whether there is such word. Then I query Translation to find translation and again query Word tables to fetch info about words. Pretty inefficient. Things got worse when I want to sort translations alphabetically (like in physical vocabulary). I heard about mongodb. Is it capable of storing such data? I want to preserve tables, because each table has its own behavior (__str__ method etc.) Can I write in Mongodb something like class Translation(Model): from_word = SomeObjectField() … -
Serving custom forms from Django's wagtail CMS
I am new to django and one of its CMS called wagtail, I need help with serving and processing custom forms in wagtail without a view to handle the processing of the forms, I came across a way of handling on github, but its only works for one form submission, if you have multiple form submissions its a problem. Any way of handling this would be highly appreciated. thanks -
key is not available in cleaned data in clean method of form in django
I have below ModelForm class. from django.forms import ModelForm from tenant.models import EventsModel from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django import forms class EventsForm(ModelForm): class Meta: model = EventsModel fields = '__all__' def clean_start_date_time(self): # can not be before than now. data = self.cleaned_data print(data) start_date_time = data.get("start_date_time") now_date_time = timezone.now() if start_date_time < now_date_time: raise forms.ValidationError( _('Start time has passed.'), code='invalid', ) return data def clean(self): # end date can not be before or equal to start date time # data = super(EventsForm, self).clean() data = self.cleaned_data print(data) start_date_time = data.get("start_date_time") end_date_time = data.get("end_date_time") if start_date_time >= end_date_time: raise forms.ValidationError( _('End time should be after start time.'), code='invalid', ) clean_start_date_time raised an error because start_date_time is in past. start_date_time is available in clean_start_date_time method but is not available in clean method. Why is this happening? I printed the cleaned data in both the methods, there is difference in cleaned data. Why is this difference? cleaned data in clean_start_date_time : {'tenant_sys_id': None, 'name': 'dfghj', 'start_date_time': datetime.datetime(2016, 12, 21, 13, 20, 23)} cleaned data in clean : {'created_by': None, 'last_updated_when': None, 'last_updated_by': None, 'tenant_sys_id': None, 'notes': 'g', 'name': 'dfghj', 'created_when': None, 'end_date_time': datetime.datetime(2016, 12, 31, 14, … -
Cloning a heroku hosted django project to your local machine
I'm new to python, Django, heroku and even PostgreSQL but am working on a Django project with a team of 3 devs (they set it up), so I'm trying to set it up on my local machine so I can start developing. Firstly I cloned the repository to my local machine, there was a requirement.txt file, so I ran pip install -r ./requirements.txt to install all the python packages the project uses. Theres a runtime.txt file which specifies python 3.5 so I need to upgrade that. I see that gunicorn is one of the packages in requiments.txt, so I'm guessing I need to use that as the web server. Heres the packages in requirements.txt that look important to me: Django==1.9.6 gunicorn==19.5.0 psycopg2==2.6.1 boto3==1.3.1 boto==2.40.0 whitenoise==3.2 django-extensions==1.6.7 The site also has a .buildpacks file, which seems to be a heroku specific thing: https://github.com/a2ikm/heroku-buildpack-libjpeg62 https://github.com/heroku/heroku-buildpack-python https://github.com/rafaelp/heroku-buildpack-wkhtmltopdf Theres a Procfile that contains this: web: gunicorn myproject.wsgi --log-file - worker: celery worker --app=genome.tasks.app -l info --beat I'm wondering what the best way to do this is. Is there a way to automatically generate a virtual environment that has all the requirements and software specified in the project? I'm already using a virtual dev environment … -
Sending emails using Django: No errors thrown when given wrong email id and password
I was trying to send emails through Django. It does not throw any errors when given a wrong password and email id. #settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'sgshds@gmail.com' EMAIL_HOST_PASSWORD = 'hshsa' EMAIL_PORT = 587 EMAIL_USE_SSL = True I made a function in views.py from django.core.mail import EmailMessage from django.conf import settings def sendit(request): from_email = settings.EMAIL_HOST_USER to_email = [from_email] msg = EmailMessage('hello', 'body', from_email, to_email) msg.send() return HttpResponse('dasasad') The output on terminal: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: hello From: sgshds@gmail.com To: sgshds@gmail.com Date: Sat, 31 Dec 2016 08:35:19 -0000 Message-ID: <20161231083519.12551.52266@vatsal-Inspiron-3543> body ---------------------------------------------------------------------- [31/Dec/2016 08:35:19] "GET /sent/ HTTP/1.1" 200 7 P.S. I also have problems in receiving emails. I think, authentication requests are made from smtp to log in to the account and make it send an e-mail. If anybody could help with that. -
Custom Error 400/500 page in Django
There is some strange problem. When I do like this def error_page(request): return HttpResponseBadRequest it raises My custom error page that I listed in main URLconf. But when i pass and exception there - I got just a blank page with the text of exception. For example, view is something like this: def error_page(request): return HttpResponseBadRequest('The error text') And I get a blank page with the "The error text" text in body, but not my custom error page. How can I make Django use my Error page Template, but with error text? -
ModelChoiceForm not creating an empty_label
I've made a form in django using ModelChoiceSelect, and I want to put an empty_label on the select widget so the first choice isn't the one that's selected. This is my forms.py: from django import forms from .models import Country, Embassy class CountryListForm(forms.Form): countries = forms.ModelChoiceField(queryset=Country.objects.all().order_by('name'), empty_label="(Nothing)") What I understand from its documentation, I just need to do is pass the empty_label attribute a value to create it. I've done it already but the empty choice isn't appearing, what I am doing wrong with this form? -
django related objects retrieving
class Publisher(models.Model): name = models.CharField(max_length=300, null=True, blank=True) class Book(models.Model): name = models.CharField(max_length=300, null=True, blank=True) publisher = models.ForeignKey(Publisher,related_name='b', null=True) from polls.models import Book, Publisher p=Publisher.objects.get(id=2) p.b.clear() p.save() b6=Book.objects.get(id=6) p.b.add(b6) p.save() b5=Book.objects.get(id=5) p.b.add(b5) p.save() b7=Book.objects.get(id=7) p.b.add(b7) p.save() print p.b.all() it prints [Book: b5, Book: b6, Book: b7] while i want it to print in the same order as i added them like this [Book: b6, Book: b5, Book: b7] -
Django with NoSQL database
I am working with an Django application which uses Django 1.8 version. Most of the data we deal with is JSON formatted ones. We are trying to implement any NoSQL database. But I see that MONGODB is not compatible for version 1.8 and over and Is there any NoSQL database that can be efficiently mapped to Django 1.8 or over ?? Thanks in advance. -
2checkout pretokenservice not found
I am trying to implement 2checkout payment gateway with my django Application.I have created a simple django application with help of this 2Checkout Documentation This is my javascript code: `window.onload=function(){ var successCallback = function(data) { var myForm = document.getElementById('myCCForm'); myForm.token.value = data.response.token.token; myForm.submit(); }; var errorCallback = function(data) { alert("ERROR CODE:"+data.errorCode); if (data.errorCode === 200) { alert('success'); tokenRequest(); } else { alert(data.errorMsg); } }; var tokenRequest = function() { var args = { sellerId: "#mysellerid", publishableKey: "mypublishkey", ccNo: $("#ccNo").val(), cvv: $("#cvv").val(), expMonth: $("#expMonth").val(), expYear: $("#expYear").val() }; TCO.requestToken(successCallback, errorCallback, args); }; $(function() { $.getScript('https://www.2checkout.com/checkout/api/2co.min.js', function() { try { TCO.loadPubKey('sandbox'); } catch(e) { alert(e.toSource()); } }); $("#myCCForm").submit(function(e) { tokenRequest(); return false; }); }); }` This is my view function for processing the order: def order(request): print('i am here') # Setup credentials and environment twocheckout.Api.auth_credentials({ 'private_key': 'privatekey', 'seller_id': '#sellerid', 'mode': 'sandbox' }) # Setup arguments for authorization request args = { 'merchantOrderId': '123', 'token': request.POST.get("token"), 'currency': 'INR', 'total': '1.00', 'billingAddr': { 'name': 'TEJKANWAR', 'addrLine1': 'myaddressline1', 'city': 'mycity', 'state': 'mystate', 'zipCode': 'pin', 'country': 'IN', 'email': 'testingadress12356@gmail.com', 'phoneNumber': '+9199999999' } } # Make authorization request try: result = twocheckout.Charge.authorize(args) return HttpResponse(result.responseMsg) except TwocheckoutError as error: return HttpResponse(error.msg) This is urls.py: from django.conf.urls import patterns, url … -
Linking one HTML file to Another in Django 1.9
I am trying to learn Django 1.9. Basically trying to build a simple website with two pages. First page is a Home page that lets me fill first and last name with "register" radio button. Once the register button is clicked, it should take me to a second HTML file that confirms the registration. I was finding a hard time reading Django documents trying to figure out how'';when I click the registration button would land me to the Second html page that reads "registration Confirmed". A little bit of insight would be greatly appreciated! -
Where to store certificates used in Django?
I have a bunch of authentication files and certificates I'm using with Django (mostly around push notifications). Where should I store these? Is it inadvisable to store these in my private repo? If yes, how and where should I keep them? -
Django-assets not compiling
Installed django-assets with pip install django-assets into my virtualenv environment. Followed the directions here: django-assets 0.12 documentation Also read through this since this documentation was linked to in the preceding link: webassets Running python manage.py assets build, it seems no matter what I do I get: No asset bundles were found. If you are defining assets directly within your template, you want to use the --parse-templates option. Directory structure: ~/projects/django-project /proj-dir assets.py settings.py /scripts manage.py /static /build app.js app.scss /css /js Variations of my assets.py file: from django_assets import Bundle, register js = Bundle('build/app.js', filters='jsmin', output='js/packed.js') register('js_all', js) And: from django_assets import Bundle, register js = Bundle('static/build/app.js', filters='jsmin', output='static/js/packed.js') register('js_all', js) I have the 'django_assets', in INSTALLED_APPS. STATIC_URL and STATICFILES_DIRS are setup properly because it loads CSS that I put in static/css myself. Added ASSETS_DEBUG = True to settings.py to try and get some indication of what is going on, but doesn't seem to be doing anything. Seems like it just isn't seeing assets.py. I am apparently overlooking something to get this working properly. -
Why would Django respond with differently to the same request
We've recently inherited a Django project which is new territory for me. In debugging an issue I've come across something I've never seen before in my 20 years of programming. I have an API (written in Django) which has multiple end points (usual user profile stuff). When I make a GET request I get a response in the format I expect, however each time I make the request the subset of data is different. I have attached 3 screenshots of the Postman request immediately following new user sign up, these are taken seconds apart with no changes to the data. I can continually make the requests and cycle through the 3 states. This is the code for the endpoint: class UserProfile(RetrieveUpdateDestroyAPIView): serializer_class = SRUserSerializer queryset = SRUser.objects permission_classes = (IsAuthenticated,) def retrieve(self, request, *args, **kwargs): instance = request.user instance.not_now_count = instance.not_now.all().count() serializer = self.get_serializer(instance) return Response(serializer.data) The only thing I can assume is that the serializer is making additional data requests to the database but returning the data before they have necessarily returned. Would there be a way to identify this? What else can I provide to help identify the issue? This is a Django 1.9 instance running on AWS … -
sitemaps.xml not working in google app engine or local google sdk but it does work running in django 1.9.7 server
left google server other one is in django server the google server does not show any logs about it, at first sight, the xml is rendered by the server but it doestn't show the links of the sitemap, sitemap.py from django.contrib.sitemaps import Sitemap from django.core.urlresolvers import reverse from datetime import datetime class BasicSitemap(Sitemap): def __init__(self, names): self.names = names def items(self): return self.names def changefreq(self, obj): return 'weekly' def lastmod(self, obj): return datetime.now() def location(self, obj): return reverse(obj) urls.py from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.shortcuts import render_to_response from django.template import RequestContext from sitemap import BasicSitemap from django.contrib.sitemaps.views import sitemap sitemaps = { 'pages': BasicSitemap(['about', 'home', 'team', 'contacto', 'courses', 'services']) } urlpatterns = [ url(r'^', include('apps.home.urls')), url(r'^', include('apps.about.urls')), url(r'^', include('apps.contact.urls')), url(r'^', include('apps.services.urls')), url(r'^', include('apps.team.urls')), url(r'^', include('apps.client.urls')), url(r'^', include('apps.course.urls')), url(r'^admin/', admin.site.urls), url('^robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap') ] def handler404(request): response = render_to_response('404.html', {}, context_instance=RequestContext(request)) response.status_code = 404 return response def handler500(request): response = render_to_response('500.html', {}, context_instance=RequestContext(request)) response.status_code = 500 return response things i've done 1.- run the aplication in different os (linux windows) 2.- tryed different django versions < 1.9.7 the weird thing about this is that a had a … -
Django form data isn't being inserted into postgres but there are no errors
I am trying to insert data from a Django form into a Postgres table. There are no errors but it's not being inserted and the redirect to the thank you page is happening so it appears to be going through the method without an issue. def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] city = form.cleaned_data['city'] m = MyUser(email=email, city=city, registration_date=datetime.now()) m.save() return redirect('thanks') return render(request, "email.html", {'form': form}) -
Django Tutorial: .choice_set.all not being called
I am new to the Django Framework and can't seem to identify why my detail.html is not rendering properly. It appears as though my forloop that iterates over choice in question.choice_set.all is not being hit. If someone could help identify why it would be very helpful. detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <label for="choice{{ forloop.counter }}">{{ choice.choice_text }} </label><br /> <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> {% endfor %} <input type="submit" value="Vote" /> </form> Views.py from django.http import HttpResponseRedirect, HttpResponse from django.template import loader from django.urls import reverse from django.shortcuts import get_object_or_404, render from .models import Choice, Question # Long Method of return HttpResponse # def index(request): # latest_question_list = Question.objects.order_by('-pub_date')[:5] # template = loader.get_template('polls/index.html') # context = { # 'latest_question_list': latest_question_list, # } def index(request): latest_question_list = Question.objects.order_by('pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) # render takes the request (object,template,dictionary<optional>) # def detail(request, question_id): # try: # question = Question.objects.get(pk=question_id) # except Question.DoesNotExist: # raise Http404("Question does not exist") # return render(request, 'polls/detail.html', {'question': question}) # SHORTCUT TO USE GET AND … -
Django Template Tag for Boolean Value
I'm new to Django, and I'm stuck on a template tag that I can't figure out how to get working. I know I'm missing something in my view but I have written it in several different ways and can't seem to find the right way to do this. I have a Morris chart in my app that I am trying to provide information to. I want to show the percentage of operators that are available. In my model, I have a Boolean value that says if the operator is_available. When I pass it back to the template I want the template tag to run the percentage and pass back the value to the morris pie chart. Here is my view: @login_required(login_url='login/') def operator(request): operators = Operator.objects.all() operator_status = Operator.objects.values_list('is_available', flat=True) context = { 'operators': operators, 'operators_available': operator_status, } return render(request, 'content/operator.html', context) This is the template tag in use: <div class="widget-detail-1"> <h2 class="p-t-10 m-b-0"> {{ operators_available | percentage_of:True }} </h2> </div> </div> and finally my template tag: @register.filter(name='percentage_of') def percentage_of(part, whole): try: return "%d"[2:] % (float(part) / whole * 100) except (ValueError, ZeroDivisionError): return "Division by Zero" -
import django_filters.rest_framework error
I'm getting error when try to use django rest framework filters by following this tutorial. The error appear when I try to import the library: from django_filters.rest_framework import DjangoFilterBackend and the error message is ImportError: No module named 'django_filters.rest_framework' FYI I'm using these version of library: Django==1.10.3 django-crispy-forms==1.6.1 django-filter==0.11.0 djangorestframework==3.5.3 Thank you