Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Retrieve last 10 records for a given query
I was reading the django documentation, and thought this would work to limit to resulting query results to the last 10 results, but it isnt doing that. Here my db query: TSUH = TSUH.objects.filter(FKToUser_id=request.user).all()[10:] TSFH = TSFH.objects.filter(FKToUser_id=request.user).all()[10:] TSJH = TSJH.objects.filter(FKToUser_id=request.user).all()[10:] return render(request, page.html', { 'GivenTSUH':TSUH }) my template contains: {% if TSUH %} {% for T in TSUH %} <li>{{ T.scanBegin }}<span> to <span>{{ T.begin }}</span> </li> {% endfor %} {% else %} It appears there are no results. {% endif %} This is returning a lot more than 10 results for each query. is the all() throwing it off? Thoughts? Thanks -
cannot css SummerNoteWidget
Here's my layout.html : {% load static %}{% load i18n %}<!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>{% block head_title %}{% endblock head_title %}</title> <!-- stylesheets --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"> {% block head %}{% endblock head %} <!-- Favicons --> <link rel="shortcut icon" href="{% static 'img/favicon.ico' %}" type="image/x-icon"> <script defer src="https://use.fontawesome.com/releases/v5.0.10/js/all.js" integrity="sha384-slN8GvtUJGnv6ca26v8EzVaR9DC58QEwsIk9q1QXdCU8Yu8ck/tL/5szYlBbqmS+" crossorigin="anonymous"></script> </head> <body class="container-fluid"> <!-- navbar --> {% include 'navbar.html' %} <!-- end of navbar --> <!-- main --> <div class="row"> <div class="col-lg-1"></div> <div class="col-lg-10"> <br><br><br><br><br> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% block content %} {% endblock content %} </div> <div class="col-lg-1"></div> </div> <!-- end of main --> <br><br> <div class="container-fluid fixed-bottom"> {% include 'footer.html' %} </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/lang/summernote-fr-FR.js"></script> </body> </html> editor.html : {% extends 'layout.html' %} {% load static %} {% load i18n %} {% block head_title %}{% trans 'Edit Entry' %}{% endblock head_title %} {% block head %} <style> #id-definition { background-color: … -
Bootstrap-ui Modal is coming up blank when set inside angular-gantt
I am having difficulties trying to get my modal to come up. I am not sure if it is because modal is not compatible with angular-gantt or if I have the code wrong. At the moment I get a darker screen as if there should be a modal there. Here is the code for the button in the gantt: JS: 'content':'<i class=\"fa fa-cog\" data-toggle="modal" data-target="#hp_modal" ng-click="scope.show_details(task.model)"></i>' + 'Gant Object' Html: <div class='modal fade' id='hp_modal'> <div class='modal dialog'> <div class='modal-content'> <div class="modal-header"> <h3>This is HP modal</h3> </div> </div> </div> </div> And here is an Image of after I click on the cog: https://imgur.com/a/CazzaLK -
Accessing a variable outside conditions in python
I have conditions and need to define var in them and use that out of this conditions. This is my codes: if 1 < (process_time % 60): final_process_time = 'process time is: ' + str(process_time) + ' sec!' elif 1 <= (process_time % 60) < 60: process_time = process_time / 60 final_process_time = 'process time is: ' + str(process_time) + ' min!' elif 60 <= (process_time % 60): process_time = process_time / 3600 final_process_time = 'process time is: ' + str(process_time) + ' hour(s)!' print(final_process_time) I got this error: local variable 'final_process_time' referenced before assignment Hints: I tested these solutions, but none of them responded: Way 1: set final_process_time to `global` # Error: name 'final_process_time' is not defined Way 2: Define final_process_time ='' Before conditions # Result: nothing set to this var Attached : Some of you suggested that I put more of my code to fix the bug in this section. My entire codes:(of course, some absolutely unrelated items have not been added) def excel_report(request): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) .... TITLES_LIST = [ ['user', 'title', 'explains', 'organization', 'post', 'time_start', 'time_end'], .... ] FILE_NAME = 'report-' + datetime.datetime.now().strftime("%Y-%m-%d-%H-%M") + '.xlsx' # writer = pd.ExcelWriter(FILE_NAME, engine='xlswriter') if request.method == … -
Accessing third party POST API
I have a third party POST API, for example: https://testenv/api/1.0/make_project/ which posts a payload like: [{'name' :'project_1' ,'created_by' :'prat' }] This json data is posted to the third party database. How could I create an API in my application to send over a payload to this third party api and would my request be a post request? And how would I go ahead with this and what all should I know about the third party api before implementation? -
Loading images from models with jinja templating
I have a simple blog, and an image in my articles model that I'd like to use as a background image in a div on my website. The image doesn't load the way the code is written now. I've tried changing the media and static settings in my settings.py, but I'm not sure if this is what the issue is. here is my articles model. class Article(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() content = HTMLField(null=True) is_draft = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('article-detail', kwargs={ 'id': self.id }) here is the index.html page, an example of how I'm trying to call the image now using jinja tags: {% extends "base.html" %} {% load static %} {% block content %} <section data-overlay> <div class="container"> <div class="row mb-4"> <div class="col-md-8 col-lg-9"> {% for post in queryset %} <div class="pr-lg-4"> <a href="{{ post.get_absolute_url }}" class="bg-primary-3-alt rounded p-4 d-flex align-items-center justify-content-center min-vh-20"> <img src="{{ article.thumbnail.url }}" alt="Avatar" class="avatar mr-2"> <span class="text-small text-primary-3">{{ post.title }}</span> </a> </div> {% endfor %} <br> <div class="row justify-content-center pr-lg-4"> <div class="col-auto"> <nav> <ul class="pagination mb-0"> {% if queryset.has_previous %} <li … -
How to get TextField to render in API Browser in DRF?
Using DRF, I have a User model that includes an Address field, which is a TextField. When I view the UserList endpoint in the API Browser, Address looks like this: "address": "<django.db.models.fields.TextField>", From the documentation, I thought I needed this in my serializer: address = serializers.CharField( max_length=1000, style={'base_template': 'textarea.html'}, ) ...but that didn't fix the problem. The same thing is happening with PhoneNumberField type fields: "phone_number": "<phonenumber_field.modelfields.PhoneNumberField>", I redefined them in my serializer as CharField. -
How to fix "AssertionError: 403 != 401"
I am writing test for User Authorization in Django. I am getting AssertionError: 403 != 401 def test_authorization_is_enforced(self): """Test that the api has user authorization.""" new_client = APIClient() res = new_client.get('/bucketlists/', kwargs={'pk': 3}, format="json") self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) AssertionError: 403 != 401 -
"ImproperlyConfigured: The included URLconf '<project>.urls' does not appear to have any patterns in it" recieved when attempting to runserver
I have created a simple webapp with django to display some lists from a .csv file. This program works perfectly fine on my local machine using runserver, however, when attempting to deploy using DigitalOcean using the following guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#create-a-gunicorn-systemd-service-file , when I run ~//manage.py runserver 0.0.0.0:8000 I am greeted with a TypeError: 'module' object is not iterable followed by "ImproperlyConfigured: The included URLconf .urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import." After spending the day searching around the majority of other people with this problem have spelling mistakes or missing commas however I don't THINK that's the case for me. I've shown my url files below: urls.py - project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('recommendation/', include('recommendation.urls')), path('admin/', admin.site.urls), ] urls.py - recommendation from django.urls import path from django.conf.urls import url from . import views app_name = 'recommendation' urlpatterns = [ path('', views.index, name='index'), url(r'^movie/search', views.movie, name='movie'), ] I saw a post explaining that the 'module' object was being found due to urlpatterns not being properly defined as lists (missing commas). Any help is … -
Django. keep getting 404 on my images, don't know if i set up the paths right
I'm trying to display images on a test website, i've already done it before but now i've tried old and new sollutions since 3 days ago and keep getting 404 on my images. I have not set any static yet, just the media files. Those are my models.py from django.db import models ´´´´ class Produto (models.Model): nome = models.CharField(max_length=50) preço = models.DecimalField(max_digits=5, decimal_places=2) foto = models.ImageField(blank=True, upload_to='media') def __str__(self): return '%s %s' % (self.nome, self.foto) ´´´´ my settings.py ´´´´ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = 'JR/JR/static/produtos' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ´´´´ ´´´´ my views.py from django.shortcuts import render from.models import Produto def produtolist(request): list = Produto.objects.all() return render(request, 'produtos.html', {'list': list}) ´´´´ and a pic with the error and paths: error -
Textfield does not work with tinymce widgets
I wanted to customize my admin file. In admin file I have TextField and I want to use tinymce widget to change its view. All things seem fine because I don't get any error but I don't see effect of my code in admin file. If I delete "field_overrides=..." part I see the normal textfield but with this function I see nothing, completely empty field. from django.contrib import admin from .models import Tutorial from django.db import models from tinymce.widgets import TinyMCE class TutorialAdmin(admin.ModelAdmin): fieldsets = [ ("Title/date", {'fields': ["tutorial_title", "tutorial_published"]}), ("Content", {"fields": ["tutorial_content"]}) ] formfield_overrides = { models.TextField: {'widget': TinyMCE} } admin.site.register(Tutorial,TutorialAdmin) This is my model: from django.db import models from datetime import datetime # Create your models here. class Tutorial(models.Model): tutorial_title=models.CharField(max_length=200) tutorial_content=models.TextField() tutorial_published=models.DateTimeField("data published",default=datetime.now()) def __str__(self): return self.tutorial_title here is my settings file(for necessary part): TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | … -
Why File is not uploading in specified upload path in models in Django, It is uploading in expected directory when uploaded from the admin
I've been trying to upload some files using normal CRUD operation in Django. The files are uploading at the media directory of the project while normally uploaded and when I try to upload the files from the admin area it is uploading in the expected directory ie. inside media/cv. I've defined the models for the database and also defined the media root and added it into the urlpatterns variable too. All seems okay and works just fine when I try to upload the file from admin view but when I try to upload file normally the file is uploaded directly in the media directory, not in media/cv. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py in project level from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')) ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models class Student(models.Model): cv = models.FileField(upload_to='cv') urls.py from django.urls import path from . import views urlpatterns = [ path('student/create', views.insert_student, name='create_student'), ] views.py from django.core.files.storage import FileSystemStorage from django.shortcuts import redirect from .models import Student def insert_student(request): if request.method == … -
django template falling into unexpected logic
I have a view that is supposed to be gathering all the objects for a currently authenticated user from three tables TSFH, TSUH, and TSJH and gather all those objects for the currently logged in user, if that user exists. However, my view logic is currently falling into the else statement it appears. Can someone help me debug why this might be happening? My tables have data for the currently logged in user, so I am not sure why this is happening. Views.py def SHO(request): TSUH = TSUH.objects.filter(FKToUser_id=request.user).all() TSFH = TSFH.objects.filter(FKToUser_id=request.user).all() TSJH = TSJH.objects.filter(FKToUser_id=request.user).all() return render(request, 'page.html', { 'TSUH':HasTSUH, 'TSFH':HasTSFH, 'TSJH':HasTSJH }) templates/page.html {% autoescape on %} {% if HasTSUH %} {% for t in HasTSUH %} <li>{{ t.begin }}<span></li> {% endfor %} {% elif HasTSFH %} {{ HasTSFH }} {% elif TSJH %} {{ TSJH }} {% else %} It appears you haven't done anything yet. {% endif %} However it keeps displaying: It appears you haven't done anything yet. what am i doing wrong here? thanks -
Django secure django-rest-framework-simplejwt
I am trying to create a JWT token authentication my Django rest application for that I am using: django-rest-framework-simplejwt I can generate an access token and I want to decode that token and only I can see the decoded values. Right now when I generate the access token it can be decoded easily. I am using this to decode: decodedPayload = jwt.decode('key_secret',None,None) And I can see my details like this: "decode": { "token_type": "access", "exp": 1558361039, "jti": "d8317cf3849f42d2b019359ab49206ce", "user_id": 2 } I am getting a token using this route: path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), Is there any way to edit this and get token with added values. And I want to decode it privately so that no one can see. -
Different bugs always raise the same error: ImproperlyConfigured: The included URLconf 'myproject.urls' does not appear to have any patterns in it
I have a pretty standard Django project with several apps, each with its own urls, models, forms, etc... My issue is that whenever I make a mistake in my code - e.g. writing a wrong name for a model field in a form "fields" attribute - the error raised is always the same: django.core.exceptions.ImproperlyConfigured: The included URLconf 'myproject.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I would expect the error message to change according to the error made. This not happening makes everything extremely difficult to debug. Any ideas? -
jango.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model %s that has not been installed
I'm getting up this message when I execute manage.py makemigrations. using django 2.1 and python 3.7 I was looking for similar questions and answer but, I didn't make it. Im doing customize user model django2. here is my project tree and files. project tree prj_testing_mimi accounts <-- added app MimiUser.py <-- added here MimiUserManage.py <-- added here ... dashboard landing prj_testing_mimi setting.py ... setting.py """ Django settings for prj_testing_mimi project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$k!#-sj=bxfg)twq3660#pdmcg8%l4k(rlimvj(*h@2y&%_64v' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', 'accounts', 'landing' ] 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', ] ROOT_URLCONF = 'prj_testing_mimi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
Access to data from OrderedDict in Python and loop over it
I have an OrderedDict in my Django application which let to get content edition and content subversions for each edition. It looks like this: from collections import OrderedDict od = OrderedDict() for version in list_of_edition(): od.setdefault((version.pk, version.title), []).extend([(subversion.pk, subversion.title) for subversion in version.collection.all()]) I get: OrderedDict([((2, '10th Edition (Current)'), [(58464, 'Ph. Eur. 10.0 lite')]), ((1, '9th Edition'), [(21928, 'Ph. Eur. 9.8 lite'), (29235, 'Ph. Eur. 9.9 lite'), (36542, 'Ph. Eur. 9.10 lite')])]) # Rewritten in order to get more readable OrderedDict( [ ( (2, '10th Edition (Current)', True), [(58464, 'Ph. Eur. 10.0 lite')] ), ( (1, '9th Edition', True), [(21928, 'Ph. Eur. 9.8 lite'), (29235, 'Ph. Eur. 9.9 lite'), (36542, 'Ph. Eur. 9.10 lite')] ) ] ) This OrderedDict lets me to create tabs for navigation in navbar menu. It should be: Tab : 10th Edition (Current) | ---> subtab : Ph. Eur. 10.0 lite Tab : 9th Edition | ---> subtab : Ph. Eur. 9.8 lite | ---> subtab : Ph. Eur. 9.9 lite | ---> subtab : Ph. Eur. 9.10 lite In my menu.py file, menu is created like this: content_children = ( AdminMenuItem(_('Manage smth1'), reverse('smth1-list'), weight=100, separator=False), AdminMenuItem(_('Manage smth2'), reverse('smth2-list'), weight=100, separator=False), ... ) Menu.add_item('content', MenuItem(_('Content'), '#content', … -
Pass elements of list as a separated string to django methods
I want to pass list elements as a separated string to value mehtod. This is my main query: resumes = JobRecord.objects.all().values('field1','field2','field3','field4') Instead of writing the each field of my JobRecord model in the values method, I want to send this list values method: fields_LIST =['field1', 'field2', 'field3', 'field4'] How can I pass elements of list as a separated string to method ? Hints I tested these solutions, but none of them responded: Vay 1: str(fields_LIST) # result: "['field1', 'field2', 'field3', 'field4']" Vay 2: str1 = '' for item in fields_LIST: str1 += '\'' + item + '\'' + ',' # result: "'field1','field2','field3','field4'," Vay 3: pass list itself: JobRecord.objects.all().values(fields_LIST) # result: Error :'list' object has no attribute 'split' Vay 4: str1 = ','.join(str(e) for e in fields_LIST) # result: 'field1, field2, field3, field4' Studies I did study this resource and questions: 1,2,3,4,5,6 -
How to integrate a ranking algorithm in my Django application
I am building a simple hacker news website and would like some help on how to integrate a ranking algorithm for submitted posts. I understand that I can rank submitted posts via 'order_by', which I have done for now: def index(request): submitted_items = Submission.objects.all().order_by('-votecount')[:20] However, I would like to make the ranking more intelligent by factoring in the date at which the submission was made. To give a little bit more context, I used this code block from a tutorial that I found as a base for trying to figure out how to implement such an algorithm: class HomeView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): ctx = super(HomeView, self).get_context_data(**kwargs) now = timezone.now() submissions = Link.objects.all() for submission in submissions: num_votes = submission.upvotes.count() num_comments = submission.comment_set.count() date_diff = now - submission.submitted_on number_of_days_since_submission = date_diff.days submission.rank = num_votes + num_comments - number_of_days_since_submission sorted_submissions = sorted(submissions, key=lambda x: x.rank, reverse=True) ctx['submissions'] = sorted_submissions return ctx But I couldn't get this to work in my own application. I guess another way to phrase my question is this. Django/Python has a standard order_by() function that allows me to sort data, most simply in an ascending or descending order. Is there a way to create my … -
Database/application structure for hierarchical model in Django
Say we are modeling a hierarchical system, where a model / database row can have a "parent". In addition, an object can have a number related models. Now, the idea is that if a row does not have its own value for a certain relation, it assumes the 'parent' relations. For example: Model table: id | parent_id | name | --------------------------- 1 | NULL | One | 2 | 1 | Two | 3 | 1 | Three | 4 | 3 | Four | 5 | NULL | Five | Relation table: id | model_id | value | --------------------------- 1 | 1 | Cheese | 2 | 2 | Crackers | With the above data, I want the result to be that: model1.relation.value == Cheese (directly, no parent) model2.relation.value == Crackers (directly, even though parent model1 has a different value) model3.relation.value == Cheese (Through the parent value, model1) model4.relation.value == Cheese (Through its parent, model3, who gets its value through its own parent) model5.relation.value == NULL (model5.relation has no value, and model 5 has no parent) Is there an accepted / standard way how to model this (in a Django application, or in general)? Or might this even be … -
Django bulk delete certain queryset
I have a multiple objects of a File model. I am trying filter and delete these files based on a certain condition but am failing to succeed in this. Consider the following I have 3 File objects: File1 File2 File3 I tried to override the delete() function of the model like this: def delete(self, using=None, keep_parents=False): test_qs = File.objects.filter(file_name='File1') if test_qs: for x in test_qs: x.delete() super(File, self).delete() When I go to my Django Admin, select all the files (File1, File2 & File3) and bulk delete them, all of them all deleted instead of just File1. In my Django Console File.objects.filter(file_name='File1') returns a queryset with just File1. I also tried to override the pre_delete signal like this: @receiver(pre_delete, sender=File) def delete_certain_files(sender, instance, **kwargs): test_qs = File.objects.filter(file_name='File1') test_qs.delete() This however, results in a RecursionError How do I make sure to just delete the File objects that meet a certain condition upon bulk deletion? -
Split data with django and display in table + save data fields in one field cell mysql
Django : how i can save data fields in new field using MySQL and split data and display. For example save data: Partie 1: name : Alex job : Doctor Age : 30 Resultat : AD3 Partie 2 split: Resultat : AD3 A : Alex D: Doctor 3: 30 -
Using MQTT protocol connect devices to server with RabbitMQ and Django
I would like to to create a connection between the device(Arduino) and web server by using the MQTT protocol. As tools, we will use RabbitMQ, Django, and Django-channels for web socket. The device should communicate to the server by means of message broker in order to pass data to interface and should be possible to get back subscription by in case of any change on the interface. I know them theoretically and cannot apply practically to Django. -
Signal/Method for every executed sql statement
According to this 12 years old issue, django does not support a signal for every executed sql statement: https://code.djangoproject.com/ticket/5415 I need this in a production environment where debug=False. This means overwriting connection.queries does not work. Is there a way to run some custom code after each sql statement (even if debug=False)? -
Why doesn't the redirect work after the ajax request?
I am sending a GET request. I process the data and get a link for the redirect. I understand that need to send it back to the client and move from it. The link comes valid. But for some reason, the function does not enter the is_ajax () block. $(document).on('click', '.top_up_pay', function (e) { var post_data; e.preventDefault(); var amount = +$('tr.sum > td.price > span.value').text(); var products_id = []; var products_count = []; var products_deliv = []; $.each($('.name'), function(){ var id = $(this).attr('data-product_id'); products_id.push(id); var count = $(this.parentNode.parentNode.parentNode).find('input[name="count"]'); products_count.push(count.val()); var deliv = $(this.parentNode.parentNode.parentNode).find('.delivery'); products_deliv.push(deliv.val()); }) var new_post = $('.new_post > input') var ukr_post = $('.ukr_post > input') var recipient = $('.recipient > input') var phone = $('.phone > input') var sum = $('tr.sum > td.price > span.value'); var data = { products_id: products_id, products_count: products_count, products_deliv: products_deliv, new_post: new_post.val(), ukr_post: ukr_post.val(), recipient: recipient.val(), phone: phone.val(), sum: sum.text(), comment: comment, amount: amount } $.ajax({ type: "GET", url: "/payments/top-up-pay/", data: data, crossDomain: true, success: function(data){ window.location = data.redirect_to }, error: function(data){ alert('Произошла ошибка. Попробуйте позже.') } }) setTimeout(function () { window.location.href = "/products/"; }, 2000); views def top_up_pay(request): template = 'payments/top_up_pay.html' conf_currency = AppConfig.get_config('subscription_price_currency') if request.method == "GET": global req_data req_data = …