Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Recaptcha (v2) - using captcha in modal rendered by ajax
So I use this package: https://github.com/praekelt/django-recaptcha I render modal with for in AJAX-based list view: {% for object in object_list %} <div id="offer-{{ object.id }}" class="modal fade services-modal" role="dialog"> <div class="modal-dialog"> <div class="modal-content shadow"> <div class="offer-box"> <div class="offer-box-head"> <div class="offer-slider"> <div class="swiper-wrapper"> {% if object.gallery.all %} {% for item in object.gallery.all %} {% thumbnail item.photo "800x530" crop="center" as img %} <div class="swiper-slide"><img src="{{ img.url }}" alt="offer image"></div> {% endthumbnail %} {% endfor %} {% else %} <div class="swiper-slide"><img src="{% static 'img/blank.png' %}" alt="offer image"></div> {% endif %} </div> <div class="offer-pagination-prev left-arrow"> <span class="ti-angle-left"></span> </div> <div class="offer-pagination-next right-arrow"> <span class="ti-angle-right"></span> </div> </div> <span class="offer-box-price">{{ object.price|floatformat:2 }} PLN</span> {% if object.featured %} <span class="offer-box-label"><span class="ti-star"></span>Polecane</span> {% endif %} </div> <div class="offer-content pl-30 pr-30"> <span class="h4 offer-box-title">{{ object.offer_type }} {{ object.surface|floatformat }}m2</span> <span class="offer-box-location"><span class="ti-location-pin"></span>{{ object.locality }}: {{ object.street }} </span> {% if object.year_built %} <span class="offer-box-meta">{{ object.year_built }}</span> {% else %} <span class="offer-box-meta">Brak daty zbudowania</span> {% endif %} <a class="close" data-dismiss="modal"><span class="ti-close"></span></a> <div class="contact-form mt-60"> <form method="post" action="{% url 'confirm_mail' %}"> {% csrf_token %} <div class="form-group"> {{ form_mail.author.errors }} <label for="{{ form.author.id_for_label }}">Autor</label> {{ form_mail.author }} </div> <div class="form-group"> {{ form_mail.email.errors }} <label for="{{ form.email.id_for_label }}">Email</label> {{ form_mail.email }} </div> <div class="form-group"> … -
Order data from database by two dates in django
I have a problem with ordering two dates in django model. I have a model which keep records of the document like below: class Document(models.Model): document_title = models.CharField(max_length=100) document = models.FileField() date_of_signature = models.DateField() date_of_rectification = models.DateField(null=True, blank=True) class Meta: ordering = ['-date_of_signature', '-date_of_rectification'] I have used the class Meta Options.ordering to order date and got result with ordering, but my specific problem is that: Ordering should be based on both fields if both fields have the date. But date_of_rectification can be a null value, so if it is null then ordering must be with latest date_of_signature which I didn't get with class Meta Options.ordering I have searched many questions on stackoverflow and found this MySQL query Mysql order items by the newest of 2 dates which exactly solved my problem in MySQL database and implemented this query on django Manager.raw() as below I got expected result. But this didn't help me on ordering data on Django Admin which is not my requirement. And also I want to know if this query could be solved using django Queryset insted of RawQueryset. Model.objects.raw("""SELECT * FROM document ORDER BY IF(date_of_rectification > date_of_signature, date_of_rectification, date_of_signature)""") -
Django translation check without running the project
Is there a simple way to check the correctness of translations in django.po file? (I don't mean to check it in the running project) -
Django bootstrap and paragraph
I'm facing a problem using Django / Bootstrap / RichText. When I start using Styles in CKEditor, my bootstrap style goes bad. In fact when I'm using several <p></p>, my layout goes wrong. My HTML File : {% for rule in rules %} <div class="content-section"> <div class="row bg-info"> <div class="col-sm-12 text-white"> <i class="fas fa-greater-than"></i> <a class="text-white" href="{% url 'rule-detail' rule.pk %}">{{ rule.title }}</a> </div> </div> <div class="row"> <div class="col-sm-2 align-middle text-center font-weight-bold"> {{ rule.reference }} </div> <div class="col-sm-10 text-justify"> {{ rule.content|safe|truncatechars:250 }} </div> </div> </div> <hr> {% endfor %} Rule source example : <p><cite>Style1</cite></p> <h1><cite>Style2</cite></h1> <p><cite><img alt="" src="https://i.kinja-img.com/gawker-media/image/upload/s--SGs2aMWj--/c_scale,f_auto,fl_progressive,q_80,w_800/jgpeuoavmn7pwbh98ycs.jpg" /></cite></p> <p>text here <strong> text there</strong> lorem ipsum</p> the first article is well displayed, but the second is shifted How can I handle this ? Thanks, -
How to retrieve a certain number of objects using Django Queryset
I need to obtain multiple objects(minimum 1, maximum 5) using the query - Document.objects.all().order_by('uploaded_at') I want to show the latest 5 or less objects. Any ideas? -
Django CMS: Plugin to app without ForiengKey
I'm new in CMS Django, and I'm trying to create a plugin which will be connected to Blog app. I want to show on every page 5 newest blog articles. Problem is that every plugin instance must be connected to some instance from blog app, because in our template we will use instance of plugin like: instance.article.all() or instance.blog.article.all(). Is some option to get instances of Article into the template of my BlogPlugins template without using instance of BlogPlugin? Thank you. -
Django logs with custom filter for username
I tried to create custom logging filter to log the username for each request like in the following link : django logging - django.request logger and extra context But my request has no user attribute. here is my code: class RequestUsernameFilter: def filter(self, record): request = record.request record.username = request.user.username return True The request attribute: AttributeError: 'socket' object has no attribute 'user' -
Mocking a SMS sending function in a class view Django
I am writing a Django class view that is supposed to run a few database checks, then create an object and send some information via SMS. The class is as follows: class MyClass(GenericAPIView): def send_info(content, number): send_sms(content, number) def post(self, request, *args, **kwargs): #... Do a bunch of stuff send_info(content, number) return Response(status=200, data="Request processed") Now I would like to test the view, of course I can't check whether and which the SMS is received. I do have a developement variable in settings.py that make sure for the moment that the info is just printed on screen, but I would like to use the unittest.mock library to write a test that simply checks whether send_info() is called, so that I won't be bother checking what info is passed (which is random). How would I go about it? -
Django Reverse with a named url
I feel like this is one that I shouldn't be having trouble with, but I'm stumped. I tried to Google around, but the every post I see has the issue in the template. I have the following in urls.py: path('AddStudent/thanks', views.thanks, name='AddStudentThanks') I have an FBV from another view that I want to link to that one. I can do it explicitly with return HttpResponseRedirect("AddStudent/thanks") but when I try to future-proof it and use the named url with the following code return HttpResponseRedirect(reverse("AddStudentThanks")) #go I get the following error & traceback NoReverseMatch at /advising/AddStudent Reverse for 'AddStudentThanks' not found. 'AddStudentThanks' is not a valid view function or pattern name. Request Method: POST Environment: Request Method: POST Request URL: http://127.0.0.1:8000/advising/AddStudent Django Version: 2.1.2 Python Version: 3.6.6 Installed Applications: ['advising.apps.AdvisingConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/ne573414/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ne573414/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/ne573414/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ne573414/Desktop/School/SD/proj/tnb/tnb/ETM_Advising/advising/views.py" in AddStudent 48. return HttpResponseRedirect(reverse("AddStudentThanks")) #go File "/home/ne573414/env/lib/python3.6/site-packages/django/urls/base.py" in reverse 90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/ne573414/env/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix 622. raise NoReverseMatch(msg) Exception Type: NoReverseMatch at … -
Django MultipleModelChoiceField gives me a ProgrammingError
I would like to get your help because I'm getting an issue which is a little bit weird to my mind. I'm using Django 1.11.16 I have in my forms.py file this class : class PublicationStatForm(forms.Form): # publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id')) publication_list = forms.ModelMultipleChoiceField( queryset=Publication.objects.all().order_by('pub_id'), label=_('Publication Choice'), widget=ModelSelect2Widget( model=Publication, search_fields=['pub_id__icontains', 'title__icontains'], attrs={'data-placeholder': "Please select publication(s)"} ) ) def __init__(self, *args, **kwargs): super(PublicationStatForm, self).__init__(*args, **kwargs) Then, in my views.py file : class StatsView(TemplateView): """ Create statistics pageview """ template_name = 'freepub/stats.html' form_class = PublicationStatForm def get_context_data(self, **kwargs): subtitle = _("Statistics") context_data = super(StatsView, self).get_context_data(**kwargs) context_data['form'] = self.form_class() ... return context_data And finally in my template, I just have : <form class="date-form" method="GET"> <div class="row"> <div class="col-md-7"> {{ form.publication_list }} </div> </div> <input id="submit-date-stats" type="submit" class="btn btn-default" name="SearchPublicationPeriod" value="{% trans 'Submit' %}"/><br/> </form> I don't understand why, when I have this line in my form it works : # publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id')) But when I replace this line by this : publication_list = forms.ModelMultipleChoiceField( queryset=Publication.objects.all().order_by('pub_id'), label=_('Publication Choice'), widget=ModelSelect2Widget( model=Publication, search_fields=['pub_id__icontains', 'title__icontains'], attrs={'data-placeholder': "Please select publication(s)"} ) ) I get this issue : Exception Type: ProgrammingError at /freepub/stats Exception Value: relation "select_cache" does not exist LINE 1: SELECT COUNT(*) FROM "select_cache" ^ Do you … -
django testing Assertquerysetequal not working
I have trying to do an assertqueryset with django testing using the following commands but all of them work if there is only one object in the list, but when I insert multiple objects in the list to compare both sets of queries all of them fail sometimes and pass sometimes which is completely strange(running with same set of code). The list of assertquerysetequal I used to test I sourced from two other questions in How do I test Django QuerySets are equal? and in Django 1.4 - assertQuerysetEqual - how to use method as well as the django documentation. This could be because the sequence is not in order when it fails the comparison test. Because when I did a print - my querysets were exactly matching. Because when I run the tests, sometimes the tests passes, sometimes it fails when I compare multiple objects in my lists. I can tell them the list differ when it fails because of the error message but I don't understand why the commands that I used does not compare them in order. (They were accepted/upvoted answers) Any advice on how I can fix this permanently would be welcome. Thank you. class TestViews(TestCase): … -
django ajax audio file upload to views.py
m a newbie in django. the problem m facing is that i cant send an audio file to views,py for further processing.kindly help me in this thanks enter image description here ` upload var recorder = document.getElementById('recorder'); var player = document.getElementById('player'); recorder.addEventListener('change', function(e) { var file = e.target.files[0]; enter code here player.src = URL.createObjectURL(file); }); ` -
Django: creating a text with gaps for input
I want to create a text on my website, where the gaps, in which the user can input a word (like the c-tests for learning language) are dynamically created depending on the text that the function gets from the database (not yet implemented). My idea was it to create a formset in which each label is different depending on a variable I give it. Here is my views.py def ctest(request): c_test_tokens, gaps, tokenindexe = generate_c_test(beispieltext()) # EXAMPLE # NOT WORKING ON POST REQUEST YET # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CTestform(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: CTestform.creatingForm(tokenindexe) ctestformset = formset_factory(CTestform, extra=len(gaps)) return render(request, 'ctest.html', {'form': ctestformset}) Here is my forms.py class CTestform(forms.Form): hello = forms.CharField(widget=forms.TextInput(attrs={'size': '5'}), required=False, label='hello', label_suffix='') Is this approach fine and how do I give the form a list with each element being the label for … -
how to show data from 2 models in django with one to many relashion in template
Hello i have 2 classes in my model: class MO (models.Model): many variables class PhotoMO (models.Model): mo = models.ForeignKey(MO, on_delete=models.CASCADE) photo = models.ImageField( upload_to='img/photo/%Y/%m/' ) my views for template class MOListView(DetailView): template_name = 'main_site/mo_view.html' model = models.MO with template : {% block content %} <h1>{{ mo.name }}</h1> <h3>{{ mo.phone_number }}</h3> <h3>{{ mo.email_mo }}</h3> <h3>{{ mo.adress_mo }}</h3> {% for photos in mo.photomo.set.all %} <img src="{{ photos.photo.url }}" alt="no img"> {% endfor %} {% endblock %} How can I display all the pictures from PhotoMO that refer to a specific entry in MO. With my "for" it dosen't work -
Does form.save() save cleaned_data value or non clean value to the model
I have a model form in Django. if form1.is_valid(): form1.save() Does this save cleaned_data to the model or does it save unclean data. Thanks -
URL configuration in Django
I have a Django in which the HTML page has a simple GitHub link. <a href="www.github.com">Github</a> When I click on it, the URL it gets redirected to is "localhost/app/github.com" Can you please explain why is it happening and what should I do to correct it? -
Admin page couldn't get found
Here come my urls.py page code: from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), ] When I run Django I get 404 error. I know this is a famous problem but couldn't find any answer for it. What is wrong? -
python ImportError: cannot import name 'Faker' from 'faker'
hello so I've been writing this script to pre-populate my Django database but when I stopped writing it I got a weird error: My Script: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() ## FAKE POPULATION SCRIPT: import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker # Creating a fake generator: fakegen = Faker topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N = 5): for entry in range(N): # GET THE TOPIC FOR THE ENTRY: top = add_topic() # Create the fake data for that entry: fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry: webpg = Webpage.objects.get_or_create(topic = top, url = fake_url, name = fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.get_or_create(name = webpg, date = fake_date)[0] if __name__ == '__main__': print("Populating Script!") populate(20) print("Populating Complete!") The error I get: python populate_first_app.py Traceback (most recent call last): File "populate_first_app.py", line 11, in <module> from faker import Faker File "E:\Python\Projects\Python And Django FullStack\Django\first_project\faker.py", line 1, in <module> from faker import Faker ImportError: cannot import name 'Faker' from 'faker' I've never seen the error like this I am using this script … -
Django - fetch data from Elasticsearch as QuerySet.
I have an ordinary ViewSet that fetch data from PostgesDB, applies some BackEnd filters etc. All of the processing works thanks to the fact that Notes.objects.all() returns a QuerySet. How do I turn a free Elasticsearch query result to QuerySet? Alternatively, How do I turn a Dict into QuerySet? Thank in advance. -
Django Forms - How to create a "Save and New" button?
Is there a way in Django Forms that I could implement a button "Save and New"? For example: I'm registering a new Book, I have both "Save" and "Save and New" buttons in the HTML template. The "Save" button behaves normally. You put the data in the form fields, click on it, the new object is created and saved and then redirects to the list of books. But I would like that the "Save and New" button redirects to the same form creation page after clicked. Plese, how could I do that? I didn't find anything about this in the docs. -
ImportError: cannot import name 'X' - Compile Python class with Cython
I'm creating a web application (using Django 1.11.2, Python 2.7.15) that will be deployed in a IIS server (actually now I'm only working on my local PC with Windows 10). Since that server will be reachable by another user and since I need to protect the application's back-end, I compiled the Python's core classes with Cython getting the ".pyd" files. Then I deleted the ".py" files (after a back-up =)). My folders organization is (note: py2_env is the virtualenv directory): C:\ └── Software\ └── MyApp\ ├── py2_env\ │ ├── Include\ │ ├── Lib\ │ ├── Scripts\ │ └── tcl\ └── MyAppServer\ ├── manage.py ├── ... └── myapp_django_server\ ├── urls.py ├── wsgi.py ├── ... └── myapp_web_app\ ├── ... └── myapp_core\ ├── __init__.py ├── db.pyd ├── all_other_classes.pyd └── ... The problem is that, when I try to run the application, using ISS I get this error in the browser: Traceback: File "C:\Software\MyApp\py2_env\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Software\MyApp\py2_env\lib\site-packages\django\core\handlers\base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "C:\Software\MyApp\py2_env\lib\site-packages\django\urls\resolvers.py" in resolve 362. for pattern in self.url_patterns: File "C:\Software\MyApp\py2_env\lib\site-packages\django\utils\functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "C:\Software\MyApp\py2_env\lib\site-packages\django\urls\resolvers.py" in url_patterns 405. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Software\MyApp\py2_env\lib\site-packages\django\utils\functional.py" in __get__ 35. res = … -
Sending JSON to the Django backend
I have an object in Angular const obj = {name: 'someName'}; And I stringify it: const data = JSON.stringify(obj); And when I'm trying to send this data to Django backend (and then, backend try to deserialize string I get an error) JSONDecodeError at /some_endpoint Expecting property name enclosed in double quotes: line 1 column 2 (char 1) And how request looks like in Chrome DevTools, in request payload data: "{"name":"someName"}" How to correct send this payload? Do I have to change data before send? -
OSError: Too Many Open Files during SMTP send email Django Core. How do I close the SMTP connection opened by Django Core send_mail method?
Traceback (most recent call last): File "/opt/anaconda/lib/python3.6/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/opt/anaconda/lib/python3.6/site-packages/django/core/mail/message.py", line 294, in send return self.get_connection(fail_silently).send_messages([self]) File "/opt/anaconda/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/opt/anaconda/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 63, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/opt/anaconda/lib/python3.6/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/opt/anaconda/lib/python3.6/smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "/opt/anaconda/lib/python3.6/smtplib.py", line 307, in _get_socket self.source_address) File "/opt/anaconda/lib/python3.6/socket.py", line 704, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): File "/opt/anaconda/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): OSError: [Errno 24] Too many open files -
How I can show multiple with respect to count in D3?
Here is an example taken from : http://bl.ocks.org/natemiller/7dec148bb6aab897e561 working fine. <!DOCTYPE html> <meta charset="utf-8"> <style> svg { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .y.axis path { fill: none; stroke: #000; shape-rendering: crispEdges; } .brush .extent { stroke: #fff; fill-opacity: .125; shape-rendering: crispEdges; } .line { fill: none; } </style> <body> <script src="http://d3js.org/d3.v3.min.js"></script> <script> var margin = {top: 10, right: 10, bottom: 100, left: 40}, margin2 = {top: 430, right: 10, bottom: 20, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom, height2 = 500 - margin2.top - margin2.bottom; var color = d3.scale.category10(); var parseDate = d3.time.format("%Y%m").parse; var x = d3.time.scale().range([0, width]), x2 = d3.time.scale().range([0, width]), y = d3.scale.linear().range([height, 0]), y2 = d3.scale.linear().range([height2, 0]); var xAxis = d3.svg.axis().scale(x).orient("bottom"), xAxis2 = d3.svg.axis().scale(x2).orient("bottom"), yAxis = d3.svg.axis().scale(y).orient("left"); var brush = d3.svg.brush() .x(x2) .on("brush", brush); var line = d3.svg.line() .defined(function(d) { return !isNaN(d.temperature); }) .interpolate("cubic") .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.temperature); }); var line2 = d3.svg.line() .defined(function(d) { return !isNaN(d.temperature); }) .interpolate("cubic") .x(function(d) {return x2(d.date); }) .y(function(d) {return y2(d.temperature); }); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + … -
Celery dont register periodic tasks
Im trying to run celery worker, but when i do that Celery cant see my periodic tasks for some reason. Here is my console output: ------------- celery@andrey-MS-7996 v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Linux-4.15.0-39-generic-x86_64-with-Ubuntu-18.04-bionic 2018-12-03 13:49:13 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: sjimalka:0x7fa69bef3e48 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] [2018-12-03 13:49:13,380: INFO/Beat] beat: Starting... [2018-12-03 13:49:13,385: INFO/MainProcess] Connected to redis://localhost:6379/0 [2018-12-03 13:49:13,392: INFO/MainProcess] mingle: searching for neighbors [2018-12-03 13:49:14,409: INFO/MainProcess] mingle: all alone [2018-12-03 13:49:14,432: WARNING/MainProcess] /home/andrey/.local/lib/python3.6/site-packages/celery/fixups/django.py:200: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('Using settings.DEBUG leads to a memory leak, never ' [2018-12-03 13:49:14,433: INFO/MainProcess] celery@andrey-MS-7996 ready. init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sjimalka.settings') app = Celery('sjimalka') app.conf.timezone = 'Europe/Moscow' app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() …