Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Random query slow - despite optimizations
I have an build an API that is supposed to return 10 randomly selected results from a - large queryset. I have the following 4 models: class ScrapingOperation(models.Model): completed = models.BooleanField(default=False) (...) @property def ads(self): """returns all ads linked to the searches of this operation""" return Ad.objects.filter(searches__in=self.searches.all()) class Search(models.Model): completed = models.BooleanField(default=False) (...) class Ad(models.Model): searches = models.ManyToManyField('scraper.Search', related_name='ads') (...) class Label(models.Model): value = models.Integerfield() linked_ad = models.OneToOneField( Ad, on_delete=models.CASCADE, related_name='labels' ) The database currently has 400.000 + Ad objects in it, but the average ScrapingOperation has 14000 Ad objects linked to it. I want the API to return 10 random results from these +/- 14000 that do not yet have a linked Label object (Of which only up to a few hundred exist per operation) So the 10 random results have to be returned from a query that contains 14.000 objects. An earlier version had to return only 1 result, but used the much slower sort_by('?') method. When I had to scale it up to return random 10 Ad objects I used a new approach based partly on this stackoverflow answer Here is the code that selects (and returns) the 10 random objects: # Get all ads linked to … -
How to create a file in memory (not an uploaded file) and save to FileField through Django default_storage?
If I was to create a file-like csv object in memory like so: output_stream = io.StringIO() sheet = pyexcel.get_sheet(records=data) sheet.save_to_memory(file_type='csv', stream=output_stream) What can I do to save the file like object in output_stream to a file on my default_storage backend with Django? class Example(models.Model): model_file = models.FileField(upload_to='', max_length=255, blank=True, null=True) I've tried something like: self.model_file.save(filename, ContentFile(output_stream.read())) But I get the following error: "TypeError: ('data must be bytes, received', )" pyexcel only supports io.StringIO streams for csv type files. -
Django - How does Django access data in sqlite?
How does Django access data in sqlite database? Lets assume this scenario: Very basic models.py, and views.py are created to accept user input from page and store it in sqlite database. If a user clicks a submit button, that data is sent to sqlite database, and the user can view it by accessing the Django Admin page. Later the user wants to display the stored data using CBV in views.py: class Some_ListView(ListView): template_name = 'some_list.html' context_object_name = 'SomeInfo' model = models.SomeModel And the data in the database is rendered in HTML like this: {% for item in SomeInfo %} <p>item<p> {% endfor %} When & how does Django load data when rendering a page? Does it access & retrieve data whenever a any html page is loaded? Is there any way to load data in a previous page, temporarily store it, and inject it in a future page? How do you get connection? Does it use connection pool? I will be using PostgreSQL for database for my real project, and I'm looking for advice on when & how to establish connection using connection pool. Another scenario: Some data were prepared by creating Class WellInfo in models.py. You can view this … -
django - identifying player (in a game) with session id
I am making a simple turn-based game app (similar to Chess) using Django as the backend. I want the game to be playable without requiring that the user register an account and sign in to play (that would be easier authentication wise, but it is also inconvenient). The requirements are that when a user clicks to join a game (with a spot available), he is assigned a color (black or white, as in chess) and only he can make moves for that color. I was thinking of having ForeignKeys within the Game model that reference Session objects. These keys are assigned when players join a game, and subsequent game moves are validated by referencing them. I see no reason why this approach wouldn't work, but I was hoping that some more experienced devs could double check my design. Would this be considered an appropriate way to use sessions? -
Filename only in django form field
I have a model that contains a filefield and am using a modelform to add instances. When I come to modify an instance the form shows the current file and displays the file path ie library/filename. Is there a way to show just the filename in the form? Thanks -
How To Set Default Fontsize for django-summernote
I have been playing around all afternoon trying to figure out how to set the default font size for the django-SummernoteWidget. I figured out how to set the default font size for the SummernoteInplaceWidget as documented here, Summernote lite bullet and number list not defaulting to custom default fontsize but now I can't figure out how to set the default font-size for the SummernoteWidget. Here is what I have tried...Thanks in advance for any thoughts... My settings.py file... SUMMERNOTE_CONFIG = { 'summernote': { 'toolbar': [ ['undo', ['undo',]], ['redo', ['redo',]], ['style', ['bold', 'italic', 'underline',]], ['font', ['strikethrough',]], ['fontsize', ['fontsize',]], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ], 'width': 760, 'height': 400, 'focus': True, 'fontSizes': ['8', '9', '10', '11', '12', '14', '18', '22','24', '36', '48' , '64', '82', '150'], 'font-size': 18, }, } I have also tried to set my CSS for the item in question as shown below: .editor { font-size: 18px; margin-left: 24.4rem; } But no matter what I do the end result is.... The SummernoteInplaceWidget for django seems to be modifiable via CSS but the standard SummernoteWidget does not, at least as far as the fontsize is considered. The margin-left does take effect but the fontsize for the SummernoteWidget does not. … -
How to assign filename to Image in Django based on EXIF DateTime
I would like to read EXIF information from a user-uploaded image in Django, then use that EXIF info to generate the filename to store the image as (under the animal_img/alfred-0012 directory), for example: Original filename: P1110438.JPG Date taken: 2012-07-22 Name: Alfred Intended filename: alfred-20120722.jpg Somehow, this had been working up until recently, but Django has been complaining about not finding the file with [Errno 2] No such file or directory: 'P1110438.JPG' The code I've been using in my model to rename the images: def img_namer(instance, filename): path = 'animal_img/%s-%04d/' % (instance.name.lower(), instance.id) name = instance.name.lower() + Image.open(filename)._getexif()[36867] + ".jpg" return os.path.join(path, name) image = models.ImageField( default=None, blank=True, upload_to=img_namer, ) I can see the limitations with trying to open the ImageFile before it's been properly saved, however this had been working, like I said, so maybe I'm doing something wrong? Any help is appreciated! -
RuntimeError: Model class xxx.xxx doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
i am getting the following error when trying to run the django 2 app few lines from stacktrace File "/Users/shobi/Projects/emailtool/emailtool/frontend/models/AwsSettings.py", line 4, in from emailtool.frontend.models.AwsRegions import AwsRegions File "/Users/shobi/Projects/emailtool/emailtool/frontend/models/AwsRegions.py", line 4, in class AwsRegions(models.Model): File "/Users/shobi/Projects/emailtool/env/lib/python3.6/site-packages/django/db/models/base.py", line 108, in new "INSTALLED_APPS." % (module, name) RuntimeError: Model class emailtool.frontend.models.AwsRegions.AwsRegions doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I tried Django: Model class user.models.Users doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS and many google results as well, what is missing? Django2, Python 3.6 -
MultiValueDictKeyError Django Stripe integration
In a tutorial on Stripe.com they have the following Stripe "Checkout" form: <form action="{% url 'payment' %}" method="POST"> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_z1bxF7Bk4Rk9PZuBFHMrYZnj" data-amount="999" data-name="Demo Site" data-description="Example charge" data-image="https://stripe.com/img/documentation/checkout/marketplace.png" data-locale="auto"> </script> </form> and the following python code: import stripe def payment(request): # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = "sk_test_BJUliYkgS5VZEKFM1UQAz9cF" # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: token = request.POST['stripeToken'] #my comment: I am assuming 'stripeToken' comes from https://checkout.stripe.com/checkout.js but am not completely sure charge = stripe.Charge.create( amount=999, currency='usd', description='Example charge', source=token, ) Note in their example they use Flask, so I have changed token = request.form['stripeToken'] #Flask to token = request.POST['stripeToken'] #Django But when I run the above code I get the following response: Exception Type: MultiValueDictKeyError Exception Value: "'stripeToken'" I have also tried token = request.POST.get['stripeToken'] #Django this returns 'method' object is not subscriptable Here is the tutorial I am following if you wish to look: https://stripe.com/docs/quickstart (steps 1 and 2 are relevant to this question) Thanks in advance for any help...according to Stripe this is all it should take for a … -
Django Create multiple instance of model with one form
In my django project I want to save multiple instances of modal with one form, for better understanding, let I have model as - class Book(models.Model): author = models.CharField(max_length=100) title = models.CharField(max_length=100) languages = models.ManyToManyField(Languages, related_name='book_language') price = models.DecimalField(max_digits=5) In my form class BookForm(forms.ModelForm): multi_pricing = forms.CharField(widget=forms.HiddenInput()) pricing_type = forms.CharField(widget=forms.HiddenInput()) class Meta: model = Book fields = '__all__' If pricing_type = 'single_pricing' then do nothing and save only one model, but if value of pricing_type = 'multi_pricing' Then I am receiving different pricing for different language in dictionary, such as - multi_pricing = {"English":"400","Hindi":"300","French":"500"}. Now What I want is to create three instance of Book and set three languages according to their price. I don't want to use create method, if anyone can suggest me the best and most convenient way and method which apply all validations as if user select single_pricing. Any kind of suggestions and help will be appreciable. -
Assign user when upload excel file with django-excel
I'm trying to populate my database model in bulk with uploading a excel file. It works fine, except I get the following error. ValueError at /xls/ Cannot assign "u'admin'": "Child.user" must be a "MyUser" instance. Request Method: POST Request URL: http://localhost:8000/xls/ Django Version: 1.11 Exception Type: ValueError Exception Value: Cannot assign "u'admin'": "Child.user" must be a "MyUser" instance. Exception Location: /Users/Dropbox/sp_env/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py in __set__, line 216 Python Executable: /Users/Dropbox/sp_env/bin/python Python Version: 2.7.10 Python Path: ['/Users/Dropbox/sp_env/sp/src', '/Users/Dropbox/sp_env/lib/python27.zip', '/Users/Dropbox/sp_env/lib/python2.7', '/Users/Dropbox/sp_env/lib/python2.7/plat-darwin', '/Users/Dropbox/sp_env/lib/python2.7/plat-mac', '/Users/Dropbox/sp_env/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/Dropbox/sp_env/lib/python2.7/lib-tk', '/Users/Dropbox/sp_env/lib/python2.7/lib-old', '/Users/Dropbox/sp_env/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/Dropbox/sp_env/lib/python2.7/site-packages'] The view is copied from a given django-excel view see: from django.shortcuts import render, redirect from django.http import HttpResponseBadRequest, HttpResponse from _compact import JsonResponse from django import forms import django_excel as excel from django.contrib import messages from .models import Parent, Child def import_data(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) def choice_func(row): q = Parent.objects.filter(slug=row[0])[0] row[0] = q return row if form.is_valid: request.FILES['file'].save_book_to_database( models=[Parent, Child], initializers=[None, choice_func], mapdicts=[ ['is_b2b', 'parent_image', 'title', 'user', 'description', 'brand', 'product_category', 'slug'], ['parent', 'product_name', 'sku', 'product_id_code', 'user', 'purchase_price', 'retail_price', 'ws_price', 'quantity', 'min_stock_amount', 'var_color'] ]) messages.success(request, 'Data successfully processed...') return redirect('/xls/') else: return HttpResponseBadRequest() else: form = UploadFileForm() return render( request, 'xlsproduct/xls_home.html', { 'form': form, }) I have … -
Django rest framework ApiView reurn executable file
Question similar to this django rest framework return file Trying to apply a similar solution to return an executable python binary in Django Rest ApiView: from wsgiref.util import FileWrapper bin_file = open(f'cli/builds/dist/cli', 'rb') response = Response(FileWrapper(bin_file), content_type='application/octet-stream') response['Content-Disposition'] = f'attachment; filename="cli"' response.status_code = status.HTTP_200_OK return response getting Object of type 'FileWrapper' is not JSON serializable error. Referring to the previously mentioned SO topic - this solution is warking for a zip file. Question - why doesn't it work for my setting, returning the python executable? python 3.6.5, djangorestframework==3.8.2 -
Create Model for 4-D kind of array in Django
I'm running a small company. I have a logic constructed for my Database, but I am quite unable to convert it into Django Models that can be used in Models.py file in my WebApp : User : U Transcation-ID : T Datetime : D Transaction-ID Status-1 for a today : A[0] Transaction-ID Status-2 for a today : A[1] Transaction-ID Status-3 for a today : A[2] For above a logic can be constructed with N users : U[N] where U[i] -> T[i][] transaction, and each transaction has 3 transactional attributes T[j] -> A[j][3]. How should I proceed with constructing a model for the given details. Also if possible how can I store date wise Model for the three A[k] statuses of Transcation and add them for a week wise and month wise avergae and procced with making the db. Detailed Explanation : A particular user in my company can have done variable number of Transactions, and for each transaction there is a key provided used to get the status of that particular transaction. Like the power points earned, bonus points earned and fame points earned. I periodically want to update the 3 points earned daily, weekly and monthly across all transactions … -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'User'
I developed an API using Django Rest Framework. I just changed my model in order to link my object to User object of Django by adding creationUser and updateUser : class Document(models.Model): name = models.CharField(max_length=100) recipient = models.ForeignKey('Client', models.SET_NULL, null=True, verbose_name='Client') provider = models.ForeignKey('Provider', models.SET_NULL, null=True, verbose_name='Provider') type = models.CharField(max_length=50) receptionDate = models.DateField() fileName = models.CharField(max_length=200) comment = models.TextField(blank=True, null=True) summary = models.TextField(blank=True, null=True) status = models.CharField(max_length=5) creationDate = models.DateTimeField(auto_now_add=True, editable=False) updateDate = models.DateTimeField(auto_now=True) creationUser = models.ForeignKey(User, models.SET_NULL, null=True, related_name='creationUser') # New Line updateUser = models.ForeignKey(User, models.SET_NULL, null=True, related_name='updateUser') # New Live def __str__(self): return "Id : {0} | Nom : {1} | Fournisseur : {2} | Type : {3} | Date de reception : {4}".format(self.id, self.name, self.provider, self.type, self.receptionDate) Then I execute : pipenv run python manage.py makemigrations pipenv run python manage.py migrate First line works, but second line provides : Operations to perform: Apply all migrations: admin, api, auth, contenttypes, inbox, sessions Running migrations: Applying api.0027_auto_20180721_0106...Traceback (most recent call last): File "manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\mjacq\.virtualenvs\gouvernante_is_real-pYxsNaTM\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, … -
module 'book.views' has no attribute 'BookListView' in django my project
code : https://i.stack.imgur.com/AZZua.png https://i.stack.imgur.com/4qTbN.png and error : https://i.stack.imgur.com/GaP7O.png pleas help me. -
Stripe integration with Django
I am following a tutorial on stripe.com, to accept a charge it says to use the following form and capture the Token it returns in a view Stripe "Checkout" form: <form action="{% url 'payment' %}" method="POST"> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_z1bxF7Bk4Rk9PZuBFHMrYZnj" data-amount="999" data-name="Demo Site" data-description="Example charge" data-image="https://stripe.com/img/documentation/checkout/marketplace.png" data-locale="auto"> </script> </form> The next step says to simply copy and paste this and your test account should be able to accept charges Stripe view: def payment(request): # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = "sk_test_BJUliYkgS5VZEKFM1UQAz9cF" # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: token = request.POST['stripeToken'] charge = stripe.Charge.create( amount=999, currency='usd', description='Example charge', source=token, ) but stripeToken is mentioned nowhere in the form and the code returns an error because of this, can someone explain where this is coming from? (Note, the example was in Flask so I changed token = request.form['stripeToken'] # Using Flask to token = request.POST['stripeToken'] #using Django Both of these can be found at https://stripe.com/docs/quickstart (Step 1 shows 'Checkout', step 2 shows the python code) Thanks in advance for any help. -
Django delete the old profile image cause this error in save() method The 'profile_img' attribute has no file associated with it
I have profile model with an image field. The image will be cropped and resized When the user upload new one. I want to delete the old image using post_save signal. models.py class Profile(models.Model): profile_img = models.ImageField(upload_to='profile_img', default='/profile_img/default.png', null=True, blank=True) @receiver(post_init, sender=Profile) def backup_image_path(sender, instance, **kwargs): instance._current_image = instance.profile_img @receiver(post_save, sender=Profile) def delete_old_image(sender, instance, **kwargs): if hasattr(instance, '_current_image'): if instance._current_image.path != instance.profile_img.path: instance._current_image.delete(save=False) when the _current_image is deleted, the below save method raise the error. the error comes from this line image = Image.open(profile.profile_img) forms.py class ImageUploadForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = Profile fields = ("profile_img",) def save(self): profile = super(ImageUploadForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(profile.profile_img) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((300, 300), Image.ANTIALIAS) resized_image.save(profile.profile_img.path) return profile I don't know where my mistake is. -
Syntax Error: invalid syntax as to 'OPTIONS' (Django context)
When I input python3 manage.py runserver, the terminal displays the following: File "/home/ms/myproject/myproject/settings.py", line 60 'OPTIONS':{ ^ SyntaxError: invalid syntax Can you help me with this Traceback? My templates in the file settings.py look this way: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':[os.path.join(BASE_DIR, 'templates')], 'APP_DIRS':True 'OPTIONS':{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Django - Get Data from Database in Highchart.js
i have this models.py name = models.TextField(db_column='Name', blank=True, null=True) wkts = models.FloatField(db_column='Wkts', blank=True, null=True) ave = models.FloatField(db_column='Ave', blank=True, null=True) econ = models.FloatField(db_column='Econ', blank=True, null=True) sr = models.FloatField(db_column='SR', blank=True, null=True) How to get these fields in highchart.js code ? for example how to display all of them in a piechart? P.s i am new to visualizations in django, unable to interpret this clearly -
Django==2.0.7 django/forms/fields.py has some issue when you handle imagefield in your code
I faced a problem while handling one ImageField in my model and deployed to production. The model I am using through Django Admin to store data into this model but when I press save data, my application generate "Server Error 500" but when I do not select image file to save there is no error and DEBUG detail trace back tells this. File "/home/asifkhan69/webapps/rmsapp/lib/python3.6/Django-2.0.7-py3.6.egg/django/forms/fields.py" in to_python 611. from PIL import Image Exception Type: ModuleNotFoundError at /admin/vv/institutes/add/ Exception Value: No module named 'PIL' Request information: USER: asifkhan The same application is not giving this error on development setup. I am looking expert answer on this to fix. -
django: extending user model with one-to-one link - how to use post_save signal
I am new to django , I am learning how to extend the user model using the following site: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html I have some doubt in the following model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() How this line exactly works: Profile.objects.create(user=instance) I know post_save will be called after user is created, but I don't understand how the following line is used to store the additional fields. Profile.objects.create(user=instance) -
django - order by query
I have a model called Post which has two fields upvotes and downvotes. Now, upvotes, downvotes are ManyToManyField to a User. This is the model: class Post(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) upvotes = models.ManyToManyField(Profile, blank=True, related_name='upvoted_posts') downvotes = models.ManyToManyField(Profile, blank=True, related_name='downvoted_posts') I have to make a query where I have to get all posts sorted by total (upvotes) - total (downvotes) I have tried Post.objects.order_by(Count('upvotes')) to get started but there's an error. -
Getting value of field of a reverse related model in django queryset
class User(models.Model): name = models.CharField(max_length=189) class Chat(models.Model): message = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="messages") created_at = models.DateTimeField(auto_now_add=True) What I want to do here is that I want to get a queryset of customers ordered by according their last message time which will also contain the last message of the user as an additional data. I have tried the following. qs = user.objects.annotate( last_message_time=Max("messages__created_at"), last_message=F("messages__message") ).order_by("-last_message_time") Here, I am getting the last message time but the first message of the user. -
Unable to store a python class object in postgres database
I have a class defined like below class StatementStatus: def __init__(self, id, statement, call, intent, score): self.id = callback_id self.statement = statement self.entities = entities self.intent = intent self.score = score def getIntent(self): return self.intent def getScore(self): return self.score def addIntent(self, intent_val): self.intent.append(intent_val) Now I want to store an instance of this class into postgres database.This file is hosted in a django server and I am unable to use django migrations due to some issues in the server.So I need to do it manually. Below is my django model class StoreState(models.Model): context_name = models.CharField(null=True,max_length=100) state = models.BinaryField(null=True) Here I want to store the StatementStatus instance in a field called state. Similarly my postgres table structure looks like below Column | Type | Modifiers --------------+------------------------+----------- id | integer | context_name | character varying(100) | state | bytea | But it doesn't store any entry into the table when I do an operation like below try: conv = StoreState.objects.create( context_name = callback_id, state=s ) except Exception as e: print("unable to save update", e) But it doesn't store anything into the table.I get the below error. ('unable to save update', TypeError("can't escape instance to binary",)) What am I doing wrong? -
Using Bootstrap Model with Django classed based views to implement login function
I have created loginview using class-based view concept as following: class LoginView(NextUrlMixin,RequestformattachMixin,FormView): form_class = login_page template_name = 'login.html' success_url = '/' def form_valid(self, form): next_url=self.get_next_url() return redirect(next_url) def form_invalid(self, form): return super().form_invalid(form) forms.py: class login_page(forms.Form): Email = forms.EmailField(required=True,widget=forms.EmailInput( attrs={"class": "form-control", "placeholder": "Email address", "id": "exampleInputEmail2"})) Password = forms.CharField(required=True,widget=forms.PasswordInput(attrs={"class": "form-control",'id':'exampleInputPassword2', "placeholder": "Password"})) I have modified on my login.html page to use bootstrap modal as the following: {% block content %} <div id="loginModal" class="modal fade"> <div class="loginModal-content"> <div class="loginModal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Login</h4> </div><div class="loginModal-body"> <div class="row"> <div class="col-md-12"> via <div class="social-buttons"> <a href="#" class="btn btn-fb"><i class="fa fa-facebook"></i> Facebook</a> <a href="#" class="btn btn-tw"><i class="fa fa-twitter"></i> Twitter</a> </div>or <form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav"> <div class="form-group"> <label class="sr-only" for="exampleInputEmail2">Email address</label> {# <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>#} {# {{ form.Email }}#} </div> <div class="form-group"> <label class="sr-only" for="exampleInputPassword2">Password</label> {# <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password" required>#} {# {{ form.Password }}#} <div class="help-block text-right"> <a href="">Forgot the password ?</a> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block">Sign in</button> </div> <div class="checkbox"> <label> <input type="checkbox"> keep me logged-in </label> {{ form }} </div> </form> </div> <div class="bottom text-center"> New here ? <a href="signUp.html"><b>Join Us</b></a> </div></div></div> <div class="loginModal-footer"> </div> </div> </div> {% endblock …