Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Class to log a mail error
I'm trying to follow the code for Django Unleashed and occasionally (by which I mean often) I have problems to understand the code in full. Here is an exaple of a function that is suppose to log errors when a certain mail does not sent. It is part of a login system. def log_mail_error(self, **kwargs): msg_list = [ 'Activation email did not send.\n', 'from_email: {from_email}\n' 'subject: {subject}\n' 'message: {message}\n', ] recipient_list = kwargs.get( 'recipient_list', []) for recipient in recipient_list: msg_list.insert( 1, 'recipient: {r}\n'.format( r=recipient)) if 'error' in kwargs: level = ERROR error_msg = ( 'error: {0.__class__.__name__}\n' 'args: {0.args}\n') error_info = error_msg.format( kwargs['error']) msg_list.insert(1, error_info) else: level = CRITICAL msg = ''.join(msg_list).format(**kwargs) logger.log(level, msg) I have a very hard time with one part: error_msg = ( 'error: {0.__class__.__name__}\n' 'args: {0.args}\n') error_info = error_msg.format( kwargs['error']) I simply don't see where this 0.class.name comes from. What is the zero suppose to mean? There is no object or class called zero in the project. Also I dont really understand the formatting of the error_msg. Potentially I have two fields with {} {} where I could fit "kwargs['error']" but I only have one value to fit into two places for string formatting. But then agian, … -
TemplateDoesNotExist at /polls/1/
I got an error, TemplateDoesNotExist at /polls/1/ templates/polls/detail.html . I wanna show detail.html. Traceback is Traceback: File "/Users/XXX/django/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 130. response = self.process_exception_by_middleware(e, request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 128. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/XXX/djangostudy/polls/views.py" in detail 43. 'question': obj, File "/Users/XXX/django/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/Users/XXX/django/django/template/loader.py" in render_to_string 61. template = get_template(template_name, using=using) File "/Users/XXX/django/django/template/loader.py" in get_template 19. raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /polls/1/ Exception Value: templates/polls/detail.html My forms.py is like from django import forms class MyForm(forms.Form): text = forms.CharField(max_length=100,required=False,label='テキスト') class VoteForm(forms.Form): choice = forms.ModelChoiceField( queryset=None, label='選択', widget=forms.RadioSelect, empty_label=None, error_messages={ 'required':"You didn't select a choice.", 'invalid_choice':"invalid choice.", }, ) def __init__(self,question,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['choice'].queryset = question.choice_set.all() Setting of radio button is written in detail.html,like <!DOCTYPE html> <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'poll_vote' question.id %}" method="post"> <!--<form action="" method="post">--> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <!--{{ form }}--> <input type="submit" value="Vote" /> </form> </html> views.py is from django.shortcuts import render from … -
Error computing aggregate over related model in Django
I have the following models: class Contest(models.Model): id_contest = models.AutoField(primary_key=True) name = models.CharField(max_length=50, blank=False) class Registration(models.Model): id_registration = models.AutoField(primary_key=True) team = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='registrations', related_query_name='registration') contest = models.ForeignKey( Contest, on_delete=models.DO_NOTHING, related_name='registrations', related_query_name='registration') created_at = models.DateTimeField(null=True) confirmed_at = models.DateTimeField(null=True) class Submission(models.Model): id_submission = models.AutoField(primary_key=True) team = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='submissions', related_query_name='submission') contest = models.ForeignKey( Contest, on_delete=models.DO_NOTHING, related_name='submissions', related_query_name='submission') submitted_at = models.DateTimeField(null=True) is_valid = models.NullBooleanField() public_score = models.FloatField(null=True) And I'm working on a leaderboard query (PostgreSQL) like: select r.team_id, max(t.username) as team_name, count(*) as num_submissions, min(s.public_score) as score, max(s.submitted_at) as last_submission, max(r.confirmed_at) as confirmation from api_registration r left join auth_user t on (r.team_id = t.id) left join api_submission s using (contest_id) where r.contest_id = 1 and s.is_valid = TRUE group by r.team_id order by score ASC, last_submission DESC; Which returns the results I want. However, when translating into Django QuerySet operations, the closest I've come is: leaderboard = Registration.objects \ .filter(contest=contest, contest__submission__is_valid=True) \ .annotate(team_name=Max('team__username'), num_submissions=Count('team__submission'), score=Max('contest__submission__public_score'), last_submission=Max('contest__submission__submitted_at'), confirmation=Max('confirmed_at')) \ .order_by('score', '-last_submission') which generates the query: SELECT "api_registration"."id_registration", "api_registration"."team_id", "api_registration"."contest_id", "api_registration"."created_at", "api_registration"."confirmed_at", MAX("api_registration"."confirmed_at") AS "confirmation", MAX("api_submission"."submitted_at") AS "last_submission", MAX("auth_user"."username") AS "team_name", MAX("api_submission"."public_score") AS "score", COUNT(T5."id_submission") AS "num_submissions" FROM "api_registration" INNER JOIN "api_contest" ON ("api_registration"."contest_id" = "api_contest"."id_contest") INNER JOIN "api_submission" ON ("api_contest"."id_contest" = … -
DB constantly exploding in Django
I am trying to get going with django, which so far I have found to be amazing other than repeated db issues. My latest is following the Django by Example book and I have followed everything to the letter, yet when following some simple instructions to add some data via the python shell api I get the following: >>> from django.contrib.auth.models import User >>> from blog.models import Post >>> user = User.objects.get(username='jamie') >>> Post.objects.create(title='One More Post', slug='one-more-post', body='Post body', author='user') Traceback (most recent call last): File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle self.run_shell(shell=options['interface']) File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell raise ImportError ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/query.py", line 346, in create obj = self.model(**kwargs) File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/base.py", line 468, in __init__ setattr(self, field.name, rel_obj) File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 629, in __set__ self.field.rel.to._meta.object_name, ValueError: Cannot assign "'user'": "Post.author" must be a "User" instance. This has happened while following multiple tutorials and I am stumped. I followed standard instructions and installed, pip, python and django via terminal. Also using a virtual env so not sure why this is … -
Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance
I am really stuck overwhat is going on. Basically, i want to let the user change his phone number. He have to input just his current password and a new phone number. I want to pass the user to the init function so his current password can be validated along the way. But it gives me the above error message. My serializers.py is: class ChangePhoneSerializer(serializers.Serializer): ''' Change my phone number ''' password_current=serializers.CharField(max_length=16,allow_blank=False,required=True) new_phone=serializers.CharField(max_length=13,required=True,allow_blank=False) def __init__(self,*args,**kwargs): self.user=kwargs.pop('user') def validate(self,data): phone=data['new_phone'] pwd_current=data['password_current'] errmsg='' if not pwd_current: errmsg=str(_('Current password must be given')) else: if not self.user.check_password(pwd_current): errmsg=_('Current password is incorrect') if errmsg: raise serializers.ValidationError(errmsg) return data In my views.py: data=request.data serializer=ChangePhoneSerializer(user=request.user,data=data) if serializer.is_valid(): #do stuff to change the phone But it gives me hte above error. It was working fine when I wasn't use serializers. -
How to copy csv file to database using django
I have Django model as follows: class TraxioRelations(models.Model): code = models.CharField(max_length=20, null=True) matchcode = models.CharField(max_length=20, null=True) hfdhuis = models.CharField(max_length=100, null=True, blank=True) cornaam1 = models.CharField(max_length=100, null=True, blank=True) cornaam2 = models.CharField(max_length=100, null=True, blank=True) coradres = models.CharField(max_length=255, null=True, blank=True) corhuisnr = models.CharField(max_length=10, null=True, blank=True) corpostcode = models.CharField(max_length=10, null=True, blank=True) corgemeente = models.CharField(max_length=100, null=True, blank=True) corland = models.CharField(max_length=10, null=True, blank=True) cortaal = models.CharField(max_length=10, null=True, blank=True) coremail = models.EmailField(null=True, blank=True) cortelefoon = models.CharField(max_length=50, null=True, blank=True) corgsm = models.CharField(max_length=50, null=True, blank=True) corfax = models.CharField(max_length=50, null=True, blank=True) faknaam1 = models.CharField(max_length=100, null=True, blank=True) faknaam2 = models.CharField(max_length=100, null=True, blank=True) fakadres = models.CharField(max_length=255, null=True, blank=True) fakhuisnr = models.CharField(max_length=10, null=True, blank=True) fakpostcode = models.CharField(max_length=10, null=True, blank=True) fakgemeente = models.CharField(max_length=100, null=True, blank=True) fakland = models.CharField(max_length=10, null=True, blank=True) faktaal = models.CharField(max_length=10, null=True, blank=True) fakemail = models.EmailField(null=True, blank=True) faktelefoon = models.CharField(max_length=50, null=True, blank=True) fakgsm = models.CharField(max_length=50, null=True, blank=True) fakfax = models.CharField(max_length=50, null=True, blank=True) btwnr = models.CharField(max_length=50, null=True) weburl = models.CharField(max_length=100, null=True, blank=True) groep1 = models.CharField(max_length=100, null=True, blank=True) groep2 = models.CharField(max_length=100, null=True, blank=True) relatiecode = models.CharField(max_length=100, null=True, blank=True) geldig = models.CharField(max_length=100, null=True, blank=True) credatum = models.DateField(null=True, blank=True) crevest = models.CharField(max_length=100, null=True, blank=True) creuser = models.CharField(max_length=100, null=True, blank=True) upddatum = models.DateField(null=True, blank=True) updvest = models.CharField(max_length=100, null=True, blank=True) upduser = models.CharField(max_length=100, null=True, blank=True) typefiliaal = models.CharField(max_length=100, null=True, … -
Docker image is not binding to port
I am using Django with Docker on windows to build my web app. I using Docker-toolbox and I am able to run the web through "docker-compose up" on my local machine. I am able also to create an image successfully, however I am not able to run my web app from the image itself using "docker run -p [new-port]:[old-port] [image_name]". It doesn't look even there is any binding to the new port after checking "netstat -t". I am new to Docker and I can't figure out whats wrong. DockerFile: FROM python:3 ENV PYTHONUNBUFFERED 1 ENV COMPOSE_CONVERT_WINDOWS_PATHS 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ Docker-compose.yml version: '2' services: nginx: image: nginx:latest container_name: ng01 ports: - "8000:8000" volumes: - .:/code - ./nginx:/etc/nginx/conf.d - ./myapp/static:/static depends_on: - web db: image: postgres container_name: ps01 web: env_file: docker.env container_name: dg01 build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn myapp.wsgi -b 0.0.0.0:8000" volumes: - .:/code - ./myapp/static:/static expose: - "8000" depends_on: - db -
Cannot load a static file
I cannot load files from static-folder “todo.js”. My project-tree and settings.py: index.html <!DOCTYPE html> <html> <head> <title>to do</title> {% load static %} </head> <body> <script src="{% static 'js/todo.js' %}" type="text/javascript"></script> </body> </html> and console gives me the following [21/Aug/2017 16:36:15] "GET /static/js/todo.js HTTP/1.1" 404 1643 -
Django language for dynamic fields
<table class="table"> <tr> {% for item in summary.titles %} <th>{{item }}</th> {% endfor %} </tr> <tr> {% for title in summary.titles %} <td> {{ summary.data[title] }}</td> {% endfor %} </tr> </table> Is it possible to get data in a similar way? Exception Value: Could not parse the remainder: '[title]' from 'summary.data[title]' var summary = { data:{ title1: 1, title2:2 }, titles: [title1, title2] } -
collections.Counter behavior with Django ORM queries
I am trying to get the same result we can see from using a collections.Counter but with a query, if that's possible. I was looking at using aggregations and annotations but I don't think they can help in my scenario. In the context of a single-elimination tournament made up of matches that belong to a fixture (1st round, quarter-final, final...), note that a fixture can be made up of either one match (tennis tournament) or multiple matches (NBA playoffs): class Match(models.Model): fixture = models.ForeignKey('Fixture', null=True) I have a particular QuerySet of matches, and I need to groupe these by fixture and the number of matches found in that QuerySet that belong to the same fixture, for example: [<Match 1 - Quarterfinals 2>, <Match 2 - Quarterfinals 2>, <Match 4 - Quarterfinals 1>] should produce: {<Quarterfinals 2>: 2, <Quarterfinals 1>: 1} This is how I could achieve it: d = collections.Counter(matches.values_list('fixture', flat=True)) d = {Fixture.objects.get(id=f): c for f, c in d.iteritems()} I wonder if I can achieve a similar result just using a Django query (without resorting to a Counter) and ideally without having to hit the database again to fetch each Fixture (is there a way for values_list to return … -
django channel set up routing
I'm learning how to setup a websocket connection with django-channel, i've got this setup in routing.py from channels import route from gallery import socket as sock channel_routing = [ # Wire up websocket channels to our consumers: route("websocket.connect", sock.ws_connect, path=r"^/render-status/$"), route("websocket.receive", sock.ws_receive, , path=r"^/render-status/$"), ] and the following javascript // When we're using HTTPS, use WSS too. var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var ws_path = ws_scheme + '://' + window.location.host + '/render-status/'; console.log("Connecting to " + ws_path) var socket = new ReconnectingWebSocket(ws_path); socket.onmessage = function(message) { console.log("Got message: " + message.data); var data = JSON.parse(message.data); // if action is started, add new item to table if (data.action == "started") { } // if action is completed, just update the status else if (data.action == "completed"){ } }; var message = { action: "incomplete", job_name: "10", }; socket.send(JSON.stringify(message)); tried it out and there's a failure in connecting (from the console) colorpicker2.js:565 Connecting to ws://127.0.0.1:8000/render-status/ reconnecting-websocket.min.js:1 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at a.send (http://127.0.0.1:8000/static/js/reconnecting-websocket.min.js:1:2611) at HTMLDocument.<anonymous> (http://127.0.0.1:8000/static/js/colorpicker2.js:584:11) at k (http://127.0.0.1:8000/static/js/jquery.js:15:16962) at Object.fireWith [as resolveWith] (http://127.0.0.1:8000/static/js/jquery.js:15:17720) at Function.ready (http://127.0.0.1:8000/static/js/jquery.js:15:12435) at HTMLDocument.D (http://127.0.0.1:8000/static/js/jquery.js:15:9840) send @ reconnecting-websocket.min.js:1 (anonymous) @ colorpicker2.js:584 k @ jquery.js:15 … -
Django ORM - building hierarchical data structure with multiple models
as a part of a project I'm working on, I'm trying to build an hierarchical data structure of objects from different types. I used django-mptt for it, which promises to handle trees in a smart way with fast queries. The problem is, that I have multiple models that needs to participate in this data tree, so I used generic relation in order to store the required data. A snippet of the model I built: class CPNode(MPTTModel): content_type = models.ForeignKey(ContentType, null=True, blank=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) ... This gives me what i want, except of the query issue. I figure that to query all the data will cost multiple queries (each time I would like to get the content_object itself). Does anyone has an idea of how I can maintain this structure, and at the same time being able to get all the data in a scalable query? -
Create custom Database Connection in Django
I am creating a project in DJango where I want to use a mixture of MySQL and ArangoDB. I am creating an API based on DJango REST Framework. The Process for ArangoDB User calls an API and request enters in the VIEW View validates the request.data via serializers If data is valid, .save() is called which saves the data in ArangoDB. I won't use Models as there is no schema (that's why using NoSQL). The Problem How can I create a global connection with ArangoDB that I can use everywhere else? Will the connection with ArangoDB be active or I need to re-connect? What should I do? -
how to use queryset filter attribute depending on array in django?
if i have : data= request.data['participants'] Conversation.objects.filter(participants = data).values() where data is an array of participants, i want to get conversations which have those participants in. i want compare an array to a foreign key(one to many) to get conversation which contains those participants. { "conversation_id": 38, "created_at": "2017-08-14T09:15:19.776000Z", "name": "first conversation", "participants": [ { "id": 1, "username": "zezor93", }, { "id": 64, "username": "tasus22", } ] } -
Celery freezes on heroku and resumes only after Node server is restarted
We are running two apps on heroku - python(django) and node. Both use celery to do some asynchronous tasks. We've started to get a situation where celery workers freeze. Celery Flower shows offline workers even when heroku ps shows them to be up. When we check RabbitMQ management dashboard we see publish rate to be more than deliver rate implying connections piling over and eventually publish and deliver rate falling to 0. Sometimes it resumes on its own but most of the times the only way celery resumes again is after restarting Node server manually. We are using New Relic but we aren't able to make any useful information out of it apart from observing few notorious spikes in request and response times. We also are using websockets to push events from backend. There are too many App crashed errors around websocket APIs as well. I need some advice around how can I debug this problem. Where to find any logs related to rabbitmq? How to setup events and states logging or monitoring for a particular app? I understand that there is not much technical info here. But I'ld appreciate any help. Should you need any info let me know … -
python - Django Translation of class variables
Under the ActivationKey class, I generate a random key with a key variable of 50 characters. I do this to confirm the e-mail. The point I attach is that when I create a servlet key that will be a key variable (such as verification / {key}) that has a url generator and a key that is somewhere in the variable and a variable (such as verification / {key}) then I will not create a link using this url (like verficaton / asasaassassassassassa) When I click on the URL in the structure I specify for the view will work, key control and verifiyicek. I need to write a view using RedirectView that will perform only one operation and will go somewhere else; URLs view I do not know how to make models.py like the following. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name=_('Email'), max_length=255, unique=True ) first_name = models.CharField(verbose_name=_('First Name'), max_length=50) last_name = models.CharField(verbose_name=_('Last Name'), max_length=50) is_active = models.BooleanField(verbose_name=_('Active'), default=True) is_staff = models.BooleanField(verbose_name=_('Staff'), default=False) is_verify = models.BooleanField(verbose_name=_('Verify'), default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] class Meta: verbose_name = _('User') verbose_name_plural = _('Users') def __str__(self): return self.get_full_name() def get_full_name(self): return '{first_name} {last_name}'.format( first_name=self.first_name, last_name=self.last_name ) def get_short_name(self): return '{first_name}'.format(first_name=self.first_name) … -
'method' object has no attribute 'inner_html'
I have made a web site by seeing django tutorial. https://docs.djangoproject.com/en/1.11/intro/ I got an error AttributeError at /polls/1/ 'method' object has no attribute 'inner_html' . Traceback says Traceback: File "/Users/XXX/django/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 130. response = self.process_exception_by_middleware(e, request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 128. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/XXX/djangostudy/polls/views.py" in detail 40. form = VoteForm(question=obj) File "/Users/XXX/djangostudy/polls/forms.py" in __init__ 21. self.fields['choice'].widget.render.inner_html = '{choice_value}{sub_widgets}<br>' Exception Type: AttributeError at /polls/1/ Exception Value: 'method' object has no attribute 'inner_html' My forms.py is like from django import forms class MyForm(forms.Form): text = forms.CharField(max_length=100,required=False,label='テキスト') class VoteForm(forms.Form): choice = forms.ModelChoiceField( queryset=None, label='選択', widget=forms.RadioSelect, empty_label=None, error_messages={ 'required':"You didn't select a choice.", 'invalid_choice':"invalid choice.", }, ) def __init__(self,question,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['choice'].queryset = question.choice_set.all() self.fields['choice'].widget.render.inner_html = '{choice_value}{sub_widgets}<br>' Setting of radio button is written in detail.html,like <!DOCTYPE html> <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'poll_vote' question.id %}" method="post"> <!--<form action="" method="post">--> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <!--{{ form }}--> <input type="submit" value="Vote" /> </form> </html> views.py is from django.shortcuts import render … -
for all model structure: AttributeError: 'str' object has no attribute '_meta' , why?
for all model structures in my project, I have this Error AttributeError: 'str' object has no attribute '_meta' why? in other project don't have this Error -
django-filter, ordering objects of many to many field
I am working on API, written in django. I have models similar to: class foodprices(models.Model): price_description = models.TextField(blank=True,null=True) price = models.FloatField(max_length=8) class food(models.Model): name = models.Charfield(max_length=100) price_ids = models.ManyToManyField(foodprices,blank=True) #I have multiple prices for single food object In my views: class foodviewset(ModelViewSet): queryset = food.objects.all() serializer_class = food_serializer filter_backends = (filters.OrderingFilter) ordering_fields = ('price_ids__price',) This ordering will work fine if i only have single price for my food object. In my case, I want to order my food objects based on first price_id in my food table. I want to omit all other prices, except first while ordering. I want some thing like this ordering_fields = ('price_ids__price[0]',) Is it possible with inbuilt Django filters? Thank you. -
Multiple User authentication model on single Django project
I have a single Django project and 3 apps in my project. 1 app is for end user. 2 app is for service provider. 3 app is for system operator. and I want to use django authentication system each apps. But I have no idea how can I make settings in order to do this. In settings.py, I must write something like this. AUTH_USER_MODEL = 'users.User' But I think I can write only one model. How can I write 3 authentication model? Please let me know. -
Django get all child and subchilds of a parent
i have a model that have self-referenced to itself , i want to get all child and child of child and so on in one query. is there any queryset to get all child related to a parent ? -
Custom Errors and logging Errors to console
I have the following code: logger = logging.getLogger(__name__) class PostCreate(PostGetMixin, View): form_class = PostForm model = Post template_name = 'blog/post_form.html' def get(self, request): return TemplateResponse(request, self.template_name, {'form': self.form_class()}) def post(self, request): bound_form = self.form_class(request.POST) if bound_form.is_valid(): new_post = bound_form.save() return redirect(new_post) else: if bound_form.errors: for err in bound_form.errors: level = INFO msg = 'Error: {}'.format(err) logger.log(level, msg) return render(request, self.template_name, {'form': bound_form}) What I'm trying to do is, log when a user submits something via POST and recieves an error. The logger should print the error message to the console. But it doesn't work and I dont know why (can someone help?). Also I want the error description in the log message. With the current code I assume the log message will print the 'Key' value for the fields where the error occured e. g. 'name' or 'slug' - since bound_form_errors should return a DICT. But I do try to display the error message in the log. from .log_filters import ManagementFilter verbose = ( "[%(asctime)s] %(levelname)s " "[%(name)s:%(lineno)s] %(message)s") LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'remove_migration_sql': { '()': ManagementFilter, }, }, 'handlers': { 'console': { 'filters': ['remove_migration_sql'], 'class': 'logging.StreamHandler', }, }, 'formatters': { 'verbose': { 'format': verbose, … -
Using JavaScript library installed via npm in Django template
I have rudimentary experience with JavaScript, centered around predominantly using JQuery. In a Django project I'm building, I typically import my JQuery code into a Django template like so: <script type="text/javascript" src="{{ STATIC_URL }}js/preloader.js"></script>. Now I need to use a JS library that's installed via npm. Specifically this one: github.com/brunobar79/J-I-C. It's job is to compress user uploaded on the client-side before uploading them to the server. E.g. I can do target_img.src = jic.compress(source_img,quality,output_format).src;. But how would I call this compress method in my template? As in, where/how do I import it? Should I dump all the library's code in a separate file and import it via <script type="text/javascript" src="{{ STATIC_URL }}js/JIC.min.js"></script>? If I were to do that, then why install the library via npm at all? Like I said, my knowledge in this domain is rudimentary. Would be great to get an illustrative example that clears my concept. Sorry for the noob question (if it is). -
Django - Add Empty Form in Tabular Format
I have a template: <form method="post" action=""> {% csrf_token %} {{ modelformset.management_form }} <div id="form_set"> {{ modelformset.non_form_errors.as_ul }} <table id="formset" class="form"> {% for form in modelformset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> </div> <input type="button" value="Add More" id="add_more"> <input type="submit" value="Submit"> <div id="empty_form" style="display:none"> <table id="formset" class="form"> {% for form in modelformset.empty_form %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> {% if messages %} <ul class="messages"> {% for message … -
Django.How to preserve data in form fields after page reload?
When i submit my form it clears my form field values. I tried to set the initial data in the form constructor, but ut says that the form object IS NOT CALLABLE form_class = self.get_form_class() self.form = self.get_form(form_class(initial = get_data)) context = self.get_context_data(object_list=self.object_list, form=self.form, collapse=collapse) return self.render_to_response(context)