Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django auto save the current user in the model on save
I am trying to save the user automatically when saving new data. It's working if I hard-coded the user-id get(id=2). How can I make the id dynamic? If it's not possible how can I do it in views or serializer without using forms? models.py class Feedback(models.Model): . . author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, editable=False, ) def save(self, *args, **kwargs): self.author = get_user_model().objects.get(id=2) @@@@@@@@@@@@@@@@@ return super().save(*args, **kwargs) -
Getting Error in Heroku when Deploying Django
I'm trying to Deploy the Django backend in Heroku through the GitHub repo (which I have committed in main Branch). I'm getting the following error below when deploying it. -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt ! Python has released a security update! Please consider upgrading to python-3.10.5 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.10.4 -----> Installing pip 22.1.2, setuptools 60.10.0 and wheel 0.37.1 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (79baf8)... Ignoring tzdata: markers 'sys_platform == "win32"' don't match your environment -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_6bcdc97f/manage.py", line 22, in <module> main() File "/tmp/build_6bcdc97f/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/app/.heroku/python/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' ! … -
TypeError: AsyncConsumer.__call__() missing 1 required positional argument: 'send'
consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name= self.scope['url_route']['kwargs']['room_name'] self_room_group_name='chat_%s' % self.room_name await self.channel_layer.group_add ( self.room_group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type':'tester_message', 'tester':'Hello world', } ) async def tester_message(self,event): tester =event['tester'] await self.send(text_data=json.dumps({ 'tester':tester, })) async def disconnect(self, code_close): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) pass -
How to make query in django serializers many to many objects filter?
Info: I want to filter the candidate by party id Candidates.objects.filter(party_id_in=1).filter(party_id_in=4) How can i pass this queryset in ConstituenciesSerializer. I don't understand where and how i defined and get the candidates by party id. i want to get only two parties candidates in Constituencies serializers. My code is working fine but it is getting all candidates data. Models.py class Party(models.Model): name = models.CharField(max_length=255) class Candidates(models.Model): name = models.CharField(max_length=100, verbose_name=_('English name')) party = models.ForeignKey(Party, on_delete=models.SET_NULL, null=True)) class Constituencies(models.Model): candidates = models.ManyToManyField(Candidates)) serializers.py class PartySerializer(serializers.ModelSerializer): class Meta: model = Party fields = ['name'] class CandidateSerializer(serializers.ModelSerializer): party = PartySerializer(required=False, read_only=True) class Meta: model = Candidates fields = [ 'name', 'party', ] class ConstituenciesSerializer(serializers.ModelSerializer): candidates = CandidateSerializer(many=True) class Meta: model = Constituencies fields = ['candidates'] views.py class CandidateVSRetrive(generics.RetrieveAPIView): queryset = Constituencies.objects.all() serializer_class = ConstituenciesSerializer -
Django REST Framework UniqueTogetherValidator fails with FK from kwargs
I've got myself into a trouble with UniqueTogetherValidator. The problem is that ReviewSerliazer unlike CommentSerializer which is almost identical does unique together validation before actually getting a title value from kwargs and sends back 400 answer with title field being required. I've tried to identify it as a HiddenField, but although serializer validation goes fine within tests, model validation does not. And I receive django.db.utils.IntegrityError: UNIQUE constraint failed: reviews_review.author_id, reviews_review.title_id Any ideas how to fix this without catching exceptions in the viewset, which is obviously wrong? models.py class BasePost(models.Model): text = models.TextField() author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='%(class)ss') pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-pub_date', ) abstract = True def __str__(self): return self.text[:30] class Review(BasePost): score = models.IntegerField( default=0, validators=[MaxValueValidator(10), MinValueValidator(1)]) title = models.ForeignKey( Title, on_delete=models.CASCADE, related_name='reviews') class Meta(BasePost.Meta): constraints = [ models.UniqueConstraint( fields=('author', 'title', ), name='unique_title_review')] class Comment(BasePost): review = models.ForeignKey( Review, on_delete=models.CASCADE, related_name='comments') urls.py router_v1.register( r'^titles/(?P<title_id>\d+)/reviews', ReviewViewSet, basename='review') router_v1.register( r'^titles/(?P<title_id>\d+)/reviews/(?P<review_id>\d+)/comments', CommentViewSet, basename='comment') views.py class ReviewViewSet(BasePostViewSet): serializer_class = ReviewSerializer def get_queryset(self): return self.get_title().reviews.all() def perform_create(self, serializer): serializer.save(author=self.request.user, title=self.get_title()) def get_title(self, key='title_id'): return get_object_or_404(Title, id=self.kwargs.get(key)) class CommentViewSet(BasePostViewSet): serializer_class = CommentSerializer def get_queryset(self): return self.get_review().comments.all() def perform_create(self, serializer): serializer.save(author=self.request.user, review=self.get_review()) def get_review(self, key='review_id'): return get_object_or_404(Review, id=self.kwargs.get(key)) serializers.py class ReviewSerializer(BasePostSerializer): title … -
Create a dynamic datatable dashboard with dynamic values in cells
I am actually making a project on python. The goal is to display a dashboard (made of a datatable) on a webpage, in which the datas will evolve really quickly (each 1 to 2 seconds). The datas are received from a rabbitmq. I actually have successfully achieved it with Dash. Everything works well, but I have one major problem. Dash seems to be really slow when we have a huge amount of datas (approximately 300 columns for 5000 rows in my case) that are regularly actualized. As far as I went, I think that the major lack of speed comes from the fact that the values pushed in the datatables are in a dictionary and not dynamic (not an in-cell modification), so all the javascript loads slowly and is not that stable. Which leads me to this question : what would be the best way to achieve the goals mentioned below ? I thought that using Django and creating a custom javascript datatable could do the job but I would like to get some advices and ideas before starting to code that (really) time consuming solution. Thanks to all ! -
AttributeError-module 'urllib.request' has no attribute 'META'
i just started django here is my view from django.shortcuts import render from django.http import HttpResponse from urllib import request def homepage(*args,**kwargs): return render(request,'home.html') # Create your views here. def requestpage(*args,**kwargs): return render(request,'req.html') which givesenter image description here -
Django - OpenCV Display output in HTML
So I make an attendance system with face recognition on Django. Right now my code will open up the python window, detect face and record name, date and time on CSV file. I want to display name, time and date on the HTML once the face is detected. How can I do that?. views.py from django.shortcuts import render import cv2 import numpy as np import face_recognition import os from datetime import datetime from django.core.files import File from django.template.loader import render_to_string path = 'attendancesystem/file/faces' images = [] className = [] imgList = os.listdir(path) print(imgList) #read image from images folder for cl in imgList: curImg = cv2.imread(f'{path}/{cl}') images.append(curImg) className.append(os.path.splitext(cl)[0]) print(className) This is the function to mark the attendance once the face is detected. #mark attendance function def markAttendance(name): with open('attendancesystem/static/attendancesystem/Attendance.csv', 'r+') as f: attendList = f.readlines() nameList = [] for line in attendList: entry = line.split(',') nameList.append(entry[0]) if name not in nameList: now = datetime.now() dateString = now.strftime('%d/%m/%Y') timeString = now.strftime('%H:%M:%S') f.writelines(f'\n{name},{dateString},{timeString}') This is the function to encode the image that is inserted in the faces folder. #encode image def findEncoding(images): encodeList = [] for img in images: img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) encode = face_recognition.face_encodings(img)[0] encodeList.append(encode) return encodeList encodeListKnown = findEncoding(images) print("Encoding Complete") … -
Django object multilevel filtering
Hi Everyone I want to filter object which is in the form of tree class UserModel(model.Model): created_by = models.ForiegnKey('self',on_delete=model.SET_NULL,null=True) name = model.CharField(max_length = 50) the relation will be userModel A,B... represent UserModel, A -> B,represent B is child of A A -> B -> C -> D -> E -> F-> and so on I want to filter Object where A able to see its child and grandchild but not its GrandParent A is able to see UserModel Objects created by B C D E so on but B is only able to see User created by C D E F, not for A; -
How I can use json object from file (e.g text.json) for my email template to read from in Django
I am using Django to send email templates to user. I want to store all the text show ins the HTMl template in json object and reference the text as variable, double {{}} in the html email template -------> util.py def send_reset_password_email(user: User): reset_token = create_user_reset_password_token(user) reset_password_url = '{}/account/password/reset/{}'.format(settings.CLIENT_URL, reset_token) params = { 'reset_password_url': reset_password_url, 'textdata': ### how I can reference my json file here } send_template_email(user.email, 'Reset Password','reset_password.html', params) ------->text.json file { "forget_password_email_template": { "title": "This is title", "sub_title": "This is Sub title", "support": "This is title", "help_message": "This is help message" }, "confirmation_email_template": { "title": "This is title", "sub_title": "This is Sub title", "support": "This is title", "help_message": "This is help message" } } -------> reset_password.html <html> ....... <p style="margin: 0;" class="forget-password-text"> Forgot your password? Let’s get you a new one! {{params.textdata}}</p><br> ..... <<html/> I have tried import json but it didn't work. Thanks, and if there is other any better way to achieve this?? -
Django REST API get only auth user datas
I am new Django, I try make REST API. Now face one issue. I created 2 models Account & Transaction class Account(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False) user = models.ForeignKey(User,on_delete=models.CASCADE) account_name = models.CharField(max_length=100) Account have ForeignKey with user model class Transaction(models.Model): id = models.UUIDField(default=uuid.uuid4(),primary_key=True,editable=False) account = models.ForeignKey(Account,on_delete=models.CASCADE,related_name='account') transaction_no = models.CharField(default=str(uuid.uuid4())[:8],max_length=100) Transaction have ForeignKey with Account model. then get JWT token & pass on API. In view.py I filtered by requested user @api_view(['GET']) @permission_classes([IsAuthenticated]) def getAccount(request,pk): account = Account.objects.filter(user=request.user).get(id=pk) serializer = AccountSerializer(account, many=False) return Response(serializer.data) now how will filter Transaction only by auth User @api_view(['GET']) @permission_classes([IsAuthenticated]) def getTransactions(request,account_id): transactions = Transaction.objects.filter(account=account_id) serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) -
CSS alternative to "display:inline-block" for email
I have to send emails to customers when they perform various actions on my website. Obviously, I want these emails to look good and to contain an selection of images, links and other features. I have built an HTML version of the email I wish to send and my Django app converts it to a nice email that really gets the job done. The problem I have is that there seems to be no standard for what is supported by different email providers. My email looks perfect on browser, Gmail and Android, but when I open it up in the Outlook app on my Microsoft, suddenly some CSS properties are not supported. I have this website which tells me what CSS attribute are supported and which ones aren't: https://www.caniemail.com/search/?s=display From that website I understand that the "display" attribute is not supported by the Outlook app. That is very unfortunate because I don't know any alternative for essential stuff like "inline-block" or how to center my images. Would anybody know how to replace these attributes (most important of all 'inline-block') so that I can send these emails to any platform my clients might use? -
Do you think this is the right way to rename a django app?
I read different threads and tutorials on renaming and migrating a Django app (How to rename a Django app and migrate data from an app to the other for instance), I also tried to use the django package called django-rename-app but it didn't work at all. I'm going to explain the way I renamed my app in my development environment and I would like to know if you expect troubles, as apparently everything is working just as it did before so I'm considering doing the same in production. Here are the steps I took inside my root project directory and my virtualenv activated, using Django 3.2: Create the destination app django-admin startapp app2 Copy these files and directories cp app1/*.py app2/ mkdir app2/templates mkdir app2/static cp app1/templates app2/templates in this case I had a sub-folder named after the app so I renamed it like this mv app2/templates/app1 app2/templates/app2 cp app1/static app2/static Models.py Change the related_name attributes of all ForeignKeys in my new models.py and update all their references inside my views, admin, form and templates Activate the new app Add my app2 to the list of the enabled apps of settings.py Delete pycache Find and delete or empty all the … -
Django user manager overriding create()
I ran into an issue that was solved in the following way. # models.py class CustomUserManager(SafeDeleteManager,UserManager): def create(self, username, email=None, password=None, **extra_fields): return super().create_user(username, email, password, **extra_fields) class CustomUser(AbstractBaseUser): # other fields are omitted for brevity. objects = CustomUserManager() Is overriding create method in the custom user manager ok, or it can cause problems in the future? -
List of connected users in a room with django channels
How can we get the list of connected users to a room within channel with Django Channels? I know this question has been asked many times, but honestly, I've scoured all over the internet and I'm very surprised there isn't a conventional way of doing so. According to this answer, Django Channels have avoided this scenario, however, there is another package, Django Presence, that can cater for it. So far, I've got a very simple app where a websocket broadcasts data that is sent from each client, so that each connected client in a room receives that data. I've also got a simple authentication so that only authenticated users can connect. This is what I have: routing.py application = ProtocolTypeRouter( { "websocket": TokenAuthMiddleware( URLRouter([ re_path(r'ws/(?P<room_name>\w+)/$', consumers.MyConsumer.as_asgi()), ]) ) } ) middleware.py from urllib.parse import parse_qs from django.contrib.auth.models import User from django.contrib.auth.models import AnonymousUser from channels.db import database_sync_to_async from channels.middleware import BaseMiddleware class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) async def __call__(self, scope, receive, send): # Get the token token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] #custom code to validate token if token_is_valid: # assign scope['user'] = user else: scope['user'] = AnonymousUser() return await super().__call__(scope, receive, send) consumer.py def connect(self): user = self.scope["user"] if user.is_anonymous: self.close() … -
modèle d’utilisateur personnalisé en cours de projet - django [closed]
j'ai voulu mdifier le modele User de mon projet aprés deploiement.En raison des limites de Django liées à la fonctionnalité de dépendance dynamique pour les modèles remplaçables , je n'ai pas voulu prendre le risque d'avoir des erreurs de migrations ou des erreurs liées a la base de donnée. Ce que je voulais c'est mettre le champ email de User a unique et d'enlever le blank=True et ensuite creer un moteurs d’authentification basée sur le champ email et mot de passe. Ce que j'ai fais c'est de modifier le code source de models.py dans "virtual_env_name/lib/python3.8/site-packages/django/contrib/auth." Dans le champ email j'ai enlevé blank=True et j'ai mis unique=True et cela a marcher. Ma question est : est ce une bonne idee de modifier le code source de models.py dans lib/python3.8/site-packages/django/contrib/auth -
IntegrityError at UNIQUE constraint failed: sales_salesitem.product_id django
Hello there anyone and everyone! I'm stuck at a point and getting the error: IntegrityError at /meet/report_meeting/sales_person/1/customer/1/product/1/meeting_request/1/ UNIQUE constraint failed: sales_salesitem.product_id I'm getting this error when trying to use the create() method in the following snippet, like the following: def report_meeting(request, product_id, customer_id, sales_person_id, request_id): form = ReportMeetingForm() sales_person = Sales_person_profile.objects.get(id=sales_person_id) customer = Customer_profile.objects.get(id=customer_id) product_under_discussion = Product.objects.get(id=product_id) if request.method == "POST": form = ReportMeetingForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.sales_person = sales_person instance.customer = customer instance.product_under_discussion = product_under_discussion sales_person.consulted_cases += 1 cd = form.cleaned_data if cd['sale_closed'] == False and cd['follow_up'] == True: instance.number_of_follow_ups += 1 instance.save() elif cd['sale_closed'] == True and cd['follow_up'] == False: sales_person.sales_completed += 1 instance.save() sales_item = SalesItem.objects.create( product= product_under_discussion, meeting= instance, quanity= cache.get('quantity') ) else: print(form.errors) return redirect("accounts:dashboard") else: form = ReportMeetingForm() context = { 'form': form, } return render(request, 'chat/report_meeting.html', context) Now the funny thing is, I think, instance is being saved flawlessly, which means that the product_under_discussion has the product object. But when the same is delivered to the create method, it gives me the error. According to my experience, this will error will raise if I'm not giving a Product instance. Maybe I'm wrong with my concept somewhere. Anyhow, this is the SalesItem … -
GeoDjango Admin Widget for GeometryCollection?
Is it possible to have an editable widget in the GeoDjango Admin for a GeometryCollectionField? Consider the following code: models.py: from django.db import models from django.contrib.gis.db import models as gis_models class MyModel(gis_models.Model): name = models.CharField(max_length=64, blank=False, null=False) point = gis_models.PointField(blank=False, null=False) polygon = gis_models.PolygonField(blank=False, null=False) geometry = gis_models.GeometryField(blank=False, null=False) geometry_collection = gis_models.GeometryCollectionField(blank=False, null=False) admin.py: from django.contrib import admin from django.contrib.gis import admin as gis_admin from my_project.models import MyModel @admin.register(MyModel) class MyModelAdmin(gis_admin.GeoModelAdmin): fields = ( "name", "point", "polygon", "geometry", "geometry_collection", ) This gives me editable widgets for all fields except for geometry_collection: Any hints? -
Django using 2 different databases during tests
Using: Django 4.0.4 Python 3.9.13 Running: python ../../manage.py test website.functional_tests.test_loggedOutUser.HomePageTest.test_user_email_registration Files: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'ProdComment': 'This is the PROD DB.', 'TEST': { 'NAME': BASE_DIR / 'TEST_.db.sqlite3', 'MIRROR': 'default', 'COMMENT': "This is the TEST DB.", }, } } test_loggedOutUser.py content: from selenium import webdriver from django.test import TestCase as TC from django.db import connections as DBC from django.db import connection as DBCON from allauth.utils import get_user_model as getusermodel import time from django.core.exceptions import ObjectDoesNotExist allUsersALLAUTH = getusermodel() # Method used to check if a test user exists in the DB and then delete this user # Test if account creation works. # Returns 1 if user does not exist, 0 if deleted successfully. def delTestUser(): username = 'TheTester' allUsersALLAUTH = getusermodel() print("DELTESTUSER, allUsersALLAUTH.objects.all(): ", allUsersALLAUTH.objects.all()) print("DELTESTUSER, Testing if we can delete the test user.") try: userToDelete = allUsersALLAUTH.objects.get(username=username) print("DELTESTUSER, usertodelete: ", userToDelete) except ObjectDoesNotExist: print("DELTESTUSER, The user you tried to find does not exist.") # Trying to see which DB is used to no avail. print("DELTESTUSER: ", DBC.databases['default']['NAME']) return 1 else: print("DELTESTUSER - ELSE: ", DBC.databases['default']['NAME']) print("DELTESTUSER, We found the user and can delete him.") userToDelete.delete() print("DELTESTUSER, The user has now been … -
Bad Request Django upload CSV by chunks
I'm trying to upload a csv to an endpoint using Django. The csv is not linked to any Model, just is needed to trigger a celery task. The thing is that I'm getting a Bad Request and django is not providing me any more information. The uploaded file needs to be done in chunks and the code to upload is the following using the python requests library import os import requests import pdb def read_in_chunks(file_object, chunk_size=1024): while True: data = file_object.read(chunk_size) if not data: break yield data def main(file, URL): content_name = str(file) content_path = os.path.abspath(file) content_size = str(os.stat(content_path).st_size) f = open(content_path) index = 0 offset = 0 headers = {} for chunk in read_in_chunks(f): offset = index + len(chunk) headers['Content-Type'] = 'application/octet-stream' headers['Content-length'] = content_size headers['Content-Range'] = 'bytes %s-%s/%s' % (index, offset, content_size) index = offset file = {"file": chunk} try: r = requests.put(url, files=file, headers=headers) except Exception as e: print(str(e)) if __name__ == '__main__': url = 'http://127.0.0.1:8000/task/upload' main('test_upload.csv', URL) And executing like this: python3 test_upload.py Here is the view: class TaskUploadView(APIView): def put(self, request): ## NOT TESTED CODE, SINCE IT DOES NOT REACH THIS POINT parser_classes = (FileUploadParser,) f = request.FILES['file'] with open('test.csv', 'wb+') as destination: for chunk … -
Django third party authentication with Okta not changing users between logout and login with new user
I'm creating an app with Django v. 4.0.3 and using third party authentication with Okta. I have used the package django-okta-auth to aid with the connection to Django's built in authentication. The issue I have encountered is when a user logs out and a new user logs in, it is still the original user that is logged into the system. I have followed this tutorial exactly: https://pypi.org/project/django-okta-auth/ How can I add onto the logout function within the package django-okta-auth to ensure users are logged out correctly? Is this an issue with cookies needing to be cleared upon logout? There will be multiple users using the same browser (not concurrently but after login and out) so this is a necessity in the app. -
How to optimize a server request that has to send back several items with dynamic attributes that need to be calculated every time a user requests it?
I have an Angular UI app connecting to a Django API that uses GraphQL (using Graphene) and Postgres for DB. My application has many courses and each course can have several chapters. The users signing in can see access courses and not others because a course could have a prerequisite. So they will see a course listed but it will be "locked" for them and a message will say that they need to complete the particular prerequisite before it can be accessed. Like this, we need some other attributes to be sent along with the list of courses:- 'locked' - Boolean - whether a course is locked for the current logged-in user or not. 'status' - ENUM - Pending/Completed 'completed' - Boolean - whether the course is completed or not When a user requests the list of courses, these 3 attributes are calculated for each item in the list before it is compiled and sent back to the user. And this is done for each of the chapters inside the course too. And the chapter might contain upto 30 chapters or so. So this really takes a LOT of time! I've implemented caching as well, but because these values change … -
How to define a field of a model to have a choice from another field of another model of another app?
I have two models defined in two different apps. I want to have a choice option for a particular field in a model, which is deriving those attributes from another field of a model in another app. eg: I have a model "Inventory" that has a field 'title'. class Inventory(models.Model): title = models.CharField('Title', max_length=120, default='') .... I also have another model 'Invoice' that has a field 'line_one'. Both these models are located in different apps. class Invoice(models.Model): line_one = models.CharField('Line 1', max_length=120) .... I created a Django form for adding the Invoice details. I want a choice option for line_one that has all the values stored in the Inventory.title field so that the user can only select those values from a dropdown menu. How can I implement this? Thanks. -
Venda matching query does not exist
ês I don't know how to fix this little problem, I tried to change and change the form, but I still don't understand why it is not reading froms=sales , and when I looked for the error in depth it gave: order_forms Error in formatting: TypeError: unsupported format string passed to NoneType.format> ** MY models ** numero_ven = models.AutoField('Número sequencial da venda',primary_key=True) data_ven = models.DateTimeField('Data e hora da venda',auto_now_add=True,auto_now=False) nf_ven = models.IntegerField('NF',null=True,blank=True) cliente_ven = models.ForeignKey('core.Customer',db_column='cliente_ven',related_name='customer_sale',on_delete=models.CASCADE) formapag_ven = models.ForeignKey(CondPag,db_column='formapag_ven',related_name='forma_pag',on_delete=models.CASCADE) usuario_ven = models.ForeignKey('users.User',db_column='usuario_ven',related_name='usuario_sale',on_delete=models.CASCADE) desconto_ven = models.DecimalField('Desconto',max_digits=7,decimal_places=2,null=True,blank=True) condicao_ven = models.IntegerField('Condição',null=True,blank=True) obs_ven = models.TextField('Observações',blank=True,null=True) frete = models.DecimalField('Frete',max_digits=7,decimal_places=2,null=True,blank=True) seguro = models.DecimalField('Seguro',max_digits=7,decimal_places=2,null=True,blank=True) despesas_acess = models.DecimalField('Despesas acessórias',max_digits=7,decimal_places=2,null=True,blank=True) codigo_transport = models.IntegerField('Código Transporte',null=True,blank=True) placa_veic = models.CharField('Placa veículo',max_length=10,null=True,blank=True) uf_veic = models.CharField('UF veículo',max_length=2,null=True,blank=True) frete_por_conta = models.CharField('Frete por conta',max_length=1,null=True,blank=True) marca = models.CharField('Marca',max_length=10,null=True,blank=True) especie = models.CharField('Espécie',max_length=10,null=True,blank=True) numeracao = models.CharField('Numeração',max_length=10,null=True,blank=True) prev_entrega = models.DateTimeField('Data e hora da previsão de entrega',auto_now_add=True,auto_now=False) setor_ven = models.IntegerField('Setor',null=True,blank=True) precosetor_ven = models.IntegerField('Preço setor',null=True,blank=True) datanfsai_ven = models.DateTimeField('Data e hora da Nota Fiscal',auto_now_add=True,auto_now=False) horanfsai_ven = models.DateTimeField('Data e hora da Nota Fiscal',auto_now_add=True,auto_now=False) imprime_romaneio_ven = models.CharField('Imprime romaneio',max_length=1,null=True,blank=True) cupom_impresso_ven = models.CharField('Cumpom Impresso',max_length=1,null=True,blank=True) prestador_serv_ven = models.IntegerField('Prestador serviço',null=True,blank=True) usuario_atu_ven = models.IntegerField('Usuário atual',null=True,blank=True) data_atu_ven = models.DateTimeField('Data e hora da atualização da venda',auto_now_add=True,auto_now=False) hora_atu_ven = models.DateTimeField('Data e hora da atualização da venda',auto_now_add=True,auto_now=False) cupom_ven = models.IntegerField('Cupom',null=True,blank=True) qtd_vol_ven = models.IntegerField('Quantidade volume',null=True,blank=True) num_venda_antecip_ven … -
Error with form.non_field_errors are not displayed
I try show errors without fieldname identifier. For this i run in template {{ form.non_field_errors }}. But error not displayed. If i run with form.errors the erros are displayed, but with fieldname too, it's not what i want. I use AbstractBaseUser like: models.py class User(AbstractBaseUser): username = models.CharField( verbose_name = u'Nome', max_length=33 ) #identifier email = models.EmailField( verbose_name = u'Email', max_length=255, unique=True, ) phone = models.CharField( verbose_name = u'telefone', max_length=12 ) #... forms.py class SignupForm(UserCreationForm): username = forms.CharField( label=False, max_length=100, required=True, widget=forms.TextInput( attrs={ 'placeholder': 'Nome', 'autocomplete':'off', } )) email = forms.EmailField( label=False, required=True, widget=forms.TextInput( attrs={'placeholder': 'Email'} )) email_confirmation = forms.EmailField( required=True, widget=forms.TextInput( attrs={ 'placeholder': 'Confirme o email', 'id': 'email_confirmation', 'class': 'input cemail-cad' } )) phone = forms.CharField( label=False, required=True, widget=forms.TextInput( attrs={'placeholder': 'Telefone'} )) password1 = forms.CharField( label=False, max_length=50, required=True, widget=forms.PasswordInput( attrs={'placeholder': 'Senha'} )) password2 = forms.CharField( label=False, max_length=50, required=True, widget=forms.PasswordInput( attrs={'placeholder': 'Confirme sua senha'} )) class Meta: model = User fields = ['username', 'email', 'phone', 'password1', 'password2'] def clean_username(self): # mínimo 2 caracteres máximo 150 caracteres if not re.compile(r'^\S*[\w\.\-\_\d]{3,150}').match(str(self)): raise ValidationError("Nome inválido: Mínimo 3 caracteres, somente letras, números e '.', '-' ou '_' especiais") def clean_email(self): cleaned_data = super(SignupForm, self).clean() email = cleaned_data.get('email') email_confirmation = cleaned_data.get('email_confirmation') if email != email_confirmation: …