Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django dropdown form and trigger python script
Newbie with Django and Python. Creating a Nav bar with dropdown list (which being populate via form.py) Once the user select the item, Another dropdown list will display. After user selected the item from the list and hit submit, Like to trigger python script to fetch data and populate in table format Stuck executing python script Following code: views.py: class StatusLayoutPageView(FormView): template_name = "status_layout.html" form_class = SelectLocationForm def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. return super().form_valid(form) class DataView(FormView): ## This will contain the output template_name = "data.html" form_class = SelectLocationForm Here is the models.py LOCATIONS = ( ('DC1', 'DC1'), ('DC2', 'DC2'), ) class SelectLocationForm(forms.Form): error_css_class = 'error' location = forms.ChoiceField(choices=LOCATIONS, required=True) class Meta: model = SelectLocation Here is the template: <form method="post">{% csrf_token %} <select name="location"> <option selected>Select Location</option> {% for val in form.location %} <option value="{{ val }}"></option> {% endfor %} </select> <p> <button align="center" class="button execute" name="submit" value="submit">GO TO</button> </form> Issue running into is how to tell which value user selected base on that load the page. Also with the button onclick, like to pass the data to python script to run thru the … -
Django Rest Framework. How can I serialize model name and instance values instead of content_type and object_id?
I believe there should be a straightforward way to do this, but I can't figure it out. Appreciate some help. In a model like this: class Item(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return str(self.content_type) + str(self.content_object) I serialized it like that: class CaseDetailSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' Which returns me: [ { "id": 1, "object_id": 35, "content_type": 29 }, { "id": 2, "object_id": 36, "content_type": 31 } ] And I would like to have something like that: [ { "id": 1, "object_id": "A value from the instance such as name, instead of the ID", "content_type": "The name of the model, or even better, the verbose name" }, { "id": 2, "object_id": "A value from the instance such as name, instead of the ID", "content_type": "The name of the model, or even better, the verbose name" } ] SlugRelatedField seems to be the way forward, but I can make it work. Adding this to the serializer is a good stepforward. content_type = serializers.SlugRelatedField( queryset=ContentType.objects.all(), slug_field='model') However, for the object_id is not so clear to me how to query since the model is not always the same. Thanks in advance, … -
Too many connections to the DB in Heroku-postgress
In my code I can't find an error, but something wrong. Every few seconds in the heroku-postgresql there is +1 connection. The one place, where it can happens is: def dis_online_users(): date_time_now = datetime.datetime.utcnow() users = Users.objects.filter(when_online__lt=date_time_now, is_online=True) for user in users: user.is_online = False user.save() return True def start_background(): scheduler = BackgroundScheduler() scheduler.add_job(dis_online_users, 'interval', seconds=60) scheduler.add_job(remove_deleted_messages, 'interval', hours=48) scheduler.add_job(delete_null_chats, 'interval', hours=48) scheduler.start() start_background() But I can't understand what's wrong there. Can you? -
Make second request after first is done, csrf Django issue
I have a Redux app, and there is a component SalaryComponent where in its constructor I call an action creator that makes a request to the server and then dispatches an action, so the state is updated. I need to make the second request to the server after the first one is finished since I need to get some data from the first one to do the second. How would you approach the problem? Update I was able to get the second ajax called in the constructor like this: props.loadSalary(salary_id).then(() => { props.loadData(salary_id) }) I verified that loadData gets its argument salary_id correctly. But then I am getting the error Forbidden (CSRF token missing or incorrect.). The first request does not cause CSRF error, but the second somehow does. The first request is GET, but second is POST. Ultimately I solved it by using @csrf_exempt on the Django side as a decorator to the method I was using to process the second request. Another way is to get CSRF token in the browser and use it on the backend. -
Best way to have a server that only receives data?
I have a local database that I want users to be able to add to. I don't want my database to be on the server. I would want users to send data to my server which I could then look at and add accordingly to my local database. The user does not need to be notified. What would be the best way to implement this server that users can send information to? I'm basically trying to think of a way to have a secure server that only receives information. How do I create a receive-only data server? I'm not really sure how to go about implementing this. -
ModuleNotFound even though its there
When I try to import a function I created in a different file in the same directory, it does not let me. I tried creating a test.py and importing the function and calling it and it works but it doesn't work in my view.py from django.shortcuts import render, redirect from django.http import HttpResponse from timeconverter import converttime import requests, json, os, pickle Trying to call converttime() ModuleNotFoundError: No module named 'timeconverter' -
how to limit_choices_to self field id in django model
how use limit_choices_to in django class Category(models.Model): """ 商品类别 """ CATEGORY_TYPE = ( (1, "一级类目"), (2, "二级类目"), (3, "三级类目"), ) category_id = models.AutoField(primary_key=True, verbose_name='category_id') category_title = models.CharField(default='', max_length=50, verbose_name='目录标题', help_text='目录标题') category_name = models.ForeignKey(LinkDesignate,blank=True, null=True, to_field='link_des_text_id', related_name='category', on_delete=models.CASCADE) category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="类目级别", help_text="类目级别") parent_category = models.ForeignKey("self", limit_choices_to={"category_type__lte": category_type}, null=True, blank=True, verbose_name="父类目级别", help_text="父目录", related_name="sub_cat", on_delete=models.CASCADE) class Meta: verbose_name = "产品目录" verbose_name_plural = verbose_name have errors: int() argument must be a string, a bytes-like object or a number, not 'IntegerField' -
Is there a Python Database Framework? (Like a web framework without the web)
Is there such a thing as a Python Database Framework? I want all the things a web framework has (pluggable objection creation and management, authentication, authorization, robust error handling, etc.), just without the web. My previous experience is creating Django REST Frameworks that communicate via REST (i.e. microservices), but I'm on a project where the lead is against that, and wants each service to live and in the same Django application and call each other directly, and I'm at a loss. Is there a framework for interacting with databases in a similar way as DRF, but oriented around returning database objects instead of web responses? Just using Django's ORM doesn't like that, because a lot of the nice checks and common actions are baked into the views. Thanks for your thought! -
What's the best way to perform actions before a Model.save() using Django?
I'm using Django-Rest-Framework(ViewSet approach) on my project interacting with a React app. So, I'm not using Django admin nor Django forms. My project's structure is: 1. View 2. Serializer 3. Model What I need to do is to perform actions before models method calls: 1. Insert the request.user on a Model field. 2. Start a printer process after a Model.save() 3.... I have read a lot about django-way to do on Django.docs and there, the things seems to be showed for a Django-Admin like project, wich is not my case. By other hand, by reading the Stack's answers about in other topics, the way to do seems to be like: "It will work, but, It's not the right way to do that". According to Django's documentation, the best way to perform that supposed to be by using a new file, called admin.py, where I would to register actions binding to a Model wich could support save, delete, etc, but, it's not clear if this approach is to do that or only for provide a Django-Admin way to perform an action. # app/models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey(User) content = models.TextField() class Comment(models.Model): … -
500: IntegrityError at /create_post/ NOT NULL constraint failed: posts_post.body
I'm trying to integrate ajax to my django application by following this tutorial https://realpython.com/django-and-ajax-form-submissions/ and everything is fine but when ever i tried to submit a form i just get this strange error 500: IntegrityError at /create_post/ NOT NULL constraint failed: posts_post.body Request Method: POST Request URL: http://localhost:8000/create_post/ Django Version: 2.2.2 Python Executable: C:\Users\madhumani\workspace\wiring bridge\wb\venv\Scripts\python.exe Python Version: 3.7.1 Python Path: ['C:\\Users\\madhumani\\workspace\\wiring bridge\\wb\\scrapshut', 'C:\\Users\\madhumani\\workspace\\wiring bridge\\wb\\venv\\Scripts\\python37.zip', 'C:\\Users\\madhumani\\workspace\\wiring bridge\\wb\\venv\\DLLs', 'C:\\Users\\madhumani\\workspace\\wiring bridge\\wb\\venv\\lib', 'C:\\Users\\madhumani\\workspace\\wiring bridge\\wb\\venv\\Scripts', 'c:\\users\\madhumani\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\madhumani\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\Users\\madhumani\\workspace\\wiring bridge\\wb\\venv', 'C:\\Users\\madhumani\\workspace\\wiring bridge\\wb\\venv\\lib\\site-packages'] Server time: Thu, 18 Jul 2019 17:14:52 +0000 ajax code function create_post() { console.log("create post is working!") // sanity check console.log($('#exampleFormControlInput1').val()) console.log("create post is working!") // sanity check $.ajax({ url : "create_post/", // the endpoint type : "POST", // http method data : { the_title : $('#exampleFormControlInput1').val() , the_content : $('#exampleFormControlTextarea1').val()}, // data sent with the post request // handle a successful response success : function(json) { $('#post-text').val(''); // remove the value from the input console.log(json); // log the returned json to the console console.log("success"); // another sanity check }, // handle a non-successful response error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom console.log(xhr.status + ": … -
Django: Encoding problem on production environment
The data is stored in a dataframe as "S\u00c3o Miguel", but the data is returned from template as "S%C3o Miguel", and Python can't find it on the dictionary. How can I solve this? Hi guys, I developed an application that gets data (as well as the labels) from the database and plots them on charts using the Highcharts library. When the user clicks on one of the bars of the charts, the label of it is sent back to the server, which returns some values. The problem is: when the data is first loaded from the database, it is stored in memory in a dataframe, where "S\u00c3o Miguel" is one of the values, but when the user clicks on a chart and the JQuery request is made to the server, it is sent back as "S%C3o Miguel". Due to this, the code can't find this key on the dataframe in the memory. I've tried to encode the string as UTF-8 with encodeuricomponent on JavaScript prior to sending it back to the server, but no sucess. The template already has the tag. def getFromDatabase(): [...] wfarm_names = pd.read_sql(query, engine) #Gets the data from the database return (list(wfarm_names['CL_NAME'].unique())) #Returns a list with … -
Unexplained python "function-redefined" error vscode on empty line
I cannot get rid of a function redefined error on the first line of a specific module, unless I uninstall the python extension from vscode. As soon as it is reinstalled, it shows the error again - leading me to believe that it may be some kind of actual error. The error persist whether it is a blank line, doc string, or import. I have cleared css caches in vscode and obviously restarted, to no avail -
how i can make a copy from both blog and comments in django?
I want to make a copy from my blog object and its comment. i write some code and it works for blog instance but does not copy its comments. This is my model: class Blog(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) text = models.CharField(max_length=500) and this is my copy function inside Blog Model: def copy(self): blog = Blog.objects.get(pk=self.pk) # comments_query_set = blog.comment_set.all() # comments = [] # for comment in comments_query_set: # comments.append(comment) blog.pk = None blog.save() # blog.comment_set.add(comments) return blog.id can you help me please ? :( -
Django Rest API - Can't make a PUT or DELETE Request
I have a django Rest API and want to make a put request through Flutter or Postman. What ends up happening is that when I make a put request it returns a response (that looks like it changed, printed out) but actually it never really changes. This is my code! class UserProfileView(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer class AssignmentView(viewsets.ModelViewSet): queryset = Assignment.objects.all() serializer_class = AssignmentSerializer filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, rest_framework.filters.OrderingFilter, ) filter_fields = ['studyplan'] class UserAssignmentView(AssignmentView): http_method_names = ['get', 'post', 'put', 'delete'] def get_queryset(self): return Assignment.objects.filter(canview__user=self.request.user) def put(self, request, format=None): return Response({'received data': request.data}) def delete(self, request, format=None): return Response({'received data': request.data}) class StudyplanView(viewsets.ModelViewSet): queryset = Studyplan.objects.all() serializer_class = StudyplanSerializer class UserStudyplanView(StudyplanView): def get_queryset(self): return Studyplan.objects.filter(canview__user=self.request.user) -
How to push to Heroku without database being reset
I have an app running on Heroku with a database attatched. But everytime i push my local project to heroku it resets the database to the one i'm pushing, os all the changes my app has done to the database is lost. I have tried to solve this a few different ways but nothing seems to work. -
How to serve static folder which is located in network drive using nginx
I have a network drive mounted on my redhat server 7 using /etc/fstab. We have a folder called "FolderA" under this folder we have subfolders. We need to serve this folder as static folder location using nginx. It seems not working. We have another folder called static which is present on the same filesystem. It is working properly when served with nginx. The requirement is to serve both folders if not found in one folder find it in other folder. # location /static/ { # autoindex on; # root /www/AutomationServices/static; # try_files $uri $uri/ @secondStatic; # } # location /storage/ { # root /storage/Investigator_Validator; # } # location @secondStatic{ # root /storage/Investigator_Validator; # } location ~ ^/static/(.*)$ { root /; autoindex on; try_files /www/AutomationServices/static/$1 /storage/Investigato r_Validator/$1 =404; } The final result is like to serve two folders as static locations using nginx webserver. One folder is located in network drive and one is located in the filesystem -
Face Recognisation for login using django
I am trying to implement a facial recognition login system but I have an error "Operands could not be broadcast together with shapes (128,) (0,)" and I have no idea what or how can I solve it. Here are my view.py and facedetector.py that have been implemented and the error that I get from my server: link to complete project https://github.com/Vampboy/Face-Recognition-Login-System someone has already asked this question previously Operands could not be broadcast together with shapes (128,) (0,) error but didn't get much response. probably because he didn't provided complete code. Blelow is error I am getting: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/base/ Django Version: 2.2.3 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages'] 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/tiktok/.local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/tiktok/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/tiktok/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/django_app/djangoproject/mysite/pages/views.py" in base 54. if facedect(user.userprofile.head_shot.url): File "/var/www/django_app/djangoproject/mysite/pages/views.py" in facedect 33. check=face_recognition.compare_faces(face_1_face_encoding, face_encodings) File "/home/tiktok/.local/lib/python3.6/site-packages/face_recognition/api.py" in compare_faces 222. return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance) File "/home/tiktok/.local/lib/python3.6/site-packages/face_recognition/api.py" in face_distance 72. return np.linalg.norm(face_encodings - face_to_compare, axis=1) Exception Type: ValueError at /base/ Exception Value: operands could not … -
Django: Automatically logged in as Admin after runserver
Good day SO! I am a beginner in Django, and I am facing a small problem but I do not know where to start in Debugging it. After executing 'manage.py runserver', I will be automatically logged in as the Administrator account I created via createsuperuser. How do I fix this issue? Any clue on where I should start looking? Any help will be greatly appreciated, thank you! Will provide any details necessary -
crispy-forms gives error when trying to run on local host
I have been working on this django app for the last few days but have yet to find a solution to make it work. I am trying to deploy it on local host and also on heroku but neither will work as a result of this error. Here is the error messages that I get when trying to run python manage.py runserver ... Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\gorma\appdata\local\programs\python\python36- 32\Lib\threading.py", line 916, in _bootstrap_inner self.run() File "c:\users\gorma\appdata\local\programs\python\python36- 32\Lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Projects\new\apotofgold\ENV\lib\site- packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Projects\new\apotofgold\ENV\lib\site- packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Projects\new\apotofgold\ENV\lib\site- packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Projects\new\apotofgold\ENV\lib\site- packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Projects\new\apotofgold\ENV\lib\site- packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Projects\new\apotofgold\ENV\lib\site- packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Projects\new\apotofgold\ENV\lib\site- packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Projects\new\apotofgold\ENV\lib\site- packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Projects\new\apotofgold\ENV\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module … -
Internal Server Error 500 when deploying Django Application to Elastic Beanstalk
I followed meticulously the official AWS guide to deploy a Django App to Elastic Beanstalk (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html) for a school project. It is working locally, but when I try to deploy it shows a 500 Error message. I went through many adjustments in my code but they don't seem effective. The AWS dashboard shows one warning that says: Environment health has transitioned from OK to Warning. 100% of the requests are failing with HTTP 5xx. Could it be a timezone problem as I am currently in Europe? I tried to change debug mode from true to false, but I don't think that's the problem. the I truly do not understand why it's not working, I never got an error in the execution in the terminal and it always deployed everything correctly. It is just not showing the web page for some reason. '''(base) MacBook-Air-di-Davide:ebdjango davidemerlin$ eb create django-env Creating application version archive "app-190718_165248". Uploading ebdjango/app-190718_165248.zip to S3. This may take a while. Upload Complete. Environment details for: django-env Application name: ebdjango Region: eu-central-1 Deployed Version: app-190718_165248 Environment ID: e-3mxbcch2rm Platform: arn:aws:elasticbeanstalk:eu-central-1::platform/Python 3.6 running on 64bit Amazon Linux/2.8.6 Tier: WebServer-Standard-1.0 CNAME: UNKNOWN Updated: 2019-07-18 14:52:51.893000+00:00 Printing Status: 2019-07-18 14:52:51 INFO createEnvironment is … -
Django admin, multiple inlines, related to parent and each other, cannot save the objects toghether
I am creating devices network management using django admin, (Django==2.2), where for 1 device can be attached multiple mac addresses and for the same device can be attached multiple ips, but at the same time ips are attached to mac asdresses, and I need to chanage/add/view them toghether. For the device view I have no problems, there is all displayed, the problem is at add/change the device, need there also to add/change new mac/ip. ###From models #Device class, without others not important parameters class Devices(models.Model): ... name = models.CharField(max_length=63) ........... def __str__(self): return format(self.name) class Meta: ordering = ('name',) managed = False db_table = 'devices' verbose_name_plural = "Devices" #Macs class class Macs(models.Model): mac = models.CharField(max_length=17, validators=[validate_mac_adress]) device = models.ForeignKey('Devices', related_name="Macs", on_delete=models.CASCADE) ........... def __str__(self): return format(self.mac) class Meta: managed = False db_table = 'macs' #Ips class ip = models.CharField(max_length=15, validators=[validate_ipv4]) device = models.ForeignKey('Devices', related_name="Ips", on_delete=models.CASCADE) mac = models.ForeignKey('Macs', on_delete=models.CASCADE) def __str__(self): return format(self.ip) class Meta: managed = False db_table = 'ips' #form for inline class IpsForm(forms.ModelForm): class Meta: model = Ips exclude = ('mac',) #####from admin.py class MACInline(admin.TabularInline): model = Macs extra = 0 class IPSInline(admin.TabularInline): title = 'IPS' model = Ips form = IpsForm extra = 0 def save(self, … -
how to provide default value to a foreign while creating a new instance
i'm try to make a restaurant ordering system , when someone order multi products he/she be able to select the quantity of products which selected, if all customers are anonymous(there is no registration option) i want to provide default value instead select manually but i get this error ValueError at /orders-product/ Cannot assign "4": "ProductOrder.order" must be a "Ordering" instance. is there any solution , or if someone know a better way to achieve it, i appreciate it models.py class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Ordering(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey(Ordering, on_delete=models.CASCADE,blank=True) quantity = models.IntegerField(default=1) def create_order(sender , instance,**kwargs): instance.ordering.save() #for create new instance from ordering model pre_save.connect(create_order,sender=ProductOrder) views.py class ProductOrderCreate(CreateView): form_class = ProductOrdering model = ProductOrder template_name = 'create_product_order.html' success_url = '/' def form_valid(self,form): form.instance.order = list(Ordering.objects.values_list('pk' , flat=True).reverse().order_by('pk'))[0] return super(ProductOrderCreate,self).form_valid(form) -
how to instantly load a list of options after submitting a value in a django form
I have an easy template, first the user selects a country from a list of countries, then selects a region from a list of regions of the selected country, finally submits and results are shown. The problem is when a country is selected the regions of that country are shown only after the submit button is clicked so the user have to click submit two times, first after selecting a country to see the list of regions, second time to see results after selecting a region. # models.py class Region(models.Model): country_list = [('IT', 'Italy'), ('FR', 'France')] name = models.CharField(max_length=38) country = models.CharField(max_length=2, choices=country_list, default="IT") #views.py def index_w(request): country = request.GET.get('country') region = Region.objects.all() region = region.filter(country=country) regions = request.GET.get('regions') results = Result.objects.all() if regions is not None: results = results.filter(region=regions) return render(request, 'index_uni.html', { 'regions': region, 'country': country }) /*template*/ <form method="get" action="/university/" class="form-area"> <select name="country"> <option value="IT">Italia</option> <option value="FR">France</option> </select> <select name="regions"> {% for region in regions %} <option value="{{region.id}}">{{region.name}}</option> {% endfor %} </select> <input type="submit"> </form> When the page is loaded for the first time and the user selects a value for "country" there's no option for "regions"; after submit is clicked it correctly displays all the regions … -
How can i add custom div tag with class in ckeditor in django
I want to add special class For example, <div class="Open-subtitle"></div> I added this code in styles.js but doesn't show anything { name: 'Open-subtitle', element: 'div', attributes: { 'class': 'post-open-subtitle' } }, What should i do -
Python with Django Import error with RegistrationSupplementBase cannot import name 'ugettext_lazy'
I'm updating a very old Django project and trying to use RegistrationSupplementBase but when importing I get this error message: File "/home/projectmachine/Desktop/project_rebuild/projectname/models.py", line 11, in <module> from registration.supplements.base import RegistrationSupplementBase File "/home/projectmachine/.local/share/virtualenvs/projectname-QrYA9Qp-/lib/python3.6/site-packages/registration/supplements/base.py", line 9, in <module> from django.utils.text import ugettext_lazy as _ ImportError: cannot import name 'ugettext_lazy' I can't figure out what's wrong. It seems like there is an issue with the dependancies installed. I'm using Django 2.2 with django-inspectional-registration 0.6.2 Here is how I am importing the class: from registration.supplements.base import RegistrationSupplementBase