Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
behave-django: When running multiple apps' features the 2nd app does not find it's steps
I'm using behave 1.2.5 on Django 1.11 with behave-django 1.1.0. My historic folder structure is as following: projectroot/some/folder/app1/features/feature1.py projectroot/some/folder/app1/features/steps/steps.py projectroot/some/folder/app1/features/steps/steps_additional.py projectroot/some/folder/app2/features/feature2.py projectroot/some/folder/app2/features/steps/steps.py When I run the tests for app1 and then for app2, everything is fine. If I run them together, app1 passes and app2 complains that the step definitions are missing. Is my project structure not compatible with behave? I'm a bit lost at the moment. -
Django conditional create
Does the django ORM provide a way to conditionally create an object? For example, let's say you want to use some sort of optimistic concurrency control for inserting new objects. At a certain point, you know the latest object to be inserted in that table, and you want to only create a new object only if no new objects have been inserted since then. If it's an update, you could filter based on a revision number: updated = Account.objects.filter( id=self.id, version=self.version, ).update( balance=balance + amount, version=self.version + 1, ) However, I can't find any documented way to provide conditions for a create or save() call. I'm looking for something that will apply these conditions at the SQL query level, so as to avoid "read-modify-write" problems. -
Django Admin template override
I am following the tutorial on django website to create my first django app. Now I am stuck trying to override Django Admin template. My project directory is this: First I tried creating a new admin template in the surveys app. It works. Then, I tried with the override function. For this I created at surveys/admin.py the following code: from django.contrib.admin import AdminSite from django.utils.translation import ugettext_lazy class SurveysAdminSite(AdminSite): site_header = ugettext_lazy('Test administration') surveys_admin_site = SurveysAdminSite() And add to computationalMarketing/urls.py the following: from .admin import surveys_admin_site urlpatterns = [ path('admin/', surveys_admin_site.urls, name='admin'), ] It doesn't work, so I search, and tried something different. Add this same previous code to surveys/urls.py. Neither works. Then I rollback the changes to save the code to computationalMarketing/urls.py, but this time I changed the code from surveys/admin.py to computationalMarketing/admin.py (in fact I created the file because it doesn't exists. It works and now I see the site header that I want, but I get You don't have permission to edit anything. I have seen that is something related with superuser creation, but until now I was able to admin my surveys app without problem, so I believe in some solution related with override properly the … -
IndexError :tuple index out of range
I have a dictionary which contains a list and the list elements are supposed to be tuple qu={'price':['(300,600)','(600,900)']} I want to run the following query result=Product.objects.all() for key, value in qu: result=result.filter(attribute__price__range=value) print (result) I am getting IndexError :tuple index out of range -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet error in django, celery
I'm getting django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet error in django==2.0.2 and celery==4.1.0. No search helped me around. I tried import django django.setup() But it seems, isn't worked for me. Here is the snap -
Edit rich text editor widget in django
I'm using django-summernote(link) together with crispy-forms like this: forms.py class SomeForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(EventSettingsForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' #self.helper.form_action = reverse_lazy('simpleuser') self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) #self.helper.form_class = 'form-inline' self.helper.layout = Layout( Div( 'person', ), Div( 'text', ) ) class Meta(): model = SomeModel exclude = (....) widgets ={ 'text': SummernoteWidget, } I have a base.html as a base-template, and a test.html like so: base.html {% load static %} <!DOCTYPE html> <html> <head> <title>App</title> {% block scripts-head %} <link href = "{% static 'css/bootstrap.css' %}" rel ="stylesheet"> <link href = "{% static 'css/summernote-bs4.css' %}" rel ="stylesheet"> {% endblock %} </head> <body> <div class="mx-auto center-block w-50 p-3"> {% block content %} {% endblock %} </div> {% block scripts %} <script src = "{% static 'js/jquery-3.2.1.js' %}"></script> <script src = "{% static 'js/bootstrap.js' %}"></script> {% endblock %} </body> </html> And finally the test.html {%extends 'base.html'%} {% load static %} {% block scripts-head %} {{ block.super }} {% endblock %} {% block content %} {% load crispy_forms_tags %} {% crispy form %} {% endblock %} {% block scripts %} {{ block.super }} {% endblock %} I need to change the behaviour of the SummernoteWidget when someone pastes some text- i … -
Prevent create/update foreign key to forbidden objects in Django rest framework
Let us assume I have the following models class Blog(models.Model): user = models.ForeignKey(User, null=False, on_delete=models.CASCADE) class Post(models.Model): blog = models.ForeignKey(Blog, null=False, on_delete=models.CASCADE) post = models.TextField() The problem is that creating a Post will let me set the blog id to anything (that exists). That means that I am able to create a Post object that has a relation to a Blog object that the user does not "own". However, there are easy and documented ways to prevent the user from accessing objects via the GET method, that are forbidden to them, by filtering the queryset and using check_object_permissions. Example: class PostViewSet(viewsets.ModelViewSet): serializer = PostSerializer def get_queryset(self): return Post.objects.filter(blog__user=self.request.user) def check_object_permissions(self, request, obj): if obj.user != request.user: raise exceptions.PermissionDenied() super().check_object_permissions(request, obj) How do I solve my above issue and prevent creating relations to forbidden objects the smartest/correct way in Django REST framework? -
Parse large file and paginate / load its parts with scrolling
I'm looking for suggestions and the most Django way of loading large variable content (say massive 10,000 lines list) part by part to user page to display only some lines before user asks for more. This is a detailed scenario (I hope it makes sense to you. It is just a simple example to help dealing with large template variables and pagination): User goes to website.com/searchfiles which is hosted on my Django backend and returned as a template searchfiles.html template contains one form with Select drop-down menu to let choose a file that already exists on server (say there are 20 massive log files). Below the drop-down menu there is a text box that allows user to enter a regular expression string. So only two items in the form. P.S. Each file is usually pretty big e.g. 20-30MB When user selects the file and enters regular expression in the text box and clicks on "Submit", HTTP POST is made Django backend receives POST, reads the filename + regexp string and executes function dosearch(FILE, pattern) dosearch function does something like this: dosearch(FILE, pattern): result = [] fh = open(FILE, 'r') for line in fh: if re.match(pattern, line): result.append(line) return result Now, … -
Translation label with link dosen't work
I am working with django 1.6 and I would like to translate label in form: is_check = forms.BooleanField(required=True, label=mark_safe(_(u'Before send please <a href="test.com">read</a> text.'))) I want to translate to another language but is working only with english. Solution is working without link inside. -
Django form field creation and form data retrieval
I have a model in django as follows: class DeviceType(models.Model): device_type = models.CharField(max_length=200,unique=True) def __str__(self): return self.device_type class Device(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') serial_number = models.CharField(max_length=200,unique=True) in_use_by = models.ForeignKey(User,to_field='username') brand = models.CharField(max_length=200,default="-", null=False) model = models.CharField(max_length=200,default="-", null=False) type_number = models.CharField(max_length=200,blank=True,null=True) mac_address = models.CharField(max_length=200,blank=True,null=True) I want to make a django form that would have a drop-down as follows: (Below is the general pattern of the data present in drop-down menu): devicetype-serialnumber-model-brand e.g: Laptop-abcd1234-T45k-QWER How can I achieve this? My, second question is, Suppose I select the relevant option from drop-down, fill the other data required in the form and click submit. How can I store the data coming from the dropdown present in the form into their respective field in Device Model? My third question is, how can i print only that data in the dropdown that belongs to a particular user? For e.g: If I have only two devices with me then, the for dropdown should display only options for that two devices. -
pytest-django using existing "db as is"
I want to use the existing db "as is" with pytest but everytime I start test seems that operation on it are performed. I've created the conftest.py: import pytest from project import settings @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'PSQLDB', 'HOST': '127.0.0.1', 'PORT': '5432', } added the pytest.ini: [pytest] DJANGO_SETTINGS_MODULE=project.settings this it the tests.py: @pytest.mark.django_db(transaction=False) class TestExperiment(object): @pytest.fixture(autouse=True) def setup_stuff(self, db): pass def test_something(self): x=Mymodel.objects.last() assert x.p==0 why running py.test app/tests.py this trigger this operations on the DB? if params is None: return self.cursor.execute(sql) E psycopg2.NotSupportedError: cannot truncate a table referenced in a foreign key constraint E DETAIL: Table "demo_process" references "sl2". E HINT: Truncate table "demo_process" at the same time, or use TRUNCATE ... CASCADE. /home/tec1/.virtualenvs/xx/lib/python3.5/site-packages/django/db/backends/utils.py:83: NotSupportedError django.core.management.base.CommandError: Database PSQLDB couldn't be flushed. Possible reasons: E * The database isn't running or isn't configured correctly. E * At least one of the expected database tables doesn't exist. E * The SQL was invalid. E Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. /home/tec1/.virtualenvs/xxx/lib/python3.5/site-packages/django/core/management/commands/flush.py:74: CommandError ============================================================= 1 passed, 1 error in 0.20 seconds =================== the DB exist, if I run runserver it would connect without problems. -
relation "" does not exist in django for app name with mixed-case
I have faced a problem while working with django models. lets say my apps name is GasNet and my models name is Riser well the generated table name is GasNet.riser, I can successfully generate table and add objects to table and even delete all of the objects of a table. But when I try to delete an object I face this error The above exception (relation "GasNet_riser" does not exist LINE 1: ..."."createDateTime", "GasNet_riser"."deleted" FROM "GasNet_ri... ^ ) was the direct cause of the following exception: in debug window the sql query is as sql ('SELECT "GasNet_riser"."id", "GasNet_riser"."city_code", ' '"GasNet_riser"."geom"::bytea, "GasNet_riser"."node_code", ' '"GasNet_riser"."pipe", "GasNet_riser"."parcel_code", ' '"GasNet_riser"."Number", "GasNet_riser"."hack", "GasNet_riser"."multi_code", ' '"GasNet_riser"."gis_code", "GasNet_riser"."angle", "GasNet_riser"."size", ' '"GasNet_riser"."direction", "GasNet_riser"."instalation_date", ' '"GasNet_riser"."description", "GasNet_riser"."type", ' '"GasNet_riser"."status", "GasNet_riser"."instalation_type", ' '"GasNet_riser"."material", "GasNet_riser"."zone_id", ' '"GasNet_riser"."prejenti_id", "GasNet_riser"."emergency_sub_zone_id", ' '"GasNet_riser"."updateDateTime", "GasNet_riser"."createDateTime", ' '"GasNet_riser"."deleted" FROM "GasNet_riser" WHERE "GasNet_riser"."id" = %s') this is my model class Riser(models.Model): id=models.AutoField(primary_key=True) city_code = models.CharField(max_length=10) geom = models.PointField(srid=4326) node_code = models.IntegerField(default=-1,blank=True) # شماره گره جهت اعمال مصرف آن برروی گره در طراحی pipe = models.IntegerField(default=-1,blank=True) parcel_code = models.IntegerField(default=-1,blank=True) Number = models.CharField(max_length=20) #کد علمک hack = models.IntegerField(default=-1,blank=True) multi_code = models.CharField(max_length=10,blank=True) gis_code = models.CharField(max_length=20,blank=True) angle = models.FloatField(default=-1,blank=True) size = models.IntegerField(default=-1,blank=True) direction = models.TextField(max_length=500,blank=True) instalation_date = models.DateField(null=True,blank=True) # تاریخ نصب … -
django can't union other table?
django 2.0.2 python 3.4 my raw query ( MYSQL Procedures) SELECT SQL_CALC_FOUND_ROWS * FROM ( SELECT 0 AS kop, t1.Table1UID AS PostUID, t1.UserUID, t1.UserAge, t1.Content, t1.IsReply, t1.ReplyCount, t1.LikeCount, t1.IsSharePeriod, t1.ShareEndTime, t1.ReportCount, t1.IsBlind, t1.EmoIUID, t1.RegisterDate, FROM Table1 t1 WHERE t1.UserUID = i_UserUID UNION ALL SELECT 1 AS kop, t1.Tabl2 AS PostUID, t1.UserUID, t1.UserAge, t1.Content, null, t1.ReplyCount, null, null, null, t1.ReportCount, t1.IsBlind, t1.EmoIUID,t1.RegisterDate FROM Table2 t1 WHERE t1.UserUID = i_UserUID ) TEMP ORDER BY RegisterDate DESC LIMIT i_PageSize OFFSET v_Offset; my view.py Table1 = userinfomodel.table1_set.all().annotate(PostUID=F("Table1UID"), PostUIDSort=Value(0, output_field=IntegerField())).values("PostUIDSort", 'UserUID', 'PostUID', 'UserAge', 'Content', 'ReplyCount', 'IsBlind', 'EmoIUID', 'ReportCount', 'RegisterDate', 'LikeCount', 'IsSharePeriod', 'IsReply', 'ShareEndTime') Table2 = userinfomodel.storyinfo_set.all().annotate(IsReply=Value(1, output_field=IntegerField()), LikeCount=Value(1, output_field=IntegerField()), IsSharePeriod=Value(0, output_field=IntegerField()), ShareEndTime=Value("0001-01-01T00:00:00", output_field=CharField()), PostUID=F("Table2UID"), PostUIDSort=Value(1, output_field=IntegerField())).values("PostUIDSort", 'UserUID', 'PostUID', 'UserAge', 'Content', 'ReplyCount', 'IsBlind', 'EmoIUID', 'ReportCount', 'RegisterDate', 'LikeCount', 'IsSharePeriod', 'IsReply', 'ShareEndTime') Merged = Table1.union(Table2,all=True) count = Merged.count() PageSize = request.get("PageSize") PageNo = request.get("PageNo") * PageSize result = Merged.order_by("RegisterDate")[PageNo-PageSize:PageNo] models.py class Table1(models.Model): Table1UID = models.BigAutoField( db_column='Table1UID', primary_key=True) UserUID = models.ForeignKey( 'Userinfo', db_column='UserUID', on_delete=models.CASCADE) UserAge = models.IntegerField(db_column='UserAge') Content = models.TextField(db_column='Content') IsReply = models.IntegerField(db_column='IsReply') ReplyCount = models.IntegerField( db_column='ReplyCount', default=0) LikeCount = models.IntegerField( db_column='LikeCount', default=0) IsSharePeriod = models.IntegerField( db_column='IsSharePeriod') ShareEndTime = models.DateTimeField(db_column='ShareEndTime', default=datetime.datetime( 9999, 12, 30).strftime("%Y-%m-%dT%H:%M:%S")) ReportCount = models.IntegerField( db_column='ReportCount', default=0) IsBlind = models.IntegerField( db_column='IsBlind', default=0) EmoIUID = models.OneToOneField("Emoiteminfo", db_column='EmoIUID', on_delete=models.CASCADE, … -
Django http-request in graphene schema
How do I get the http-request-session object into a graphene schema? I have stored som values in request session that I need access thru. A possible solution is to send the session-id to the frontend and then pass it into the post request, but that does not seem like a good solution. Graphene hast a context_value but I don't understand how I works. Into my Django-views I put this: schema = graphene.Schema() schema.execute('{ viewer }', context_value={'session': request.session}) In my graphene schema if I try to do like described in the tutorial, it says 'WSGIRequest' object has no attribute 'get' class Query(graphene.ObjectType): viewer = graphene.Field(Viewer) def resolve_viewer(self, info): info.context.get('session') print(info.context.session.keys()) #an empty array return Viewer() -
Convert a list of dict into several single dict
I have model and data as below: class Message(models.Model): name = models.models.CharField(max_length=50) version = models.FloatField(default=1, blank=True) class Test(models.Model): user = models.ManyToManyField(User, related_name="tests", blank=True) message = models.ManyToManyField(Message, related_name="tests",blank=True) class UserMessage(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, blank=True) message = models.ForeignKey(Message,on_delete=models.CASCADE, null=True, blank=True) version = models.FloatField(default=1, blank=True) add_time = models.DateTimeField(auto_now=True) def get(request, pk): test = get_object_or_404(Test, pk=pk) user = list(test.users.all()) message = list(test.messages.all()) I have to save data as below into UserMessage table when create a test, But I don't know how to define the version of the message. [{'user': 'a', 'message': 'message1', 'version': 1.0}, {'user': 'b', 'message': 'message2', 'version': 2.0}, {'user': 'c', 'message': 'message1', 'version': 1.0}, {'user': 'd', 'message': 'message1', 'version': 2.0}] And If I got data as above, how to convert a list of dict into several single dict as below? All I want is to save single dict to database table. {'user': 'a', 'message': 'message1', 'version': 1.0}, {'user': 'b', 'message': 'message2', 'version': 2.0}, {'user': 'c', 'message': 'message1', 'version': 1.0}, {'user': 'd', 'message': 'message1', 'version': 2.0}, -
How to specify Django backend?
I do not understand what is wrong with my Django backend specification These are my urls from django.contrib import admin from django.urls import path,include from django.conf.urls import url from store import views urlpatterns = [ url(r'^', include('store.urls')), url(r'^accounts', include('registration.backends.default.urls')), path('admin/', admin.site.urls), ] This is the tree structure bookstore ├── bookstore │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── settings.cpython-36.pyc │ │ ├── urls.cpython-36.pyc │ │ └── wsgi.cpython-36.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── requirements.txt └── store ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20180604_0751.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-36.pyc │ ├── 0002_auto_20180604_0751.cpython-36.pyc │ └── __init__.cpython-36.pyc ├── models.py ├── __pycache__ │ ├── admin.cpython-36.pyc │ ├── __init__.cpython-36.pyc │ ├── models.cpython-36.pyc │ ├── urls.cpython-36.pyc │ └── views.cpython-36.pyc ├── templates │ ├── registration │ │ ├── activate.html │ │ ├── activation_complete.html │ │ ├── activation_email_subject.txt │ │ ├── activation_mail.txt │ │ ├── registration_complete.html │ │ └── registration_form.html │ ├── store.html │ └── template.html ├── tests.py ├── urls.py └── views.py Now when I try python manage.py runserver I got this Also in terminal shows me Not Found: /accounts [05/Jun/2018 09:08:17] "GET /accounts … -
Django - make list_editable only for some entries
I have a model Person which I want to have it in admin panel. I created PersonAdmin with the following: class PersonAdmin(admin.ModelAdmin): list_display = ["Name", "LastJob", "CurrentJob", "status"] list_editable = ["CurrentJob"] class Meta: model = Person admin.site.register(Person, PersonAdmin) status is tells me if the person is dead or alive. I want if status is dead -> CurrentJob to not be editable anymore. Do you have any suggestions how can I do this? Thank you! -
Using self-hosted GitLab as Oauth Provider
I managed to succefully install django-allauth and configure my app to allow authentication via Google Oauth2, but when i try to configure GitLab Oauth2 integration it juste fail with the message: The redirect URI included is not valid. I did set http://xxx.xxx.xx/accounts/gitlab/login/callback/ as Callback url Thanks! -
How to get the line number on which exception or error occurred in Python?
I have a Django ORM query like this: try: specialization_object = Specialization.objects.get(name="My Test Specialization") except Exception as ex: print(ex) When there occurs an exception then it prints "Specialization matching query does not exist.", but it does not print the line number. How can I trace the line number on which the exception or error occurred? -
The `get_context_data` of attribute of class object
The get_context_data of attribute of class object. I encounter PasswordContextMixin in django/contrib/auth/views.py class PasswordContextMixin: extra_context = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'title': self.title, **(self.extra_context or {}) }) return context I am confused with context = super().get_context_data(**kwargs), because it equals to context = object.get_context_data(**kwargs) In [15]: getattr(object, 'get_context_data') AttributeError: type object 'object' has no attribute 'get_context_data'How to understand this? -
Django app throwing errors on deployment to production using virtualenv, wsgi and apache
Trying to take my application to production has been hectic. I get syntax error when i check apache's error log after i make a call to the site. I have done everything as seen in different sources online, yet i can't get passed the error. The major problem is, i don't even get why a syntax error from Django's internal function when the app ordinarily works on development without hitches. The Error i get is as seen below [Tue Jun 05 08:13:34.179813 2018] [:error] [pid 1390] [remote ::1:0] File "/var/www/html/app_folder/app/index.wsgi", line 29, in <module> [Tue Jun 05 08:13:34.179860 2018] [:error] [pid 1390] [remote ::1:0] import django.core.handlers.wsgi [Tue Jun 05 08:13:34.179869 2018] [:error] [pid 1390] [remote ::1:0] File "/home/user/.virtualenvs/app/lib/python3.6/site-packages/django/__init__.py", line 1, in <module> [Tue Jun 05 08:13:34.179900 2018] [:error] [pid 1390] [remote ::1:0] from django.utils.version import get_version [Tue Jun 05 08:13:34.179907 2018] [:error] [pid 1390] [remote ::1:0] File "/home/user/.virtualenvs/app/lib/python3.6/site-packages/django/utils/version.py", line 2, in <module> [Tue Jun 05 08:13:34.179954 2018] [:error] [pid 1390] [remote ::1:0] import functools [Tue Jun 05 08:13:34.179982 2018] [:error] [pid 1390] [remote ::1:0] File "/home/user/.virtualenvs/app/lib/python3.6/functools.py", line 254 [Tue Jun 05 08:13:34.179986 2018] [:error] [pid 1390] [remote ::1:0] cls, func, *args = args [Tue Jun 05 08:13:34.179988 2018] [:error] [pid … -
Django Channels testing fails
I'm putting up django-channels on a basic django site, configured in the following way. consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) routing.py from django.conf.urls import url from consumers import ChatConsumer #supposed to be on the main routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter websocket_urlpatterns = [ url(r'^ws/chat/$', ChatConsumer), ] #after linking to above as chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) settings.py ASGI_APPLICATION = 'chatsys.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('35.185.80.98', 6379)], }, }, } INSTALLED_APPS = [ ... 'channels', ] After installing the necessary applications I went to the next step in the tutorial that's testing this on the shell. In [1]: import channels.layers In [2]: from asgiref.sync import async_to_sync In [3]: async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-3-80e65666e9e2> in <module>() ----> 1 async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) NameError: name 'channel_layer' is not defined In [4]: channel_layer = channels.layers.get_channel_layer() In [5]: async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) --------------------------------------------------------------------------- TimeoutError Traceback (most recent call last) <ipython-input-5-80e65666e9e2> in <module>() ----> 1 … -
Bulk image upload in djanog cms plugin
i am trying to make a plugin in which I will be able to upload multiple images one by one. Then show those images by loop inside template. This is possible in wagtail using ListBlock with ImageChooserBlock. How do I implement the same thing in django cms? -
Django Summernote WYSIWYG editor jquery edit
I'm trying to use Summernote editor with Django. There is a fix i need to implement- to strip any copy-pasted text of all tags and there is a fine solution here which looks like this: $('.summernote').summernote({ callbacks: { onPaste: function (e) { var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text'); e.preventDefault(); // Firefox fix setTimeout(function () { document.execCommand('insertText', false, bufferText); }, 10); } } }); My problem is that i don't know how to implement this in a django template since i'm using django-summernote (link) andcrispy-forms- i have never worked with jquery. My cyrispy-forms template wraps the Summernote widget in a div with id = div_id_text - Is there any way to point the code above to this ? I tried including this in my html template but to no avail: <script > $('#div_id_text').on('summernote.paste', function(e) { var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text'); e.preventDefault(); // Firefox fix setTimeout(function () { document.execCommand('insertText', false, bufferText); }, 10); } ) </script> -
Django: Combine 3 separate 'filters()' into single query
I have following piece of code def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) prefetch = ['vendor', 'picture'] context['most_popular_products'] = Product.objects.filter(is_popular=True)[:5].prefetch_related(*prefetch) context['coming_soon_products'] = Product.objects.filter(is_coming_soon=True)[:5].prefetch_related(*prefetch) context['recent_products'] = Product.objects.all()[:5].prefetch_related(*prefetch) return context As you see there are 3 separate calls for 5 latest most_popular, coming_soon and recent products. It there a way to reduce number of database calls? I'd like to construct single query like, popular, coming_soon, recent = Product.objects.filter...and.so.on Any ideas? thanks