Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does django ignore HTTP_X_FORWARDED_PROTO from the wire but not in tests?
Why does django ignore the HTTP_X_FORWARDED_PROTO if it comes through the wire? I added to the settings.xml the following config: # make sure we know when we are secure when we are behind a proxy SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') I made a test to test that if def testHttpSupport(self): url = reverse('configuration-list') response = self.client.get(url, HTTP_X_FORWARDED_PROTO='https') cfg = response.data[0] cfg_url = cfg['url'] self.assertTrue(cfg_url.startswith('https')) this works fine. The url of the return object starts with https. however if I try : curl -v -H 'HTTP_X_FORWARDED_PROTO: https' http://localhost:8000/api/users/ ... > GET /api/users/ HTTP/1.1 > Host: localhost:8000 > User-Agent: curl/7.51.0 > Accept: */* > HTTP_X_FORWARDED_PROTO: https > * HTTP 1.0, assume close after body < HTTP/1.0 200 OK < Date: Mon, 03 Jul 2017 16:22:04 GMT < Server: WSGIServer/0.2 CPython/3.6.1 < Content-Type: application/json < Allow: GET, POST, OPTIONS < Vary: Accept, Cookie < X-Frame-Options: SAMEORIGIN < Content-Length: 197 < * Curl_http_done: called premature == 0 * Closing connection 0 [{"url":"http://localhost:8000/api/users/1/",... How come it does not return 'https://' based urls like in my unit-test? -
How to change Django's custom user class without logging people out?
I have a custom user class that uses email as the "USERNAME" field in Django, goes something like this, class CustomUser (AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] The site is primarily used within the Chinese chat application WeChat, which has a mechanism that can allow you request an openid from the visitor. Since a lot of users are complaining about the cumbersome email registration process, I figured maybe I'll just log them in through the openid. So maybe I will change the custom user class to something like this, class CustomUser (AbstractBaseUser, PermissionsMixin): open_id = models.CharField(max_length=254, unique=True) objects = CustomUserManager() USERNAME_FIELD = 'open_id' REQUIRED_FIELDS = [] I have the following questions. What happens to users who were "logged in" if I change the CustomUser class? As in will their local cookies automatically expire and they're forced to re-login? What's the best way to make this transition? I'm guessing I should wait a while until I get a lot of the openids (or majority of them) from users who've already logged in so I can associate their email accounts with their openids. But then I will always orphan a bunch of users' … -
Django setting TIME_ZONE in DATABASES has no effect
I want to interact with a legacy database where datetimes are saved in another time zone. According to Django's documentation for 1.11, I can use set TIME_ZONE values specific to each database. A specific quote is When USE_TZ is True and the database doesn’t support time zones (e.g. SQLite, MySQL, Oracle), Django reads and writes datetimes in local time according to this option if it is set and in UTC if it isn’t. This means my settings.py can look like this: DATABASES = { 'legacy': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '...', }, 'TIME_ZONE': 'Europe/Paris', }, 'default' : { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '...', }, } } DATABASE_ROUTERS = '...' LANGUAGE_CODE = 'fr' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = False USE_TZ = True DATETIME_FORMAT = 'N j, Y, H:i T' I'd like to keep USE_TZ for two reasons, 1/ everything makes more sense with timezone aware datetimes, 2/ I believe being aware is a superior behavior over unaware When I run a filter by date, my database setting is ignored: DEBUG [django.db.backends:91] (0.000) SELECT (1) AS `a` FROM `alert` WHERE (DATE(CONVERT_TZ(`alert`.`publication_scheduled_date`, 'UTC', 'Europe/Paris')) = '2017-07-03') LIMIT 1; args=('Europe/Paris', u'2017-07-03') From what I understand, the UTC in CONVERT_TZ … -
Sorl thumbnail not working [Errno 2] No such file or directory
I'm using sorl-thumbnail 12.2 {% load thumbnail %} {% for image in citem.get_images %} <div class="image-block"> {% thumbnail image.img.path '180x180' as thumb %} {% thumbnail image.img.path '640x640' as medium %} <a data-lightbox="i-{{image.id}}" href="{{medium.url}}" title="{{citem.display_plant_smart}}"> <img class="img-rounded img-responsive bound-img-big" src="{{ thumb.url }}" alt="{{citem.display_plant_smart}}" style="padding-bottom: 1px"/> </a> {% endthumbnail %} Usually this code was working, for some unknown reason it stops working. Now I'm getting [Errno 2] No such file or directory Even the file exists on disk. When trying to run sorl migrations I get this: django.db.utils.ProgrammingError: relation "thumbnail_kvstore" already exists -
what's a django static/dynamic view?
I'm familiar with Django views and I've used them for a while now. But I don't know the difference between static and dynamic views. To my understanding, static views represent views whose URLs don't change (e.g. QuerySets would be simply Objects.objects.all(), or a view that serves a static HTML page), and a dynamic view is a view whose URL is dependent upon the object's pk (e.g. a view for a blog entry). If I'm wrong, could someone explain to me what the difference is? -
Efficient Django Query using annotate function
There is a table A with fields: id_1(int)|id_2(int) I have a query writen on id_2: blocked_users = bl_.objects.filter(id_2=request.user.id); #for a single value of id_2,there are multiple entries,like: id1|id2 2 |3 5 |3 7 |3 There is a table B with fields: id_3(int)|id4(int) Now,for every id_1 in the variable:blocked_users,there is a id3 in the table B,which I want to access: table B: id3|id4 2 |90 5 |89 7 |87 I know it can be done with for loops,but is there a better solution for this(eg:by the annotate function)? Thanks. -
Django POST is null from jquery
I am attempting to incorporate a range slider in my django project as a sidebar to filter a list. Below is the code that I am currently using, however the issue I am facing is that the jquery is not forwarding the slider value to the hidden field in the form, hence the POST request is always NULL. The thing is when I change the hidden field to a text field and manually type in the value and submit it, there is no issue and data is received as usual. The following piece of code is in a template that is included in another template. What am I doing wrong ? I have tried multiple different methods and seem to be going no where. Any help appreciated at this time :) <script> $( function() { var minValue = 1; var maxValue = 10; var minCurrent = 1; var maxCurrent = 10; $( "#slider-range" ).slider({ range: true, step: 1, min: minValue, max: maxValue, values: [ minCurrent, maxCurrent], slide: function( event, ui ) { $( "#slider" ).val( "Negative:" + ui.values[ 0 ] + " Positive:" + ui.values[ 1 ] ); } }); $( "#slider" ).val( "Negative :" + $( "#slider-range" ).slider( "values", … -
Model Serializer TypeError on Related Field
I have never worked with the Django Rest Framework before, but I wanted to serialize a few of my models because I want to ultimately get and post information for these particular models through JS instead of Django. I have one working correctly, but the one called ManifestSerializer gives me the error: TypeError: 'Freight' object is not iterable. Here is my code: Models.py: class Freight(models.Model): pu_location = models.OneToOneField(AddressBook, to_field='address', related_name='pu_location') pu_customer = models.CharField(max_length=200) pu_appt_time = models.DateTimeField(default=datetime.now) po_number = models.CharField(max_length=20) load_number = models.CharField(max_length=10, blank=True, null=True) pallet_count = models.IntegerField(validators=[MaxValueValidator(99)]) content_type = models.CharField(max_length=20, choices=[('Frozen', 'Frozen'), ('Chilled', 'Chilled'), ('Dry', 'Dry')]) cases_count = models.IntegerField(validators=[MaxValueValidator(9999)]) weight = models.IntegerField(validators=[MaxValueValidator(99999)]) del_customer = models.CharField(max_length=200) del_location = models.OneToOneField(AddressBook, to_field='address', related_name='del_location') del_city = models.CharField(max_length=50, blank=True, null=True) del_state = models.CharField(max_length=2, blank=True, null=True) del_appt_time = models.DateTimeField(default=datetime.now) invoice_amount = models.DecimalField(max_digits=8, decimal_places=2) status = models.CharField(max_length=20, choices=[('New', 'New'), ('EnRoute', 'En Route'), ('Complete', 'Complete'), ('NotExecuted', 'Not Executed')], default='New') note = models.ForeignKey(Note, blank=True, null=True) def save(self, *args, **kwargs): reg = re.compile(r',\s+?(?P<city>[^,]+),\s+(?P<state>[A-Za-z]{2})') location = str(self.del_location) extract = reg.search(location) city = extract.group('city') state = extract.group('state') if not self.del_city: self.del_city = city if not self.del_state: self.del_state = state super(Freight, self).save(*args, **kwargs) def __unicode__(self): return "%s : %s : %s" % (self.po_number, self.pu_customer, self.del_location) class Manifest(models.Model): manifest_number = models.AutoField(primary_key=True) freight = models.ForeignKey(Freight) … -
django- IntegrityError - duplicate key value violates unique constraint after adding clean() method
I have the following model. FRONT_BACK=(('F','Front'), ('B','Back'), ('C','Common')) PRODUCT_TYPE=(('TL','Tubeless Tyre'), ('TT','Tubed Tyre'), ('NA','Not applicable')) class Product(models.Model): product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False) manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False) product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE, null=False,blank=False) wheel_position=models.CharField(max_length=1, choices=FRONT_BACK, null=False,blank=False) opening_stock=models.PositiveIntegerField(default=0) stock_in=models.PositiveIntegerField(verbose_name="Stock in so far", default=0) stock_out=models.PositiveIntegerField(verbose_name="Stock out so far", default=0) created_by=models.ForeignKey(auth.models.User, default=1) class Meta: ordering=['product_group','manufacturer'] unique_together = ('product_group', 'manufacturer','product_type','wheel_position') The unique_together gives the desired result - when I try to duplicate, I get the message Product with this Product group, Manufacturer, Product type and Wheel position already exists. -----message(1) In a combination of (ProductGroup,Manufacturer,ProductType), if a product having product_type NA is present, the system should not permit to add another product with TL or TT for the same (ProductGroup,Manufacturer). Similarly, if a product of type TL/TT is present, an addition of NA (with other values the same) should be prevented. In a combination of (ProductGroup,Manufacturer,ProductType,WheelPosition), if a product having wheel_position C is present, the system should not permit to add another product with F or B for the same (ProductGroup,Manufacturer,ProductType). Similarly if a product of type F/B is present, and addition of C (with other values the same) should be prevented. In order to ensure this, I've added a clean() method to my form (which is enclosed below). I think this addition does … -
Celery Flower Django
i'm doing some tests with the stack: Django, RabbitMQ, Celery and Flower. Everything is going fine, but we have a problem with failed tasks, i know that they can't be restarted from the Flower web interface (i'm right?), so what i've started celery... Im my view, i have a dump code that does this job: @app.task(max_retries=2, default_retry_delay = 1 * 1) def debug_task(): try: random_int = int(randint(0, 15)) if random_int > 5: raise Exception ('> 5') else: print('Request: {0!r}'.format('OK')) except MaxRetriesExceededError: print('New queue') debug_task.apply_async(queue='failed_tasks') except Exception as exc: raise debug_task.retry(exc=exc) It's seems to work, due to the fact that i'm seeing in flowers that when the number it's > 5 the entire procedure will be executed another time, as you can see in the screenshot: So, now i have a bunch of failed tasks and i need "something" that will restart them, execute and give back the result to flower, what i'm doing wrong? -
Django form doesn't render PhoneNumberField with crispy forms
Hello I have the following code for a contact form: lass ContactForm(forms.Form): def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = "col-md-2" self.helper.layout = Layout( Div( #I need to set size for every field wrapped in a div Div('from_name', css_class="col-md-6 form-group"), Div('from_email', css_class='col-md-6 form-group'), Div('phone_number', css_class='col-md-6 form-group'), Div('subject', css_class='col-md-6'), Div('message', css_class='form-group col-md-12'), css_class='row' ), ButtonHolder( Submit('submit', 'Submit', css_class='btn btn-small btn-dark-solid') ) ) from_name = forms.EmailField(required=True, label='Name', max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'id':'name'})) from_email = forms.EmailField(required=True, label='Email', max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'id':'email'})) phone_number = PhoneNumberField(blank=True, default='', null=True, unique=True) subject = forms.CharField(required=True, label='Subject', max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'id':'subject'})) message = forms.CharField(required=True, label='Message', max_length=100, widget=forms.TextInput(attrs={'class':'cmnt-text form-control', 'id':'message'})) The problem is that the form won't render the 'phone_number' field and I want to use the django-phonenumber-field library for validating the phone numbers. What am I doing wrong here? -
Can we define django model from csv file or pandas dataframe?
I have more than 200 columns in csv file and want to define Class in django model. But I really can't find handful instructions to create django model from csv files (first row indicates columns) Is there any way to define django model from csv file or pandas dataframe? -
Soft delete, prevent delete if object is used as a foreign key by another Object
I have the two models defined below. How could I prevent the soft deletion of Source object if it is referenced by a Record obj? Is there a way maybe to trigger the actual delete to see if it fails and undo it right after? class Source(models.Model): name = models.CharField(max_length=200) deleted = models.BooleanField(default=False) def delete(self, using=None, keep_parents=False): self.deleted = True self.save() class Record(models.Model): title = models.CharField(max_length=200) source = models.ForeignKey(Source) deleted = models.BooleanField(default=False) def delete(self, using=None, keep_parents=False): self.deleted = True self.save() -
Django annotate Concat - Expression contains mixed types. You must set output_field
I have a model: class Motocycle(models.Model): title = models.CharField(max_length=50, blank=True, default='') engine_displacement = models.IntegerField(default=0) and I want to: queryset = Motocycle.objects.annotate( full_name=Concat( 'title', Value(' '), F('engine_displacement'), Value('') ), ).all() But got an error: Expression contains mixed types. You must set output_field: queryset = Motocycle.objects.annotate( full_name=Concat( 'title', Value(' '), F('engine_displacement'), Value(''), ), output_field=CharField(), ).all() I tryed to set this output_field, result was: 'CharField' object has no attribute 'resolve_expression'. What I'm doing wrong? Thank you. -
Django custom FileField attribute and property
I want to add a property to the FileField, so that I can specify when adding a field to the model. class TestFile(models.Model): c206 = CategoryFileField( category='206' ) And also get the same value from the model instance. tf = TestFile.objects.latest('id') tf.c206.category # 206 I tried to extend FileFiled by analogy with ImageFileField: class CategoryMetadataMixin(object): @property def category(self): return self.category class CategoryFieldFile(CategoryMetadataMixin, FieldFile): pass class CategoryFileField(FileField): attr_class = CategoryFieldFile descriptor_class = FileDescriptor description = _("File") def __init__(self, verbose_name=None, name=None, category='', **kwargs): self.attr_class.category = category super().__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.category: kwargs['category'] = self.category return name, path, args, kwargs But in this case category always returns ''. Apparently I went the wrong way. -
OperationalError in Django server
I receive the exception you see below when I add: date_added = models.DateTimeField(auto_now_add=True) in several of my classes in models.py Previous to this, there was an error regarding a default value. Please help, thanks. OperationalError at /admin/pizzas/pizza/ no such column: pizzas_pizza.date_added Request Method: GET Request URL: http://localhost:8000/admin/pizzas/pizza/ Django Version: 1.11.2 Exception Type: OperationalError Exception Value: no such column: pizzas_pizza.date_added Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 328 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.1 Python Path: ['/Users/Informatics/Desktop/Django/pizzeria', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] Server time: Mon, 3 Jul 2017 14:24:52 +0000 There are no issues with making migrations, or running the server. I've cleared the some previous migrations. That also seemed to help. What am I missing? -
Storing Location History in a Django Model Field
I am trying to store a multiple locations in a field of a django model, but I am not quite sure how to go about it. I am using GeoDjango's PointField to store the latest reported location. class Tracker(models.Model): # Other fields.. # srid 4326 is the WGS84 Spheroid used by GPS current_pos = models.PointField(editable=True, srid=4326) pos_hist = ? I have looked at apps like django-field-history and similar, but they seem to be designed to allow changes to be reversed by admin/user, which I don't need. Another method seems to be using a ForeignKey to make a many-to-many relationship to a Location model, but I can't seem to get my head around how that would work as each Tracker would have multiple Location models in that field, but there would be multiple Trackers? Am I approaching this from the right direction or is there a better way? Thanks in advance! -
Django nose test coverage doesnt recognize admin.py files
I am using django nose for test coverage and I cannot get the test cover admin.py files. authentication/admin.py 16 16 0% I dont know how to cover the admin.py files or if they should be covered. This what I a trying right now: class ModelAdminTests(TestCase): def setUp(self): self.user = User.objects.create( email="test@testing.com") def test_modeladmin_str(self): ua = UserAdmin(User, self.user) self.assertEqual(str(ua), 'authentication.UserAdmin') def test_default_fields(self): ua = UserAdmin(User, self.user) self.assertEqual(list(ua.list_display), ['email', 'position', 'trend']) -
Django-Taggit Listing Items with Specific Tags
I'm trying to list all the objects with the same tag or tags and show them on the web page when i click the link in navigation bar. For example on my website, i have 'Python' link in my navbar so when clicked, it should list all the Entries with specific tag according to its slug in url. Navbar 'Python' link <li><a href="{% url 'tag-index' slug=tag %}">Python</a></li> urls.py url(r'^post/(?P<slug>[\w-]+)/$', TagIndexView, name="tag-index") models.py class Entry(models.Model): title = models.CharField(max_length=60) content = models.TextField() image = models.ImageField() published = models.DateTimeField('Publish Date', auto_now_add=True) modified = models.DateTimeField('Modified Date', auto_now=True) slug = models.SlugField(editable=False, max_length=200) tags = TaggableManager('Tags') def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Entry, self).save(*args, **kwargs) def __str__(self): return self.title views.py class TagIndexView(ListView): model = Entry template_name = 'myblog/tag_details.html' def get_context_data(self, **kwargs): context = super(TagIndexView, self).get_context_data(**kwargs) context['tag'] = Entry.objects.get(tags=self.request.tags) return context I know TagIndexView might be wrong but that's what i have been trying to find out. Thanks. -
Annotate query set with field of oldest related object
I'm looking to annotate a query set in Django with a specific field of the oldest related object of a reverse relationship. In the Django docs (https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#following-relationships-backwards), the following is stated: We can also ask for the oldest book of any of those managed by every publisher: Publisher.objects.aggregate(oldest_pubdate=Min('book__pubdate')) Following this example, I would not only like to know the oldest 'pubdate' of every publisher, but also the title of that oldest book. Is there a way to get this information with the Django ORM? -
Django select inherited model in a single query
Let's Assume I have a parent and a child tables which are implemented via inheritance in django. models.py class A(models.Model) a = CharField() class B(A): b = CharField() Now I want to select column b from table B I execute: B.objects.only('b').get(id=4) But this statement queries database 2 times: SELECT `b`.`a_ptr_id`, `b`.`b` FROM `b` WHERE `b`.`a_ptr_id` = 4; args=(4,) SELECT `a`.`a`, `b`.`a_id` FROM `b` INNER JOIN `a` ON (`b`.`a_ptr_id` = `b`.`id`) WHERE `b`.`a_ptr_id` = 4; args=(4,) How do I generate SINGLE query like select b from b where a_ptr_id = ? using django models? I want to query database one single time! -
Django Channels - websocket beeing disconnected immediately
I'm trying to use Django Channels using the in-memory channel layer and getting following: Client CONNECTS to Django server using websocket. Django DISCONNECTS client 2 seconds later. Why is Django not accepting the websocket connection? Client Error Log: socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host Here is my code: settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "mysite.routing.channel_routing", }, } consumers.py: from channels import Group from channels.sessions import channel_session #log = logging.getLogger(__name__) @channel_session def ws_connect(message): print "Connected" def ws_receive(message): data = json.loads(message['text']) print "Received" def ws_disconnect(message): print message print "Disconnected" routing.py from . import consumers from channels import route channel_routing = [ route('websocket.connect', consumers.ws_connect, path=r"^/$"), route('websocket.receive', consumers.ws_receive), route('websocket.disconnect', consumers.ws_disconnect), ] Couldn't find to many tutorials about the subject. -
Constructing a search form in Django
I am trying to build a search form in Django, but unfortunately I cannot get the code to work as the textbook said it would (I am using The Django Book). I couldn't get the form to submit, so I added a button, which fixed that. Unfortunately, now I cannot get the form to carry out the search function in views. It just gives me a 404 error. Below, please find the template, <html> <head> <title>Search</title> </head> <body> <form action=“/search/“ method = “get”> <input type = “text” name = “q”> < button type = “submit”> Submit</button> </form> </body> </html> Please excuse the lack of brackets. I couldn't figure out how to get the site not to interpret it as HTML. the view, from django.shortcuts import render from django.http import HttpResponse # Create your views here. def search_form(request): return render(request, "search_form.html") def search(request): if 'q' in request.GET: message = "You searched for: %r" % request.GET['q'] else: message = "You submitted an empty form." return HttpResponse(message) the URLconf, from django.conf.urls import include, url from django.contrib import admin from mysite2.views import hello, current_datetime, hours_ahead from books import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^hello/$', hello), url(r'^time/$', current_datetime), url(r'^time/plus/(\d{1,2})/$', hours_ahead), url(r'^search-form/$', views.search_form), url(r'^search/$', views.search), … -
django+nginx deployment not loading static files correctly
server { listen 80; server_name 13.xx.xx.xxx; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/studykarma/django-react-redux-base/src/; } location / { include proxy_params; include /etc/nginx/mime.types; proxy_pass http://unix:/home/ubuntu/studykarma/django-react-redux-base/src/djangoreactredux.sock; } } my nginx config file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static_dist'), ) my settings.py I have my static files in static_dist folder and my reactjs code in static folder. My static files are not loading and giving me 404, If i change path to /static_dist/ then also i am getting empty content. I am using this template: https://github.com/Seedstars/django-react-redux-base -
Show a message for a certain amount of time
Here is the javascript part $(function(){ $('.select-another-button').each(function(){ $(this).bind('click', function(e){ $('.select-another-button').css('pointer-events', 'none'); setTimeout(function(){ $('.select-another-button').css('pointer-events', 'auto'); }, 300000); e.preventDefault(); fileBrowser(this); return false; }); }); }); Here is the Django method that will send the message @staff_member_required @csrf_exempt def send(request, request_id=None): req= Request.objects.get(pk=request_id) request_folders = req.folder.all_files.all() context = [] for doc in request_folders: if doc.meta.state == u'rejected': context.append(doc) if context: ctx = {'request': req} EmailFromTemplate('document-refusal', extra_context=ctx)\ .send_to(req.customer.user) return HttpResponse('') Here is the urls.py file app_name = 'messaging' urlpatterns = [ url(r'^$', login_required( MessagingIndexView.as_view()), name='index'), url(r'^send/(?P<request_id>[0-9]+)/$', send, name='send'), ] Here is the part of the .html file <a href="#" title="{% trans "Send email - rejected file(s)" %}" class="btn btn-icon select-another-button" data-turbolinks="false" data-copy-to="{{ folder.pk }}" data-reload="true" data-url="{% url "messaging:send" request_id=object.pk %}"> <i class="material-icons">assignment_late</i> </a> Here is what I've done so far. It's not to the point yet, but I think it doesn't lack a lot to be functional. I have created a button which will send a specific message under certain conditions. Once it is send, I want that the button to be deactivate (i.e. we can't click on click to send a message) for a time of 5 minutes. Furthermore, I want during that time to show a message 'we have already sent the …