Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Target WSGI script cannot be loaded as Python module after Django update
After upgrade django to 3.2 and switching SQLITE to MSSQL with django-mssql-backend (doubt its db fault), App is giving 500 Internal Server Error in browser and following in apache log: [Thu May 06 09:17:58.791944 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] django.setup(set_prefix=False) [Thu May 06 09:17:58.791955 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] File "/opt/xip/REST/venv/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup [Thu May 06 09:17:58.791964 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] apps.populate(settings.INSTALLED_APPS) [Thu May 06 09:17:58.791983 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] File "/opt/xip/REST/venv/lib64/python3.6/site-packages/django/apps/registry.py", line 81, in populate [Thu May 06 09:17:58.792008 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] # Prevent reentrant calls to avoid running AppConfig.ready() [Thu May 06 09:17:58.792038 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:46830] RuntimeError: populate() isn't reentrant [Thu May 06 09:20:58.788482 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] mod_wsgi (pid=126006): Target WSGI script '/opt/xip/REST/cftapi/cftapi/wsgi.py' cannot be loaded as Python module. [Thu May 06 09:20:58.788559 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] mod_wsgi (pid=126006): Exception occurred processing WSGI script '/opt/xip/REST/cftapi/cftapi/wsgi.py'. [Thu May 06 09:20:58.789020 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] Traceback (most recent call last): [Thu May 06 09:20:58.789088 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] File "/opt/xip/REST/cftapi/cftapi/wsgi.py", line 9, in <module> [Thu May 06 09:20:58.789140 2021] [wsgi:error] [pid 126006] [remote 10.111.36.22:60402] application = get_wsgi_application() … -
running some Dash-Plotly apps inside a Django app similar to PaaS (platform as a service)
I have a challenge and I would be grateful if you could give me some clue... I want to run some Dash-Plotly (a framework based on Flask) applications inside a Django app. I know Dash has a framework called django-plotly-dash but what I want is a Django app that our developed Dash(aka Flask) apps can easily be imported and run. In other words, I want to make Django app a Paas (Platform as a Service) and other Dash/Flask apps can be imported in Django dashboard/(our developed page) and can be accessible from the Django app. Some idea may be using Docker containers but is also has some challenges and we want to seek the most optimal solution. is there any idea??? -
How to delete a record in django using cloud firestore?
ERROR PICTURE I'm trying to delete a record in my table but this is giving me an error error : Reverse for 'delete_Building' with arguments '('Ep7AzCd3rcUvDjvwhvL5',)' not found. 1 pattern(s) tried: ['delete/(?P[0-9]+)/$'] -> ID is selected but template is not loading because of above error my html file : <div class="row"> <div class="col-lg-12 mb-4"> <!-- Simple Tables --> <div class="card"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <a href="{% url 'building:registerBuilding'%}" class="btn btn-sm btn-primary"><i class="fas fa-plus-circle "></i> Add Building</a> </div> <div class="table-responsive"> <table class="table align-items-center table-flush" id="buildingList"> <thead class="thead-light"> <tr> <th>BUILDING NAME</th> <th>POSTAL CODE</th> <th>STREET</th> <th>HOUSE NO.</th> <th>TOWN</th> <th>ADDITIONAL INFO</th> <th colspan="2">ACTION</th> </tr> </thead> <tbody> {% for building in buildings %} <tr> <td>{{ building.building }}</td> <td>{{ building.postalCode }}</td> <td>{{ building.houseNo }}</td> <td>{{ building.street }}</td> <td>{{ building.town }}</td> <td>{{ building.additionalInfo }}</td> <td><a href="{% url 'building:updateBuilding' %}" class="btn btn-primary btn-xs" data-title="Edit" ><i class="fa fa-pen"></i>Edit</a></td> <td><a href="{% url 'building:delete_Building' building.id %}" class="btn btn-danger btn-xs text-white" data-title="Delete"><i class="fa fa-trash"></i>Delete</a></td> </tr> {% endfor %} </tbody> </table> </div> <div class="card-footer"></div> </div> </div> </div> </div> <!---Container Fluid--> </div> my views.py file def delete_Building(request, id): docId = doc_ref.id; db.collection('Buildings').doc(docId).delete(); return redirect("/") my urls.py file path('delete/<int:id>/',views.delete_Building,name='delete_Building'), -
not able to post images through rest framework django but says status code 200
i have everything set up but when i starts posting into DRF through post function with image it shows status code 200 but does not return dynamic id of object and there is no new object in database, but when i remove imagefield from models and try to post it does not give me error and returns id of posted object.. models.py class Accounts(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(default='default.png') def __str__(self): return f'Account object' serializers.py from rest_framework import serializers from .models import Accounts class Accountserializers(serializers.ModelSerializer): class Meta: model = Accounts fields = '__all__' views.py @api_view(['POST']) def post_data(request): serializer = Accountserializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) this is the code as i said when i post something it says status code 200 and does not return dynamic id.. pls help me find the solution -
ValueError at /createPost Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser
Hello Guys I'm trying to post an image file using Django. I don't know what is happening and I got another error while trying to fix one so please see the code and I got ValueError at /createPost Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x0000020C1B569F40>>": "Post.author" must be a "User" instance this error I don't know what's going on, Im beginner so. Views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .models import Post from .forms import PostForm # Create your views here. def index(request): post = Post.objects.order_by("-pub_date") context = { "posts": post } return render(request, "index.html", context) def post_create(request): form = PostForm(request.POST,request.FILES or None) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] img = form.cleaned_data["img"] username = request.user post = Post.objects.create(title = title, content = content, img = img, author = username) post.save return redirect("posts:home") else: form = PostForm() context = { "form": form } return render(request, "postcreate.html", context) Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length = 200) content = models.TextField(null = True, blank = True) img = models.ImageField(upload_to = "static/my_post_pic", null = True, blank = True) pub_date = models.DateTimeField(default = timezone.now) … -
Exclude post if post contains "good" word
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to implement a feature that, If post description contains "good" word then exclude it from all the posts. views.py def posts(request): posts = Post.objects.all() if 'good' in posts.description: printing = 'CONTAINS' context = {'posts':posts} return render(request, 'mains/posts.html', context) From this view, I am just trying to print the contains word in template ( just for test and It's working fine ) BUT I am trying to exclude that post ( which contains good word ) from all the posts. Any help would be Appreciated. Thank You in Advance. -
How to return back just queryset objects from middleware?
I'm not sure being I understand what does Middleware will help me in Django do. but if it will help me to make some help for request/response to appear globally so that, I really need it. based on that, I read a little bit more explanations and tutorials about Middleware also, I read some docs in Django middleware hence, wanted to use a request which will return an object from query set based on this request something like you will see underneath: Order.objects.get(user=request.user, in_progress=True) I confused between the two next function names which handle the response in Middleware of Django: process_template_response and process_response the problem is I need to return back the objects which will be handled in the views.py file in Django by one of these response function. I read an old doc that supports Django 1.8 and see the difference between that two functions in response as following: the process_template_response as the documentation mentioned: is called just after the view has finished executing, if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent. but when I read about process_response despite is called it before request as I understand, I figured out that … -
stacked url when using jquery ajax post
i want to use ajax to send post data to views,i'm tryin to implement pagination,when i click page button and send jquery.Post() data. But the url got stacked what should i do? .html <div class="clearfix "> <ul class="pagination pagination-sm m-0 float-right" id="submits" > <li class="page-item" id="1" ><a class="page-link" href="{% url 'postNewRA2' RAid 1 %}" id="1">1</a></li> </ul> </div> .scripts $(document).ready(function () { $('#submits li').click(function () { var a = $(this).attr('id'); linkUrl = 'library/postNewRA2/71/' + a + '' alert(linkUrl); $.ajax({ type: 'POST', url: linkUrl, data: { 'pages': 'panji', csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: "json", contentType : "application/json", success: function (result) { window.console.log('Successful'); }, error: function () { window.console.log('Error!'); } }); }); }); I expected the urlS just http://127.0.0.1:8000/library/postNewRA2/71/1 -
Como ejecutar scripts de JAVA en PYTHON [closed]
estoy creando un sitio web con django python. Mas ahora necesito una herramienta de google dev y resulta que los codigos que me entrega google están para java, necesito saber como ejecutar ese codigo de java con todo lo que tengo de python ya que necesito captar unos datos que me retorna el script y procesarlo. -
Problem in post http request django restfamework
I have this ViewSet in my project: class UserCreditCardsViewSet(UserDataModelViewSet): queryset = UserCreditCard.objects.none() http_method_names = ['post', 'get', 'delete', 'option'] def get_queryset(self): return UserCreditCard.objects.filter(user=self.request.user) serializers = { 'default': UserCreditCardsSerializer, } permission_classes_by_action = { 'default': [IsAuthenticated], } And its the URL routing: router.register(r'accounting/credit_card', UserCreditCardsViewSet, basename='UserCreditCard') Everything else working well in my project. But when I want to do a post request to this ViewSet Its shows this error: { "detail": "Method \"POST\" not allowed." } What is the problem? -
How can I use django model formset and form wizard together in specific step of the form wizard?
I don't understand how to use formset in form wizard steps but I override the get_context_data() to pass the formset in 'camp/create-camp_1.html' which is my step 2. my views.py ImageFormSet = modelformset_factory(model=Camp, fields=('video',), form=CampForm2, extra=1) class CampWizardView(SessionWizardView): FORMS = [('0', CampForm1), ('1', CampForm2), (2, CampForm3), (3, CampForm4)] TEMPLATES = {'0': 'camp/create-camp_0.html', '1': 'camp/create-camp_1.html', '2': 'camp/create-camp_2.html', '3': 'camp/create-camp_3.html'} file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'camp')) form_list = [CampForm1, CampForm2, CampForm3, CampForm4] def get_template_names(self): return [self.TEMPLATES[self.steps.current]] def get_context_data(self, form, **kwargs): context = super(CampWizardView, self).get_context_data(form) context['formset'] = ImageFormSet() return context class ContactWizard(LoginRequiredMixin, CampWizardView): def done(self, form_list, **kwargs): formset = ImageFormSet(self.request.POST, self.request.FILES) camp = Camp(**self.get_all_cleaned_data()) camp.host = self.request.user camp.save() camp.tags.set(self.get_all_cleaned_data().get('tags')) return redirect(reverse_lazy("camp:camp_list")) -
Error while saving user with other details in model in django
I am trying to take title, thumbnail, description from user and when user upload it my model get user and save it but i am getting this error on every page of my website OperationalError at / no such column: shop_upload_detail.user_id Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2 Exception Type: OperationalError Exception Value: no such column: shop_podcast_detail.user_id Exception Location: C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\admin\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\admin\Documents\Django e commerce\ecommerce', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\admin\AppData\Local\Programs\Python\Python39', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\win32', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\win32\lib', 'C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\Pythonwin'] Server time: Thu, 06 May 2021 05:39:44 +0000 my models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Upload_detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default="", null=False, blank=False) title = models.CharField(max_length=100) tubnail = models.ImageField(upload_to="podcast_images", default="", max_length=5000) description = models.TextField(max_length=300, default="") date_published = models.DateField(default=timezone.now) class Poster(models.Model): poster_images = models.ImageField(upload_to="poster_images", max_length=5000) views.py def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): new_user = form.save() new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'],) login(response, new_user) return redirect("/") else: form = RegisterForm() return render(response, "register.html", {"form":form}) def new(request): form = new_Upload(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() return redirect('/') else: form = new_Upload() return render(request, 'upload.html', {"form":form}) upload.py from django.forms … -
Django add custom permission
I am facing the problem of adding custom permission in Django. My idea is that when authorizing a user, if it belongs to group1, only the rows of group1 are displayed, and otherwise the rows of group2. There is a group field in the database table, it contains only two values group1 and group2. In the admin panel, I created 2 groups, respectively, and also included users in these groups. Also I created permissions and assigned them to each user. My models.py class Employee(models.Model): DEPT =( ('Group1', 'Group1'), ('Group2', 'Group2') ) dept = models.CharField(max_length=100, choices=DEPT, default='') fio = models.CharField(max_length = 100) work_place = models.CharField(max_length = 150, default= '') def __str__(self): return self.fio class Meta: permissions = ( ("view_museum", "can view museum"), ("view_ssoismi", "can view ssoismi"), ) My views.py def employee_list(request): context = {'employee_list': Employee.objects.all()} return render(request, "employee_register/employee_list.html", context) If i change the context row to context = {'employee_list': Employee.objects.filter(dept="Group1")} I get the desired result, but how can do it automatically with django groups and etc. Maybe i do something wrong? Any idea what to do next? Thanks in advance -
How to add multiple json entries/items into JsonResponse in Django?
When there is only one item, the below works: data = { "Id": item.id, "Title": item.title } return JsonResponse(data) When there are multiple items, how to compose the response json? for item in items: ... here is code to compose json including multiple items ... ... ... ... ... return JsonResponse(data) The json data would look like: { "items":[ { "Id":1, "Title":"aaa" }, { "Id":5, "Title":"fahldafs" }, { "Id":17, "Title":"ajjda" } ] } -
Problem with pluralization of translations in Django
Hello I'm trying to pluralize the following text <p>{% trans "How much apples do I have? I have " %} {{ nb_apples }} {% blocktrans count nb_apples=1 %}apple{% plural %}apples{% endblocktrans %}</p> My .po file is defined like that #: .\templates\pages\home.html:13 msgid "apple" msgid_plural "apples" msgstr[0] "pomme" msgstr[1] "pommes" But the above doesn't work. With count nb_apples=1 or count nb_apples=0 it never pluralize With count nb_apples>1 it produces a syntax error With count nb_apples=1|length it always pluralizes but the singular is not respected when I only get one apple. Notice that the nb_apples variable is randomly passed from the view like that def get_context_data(self, **kwargs): posts = Post.objects.all() context = super().get_context_data(**kwargs) context['title'] = _('Home') context['comment'] = _('Welcome to my site') context['posts'] = posts context['nb_apples'] = random.randint(1,10) return context and that, after the class def home(request): nb_apples = random.randint(1,10) return render(request, 'pages/home.html', { 'title': _('Home'), 'comment': _('Welcome to my site'), 'nb_apples': nb_apples }) I want to see "apple" or "pomme" when the nb_apples variable is equal to 1 and "apples" or "pommes" when the nb_apples variable is greater than 1. What's wrong? -
Everything is running fine in local host but when I deploy the code in heroku the news24 part is not running
The setopati and news24 functions scrape the respective site for news and the obtained data is passed in the context of the home view. I have tried using URL shortener to compress link of news24 which didn't work. def ratopati(): news = [] req = requests.get('http://ratopati.com/category/coronavirus') soup = BeautifulSoup(req.content, 'lxml') articles = soup.find_all('div', {'class':'item'})[0:10] for article in articles: d = {} d['source'] = 'Ratopati' d['img_link'] = article.find('a', {'class':'item-header-image'}).find('img').attrs['src'] d['content'] = article.find('p').text div = article.find('div', {'class':'item-content'}) d['title'] = div.find('a').text d['news_link'] = div.find('a').attrs['href'] d['news_link'] = 'https://ratopati.com' + d['news_link'] news.append(d) return news def news24(): news = [] req =requests.get('https://www.news24nepal.tv/category/%e0%a4%b8%e0%a5%8d%e0%a4%b5%e0%a4%be%e0%a4%b8%e0%a5%8d%e0%a4%a5%e0%a5%8d%e0%a4%af') soup = BeautifulSoup(req.content, 'lxml') articles = soup.find_all('div', {'class':'col-md-12'})[1:10] for article in articles: d = {} d['source'] = 'News24' links = article.find_all('a') d['img_link'] = links[0].find('img').attrs['src'] d['news_link'] = links[1].attrs['href'] d['title'] = article.find('h2').text d['content'] = article.find('p').text news.append(d) return news def home(request): news = ratopati() + news24() random.shuffle(news) return render(request, 'aggregator/index.html', {'articles': news}) -
Can we run a voice assistant in django template?
I have made a django website and I am rendering a template with html animation in front , linked to css. Now I want that when my template opens my python script of the voice assistant also starts executing . is is it possible? -
how to solve 413 "413 Request Entity Too Large" on elasticbeanstalk Django project
I am getting this error while uploading file of size larzer then 1MB and i am not able to configure nginx for Django project(Python) how to default file uploading size. -
Uncaught ReferenceError with javascript
I'm trying to use a variable passed from my Django view to a html's javascript. It reads the variable fine but whenever I use the variable to process my function it just shows uncaught reference error the variable is not defined. As shown in the image below, this shows up. My function's code from view.py and the javascript code for this part: userobj = request.session.get('uid') list = request.session.get('roles') avpath = "avatar/"+ userobj['localId'] +".jpg" avpath = pyrestorage.child(avpath).get_url(None) print(userobj) return render(request, 'dashboard/sidebar.html', {"lid": userobj['localId'],"dp": avpath,"email": userobj['email'],"roles": list }) <script> var firebaseConfig = { apiKey: "", authDomain: "", databaseURL: "", storageBucket: "", 'measurementId': "", }; firebase.initializeApp(firebaseConfig); function uploadimage(){ var storage = firebase.storage(); var file=document.getElementById("files").files[0]; var storageref=storage.ref(); var x = {{lid|safe}}; var y = x.concat(".jpg"); console.log(y); var thisref=storageref.child("avatar").child("avatar.jpg").put(file); thisref.on('state_changed',function(snapshot) { console.log('Done'); }, function(error) { console.log('Error',error); }, function() { // Uploaded completed successfully, now we can get the download URL thisref.snapshot.ref.getDownloadURL().then(function(downloadURL) { console.log('File available at', downloadURL); document.getElementById("url").value=downloadURL; alert('uploaded successfully'); }); }); } </script> -
django apache2 settings on ubuntu 20 for intranet access
I can't seem to get my django site to be accessible outside of development. I have looked at countless tutorials and they all say the same thing, which I have tried. nevertheless, it doesn't work. here is what I have ubuntu 20.04 installed in a virtual machine (an openstack instance) this is on an intranet that I can access at work or through a vpn I installed apache2 created a virtual host conf file tested it with a dummy page -- it worked installed djano and a few other items that most tutorials mention made my demo default django app collected static files to myproject/static enabled mod_wsgi modified my virtual host conf file like this (using the real server name instead of "example.com"): (my project is located at /home/.../myproject) <VirtualHost *:80> ServerAdmin [email] ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com DocumentRoot /home/.../myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so Alias /static /home/.../myproject/static <Directory /home/.../myproject/static> Require all granted </Directory> Alias /media /home/.../myproject/media <Directory /home/.../myproject/media> Require all granted </Directory> <Directory /home/.../myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WsGIPassAuthorization On WSGIDaemonProcess myproject python-home=/home/.../myproject/myprojectenv python-path=/home/.../myproject> WSGIScriptAlias / /home/.../myproject/myproject/wsgi.py WSGIProcessGroup myproject </VirtualHost> I know there are two documentroots there. I tried both (but not … -
Django & GoLang: Is it possible to use GoLang with Django and python backend to serve api?
Hey guys i am currently developing an app with django backend, but heard about the problems dealing with concurrent requests. i want to know whether as our requirements increases, whether it will be possible to combine golang which can deal with concurrency a lot better than python and also keeping the robust django framework. Is it possible to serve API's using GoLang and Django working together? Thank you. -
Null value when send Post data using Ajax Jquery in Django
I am trying to makes pagination in django, i need some value (pagesNumber,SearchWord,Categories) to makes some query work ,but i cant get my post data from ajax jquery.I have succeeded in running jquery This my code CDN <script src="{% static 'plugins/jquery/jquery.min.js' %} "></script> <!-- jQuery UI 1.11.4 --> <script src="{% static 'plugins/jquery-ui/jquery-ui.min.js' %} "></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script> scripts $(document).ready(function () { $('#submits li').click(function () { var a = this.id; linkUrl = 'library/postNewRA/71/' + a + '' alert(linkUrl); $.ajax({ type: 'POST', url: linkUrl, data: { 'pages': "testValue", csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: jsonp, success: function (result) { window.console.log('Successful');//I CANT GET THIS MESSAGES TOO }, error: function () { window.console.log('Error!');//I CANT GET THIS MESSAGES TOO } }); }); }); views.py def postNewRA2 (request,raID,page): pages = request.POST.get('pages',None) # this result "None" return JsonResponse({"pages":pages}) urls.py path('postNewRA/<int:raID>/<int:page>',views.postNewRA2,name = "postNewRA2"), -
How to perform simple raw query in django
I am trying to connect my django project with phpmyadmin, so far I am following this article: https://python.plainenglish.io/connect-django-with-database-43f1965565e0 and add this line in __init__.py: import pymysql pymysql.install_as_MySQLdb() and then success to connect it. But I am confuse how to perform a simple raw query like Select * from mydata. is there a guide that can I follow step by step -
Using TinyMCE 5 with Django admin TabularInline
I am trying to apply TinyMCE (preferably in inline mode) to my Django TabularInline forms. I have tried to use TinyMCE inline mode, which would be the best solution to my problem, but it only works on div or p, therefore it might not be suitable to use for CharFields/TextFields created by Django. Then I've tried applying it without using TinyMCE inline mode, The setup was successful, but the rich text editor created is disabled and I am not able to type anything onto it. After some investigation, I've found out that the iframe created by TinyMCE, which contains the rich html text, is not properly initialised by TinyMCE. Usable Editor: <iframe id="id_model" frameborder="0" allowtransparency="true" class="tox-edit-area__iframe"> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" id="mce-u0" href="./static/tinymce/skins/ui/oxide/content.min.css"> <link rel="stylesheet" type="text/css" id="mce-u1" href="./static/tinymce/skins/content/default/content.min.css"> </head> <body id="tinymce" class="mce-content-body " data-id="id_model" contenteditable="true" spellcheck="false"> </body> </html> </iframe> Not Usable Editor (In TabularInline): <iframe id="id_model" frameborder="0" allowtransparency="true" class="tox-edit-area__iframe"> <html> <head> </head> <body> </body> </html> </iframe> Below is the code used for creating said editor: (TinyMCE5, Django3.1) inlines.js tinymce.init({ selector: '.field-choice > textarea', plugins: [ 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code ', 'fullscreen insertdatetime media table paste code codesample … -
Signal is not saved Django
I want to save the instance "code_nc" that contains the id that is created by means of a signal but does not save class NoConform(BaseModel): no_conform = models.CharField(max_length=1500, verbose_name='No Conforme') origin = models.CharField(max_length=30, verbose_name='Origen', choices=OriginNoconform.choices) correction = models.CharField(max_length=500, verbose_name='Corrección') treatment = models.CharField(max_length=30, default='Abierto', verbose_name='Estado', choices=TreatmentNoConform.choices) assigned = models.ForeignKey(Process, verbose_name='Proceso', on_delete=models.CASCADE) actions = models.CharField(max_length=20, verbose_name='Plan de Acción') code_nc = models.CharField(max_length=20, verbose_name='Código') response_nc = models.CharField(max_length=150, verbose_name='Responsable') evidence = models.FileField(upload_to='no_conform/%Y%m%d', max_length=200, verbose_name='Evidencias Complementarias', null=True, blank=True) date_event = models.DateTimeField(verbose_name='Fecha y Hora de Ocurrencia', null=True, blank=True) nc_resume = models.CharField(max_length=150, verbose_name='Defecto', null=True, blank=True) def __str__(self): return f'{self.nc_resume}, {self.id}' class Meta: db_table = 'No_Conform' verbose_name = 'No_Conform' verbose_name_plural = 'No_Conform' @receiver(post_save, sender='noconform.NoConform') def post_save_function(sender, instance, **kwargs): seq = instance.id year = datetime.now ().strftime('%Y') instance.code_nc = 'NC' + year + str (seq) def save(self, force_insert=False, force_update=False, using=None, update_fields=None, *args, **kwargs): user = get_current_user() if user is not None: if not self.pk: self.user_creation = user else: self.user_updated = user return super(NoConform, self).save(*args, **kwargs)