Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Post form data then render new template
So I have a form in my HTML that looks like this: <form id="passer" method="POST" action="{% url 'Sizer:printView' %}"> {% csrf_token %} <input type="hidden" id="vals"> <input type="submit" value="Print all selected items" id="printBut"> </form> With this form what I wish to achieve is when the submit button is clicked my jQuery will calculate a value and put it into the vals field in the form, then I want it to post to the printView view (to get the calculated data into a view) then once the data has been post render a new template and pass in the data calculated by the jQuery. My printView (where the data is being posted) looks like this: def printView(request): to_print = str(request.POST.get('vals')) template = "Sizer/printview.html" context = {'to_print':to_print} return redirect('requested_print_data', to_print) And my requested_print_data view (where I want to render my new template) looks like this: def requested_print_data(request): all_data['to_print'] = #Dont know how to get my variable template = "Sizer/printdata.html" context = {'all_data':all_data} return render(request, template, context) So at the moment what happens is when the form is submit, the value is calculated and stored into the form, the URL will gain the extra part from where it's being posted (www.example.com/printables ---On Submit---> www.example.com/printables/printview/) … -
Django-Haystack-Elasticsearch: error with update_index
I am trying to set up elasticsearch locally. I have installed: Django==1.8.17 django-haystack==2.5.1 elasticsearch==1.9.0 I am using the official django-haystack documentation: https://django-haystack.readthedocs.io/en/latest/index.html The content of /etc/elasticsearch/elasticsearch.yml is: discovery.zen.ping.multicast.enabled: false discovery.zen.ping.unicast.hosts: ["127.0.0.1"] node.name: "Test node" cluster.name: elasticsearch network.host: 127.0.0.1 http.port: 9200 path.data: /usr/local/var/data path.logs: /usr/local/var/log path.conf: /etc/elasticsearch However, when I try to run update_index for the first time, I get: Traceback (most recent call last): File "/home/user/tdjango2/venv/bin/django-admin.py", line 5, in <module> management.execute_from_command_line() File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/haystack/management/commands/update_index.py", line 214, in handle self.update_backend(label, using) File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/haystack/management/commands/update_index.py", line 257, in update_backend commit=self.commit, max_retries=self.max_retries) File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/haystack/management/commands/update_index.py", line 84, in do_update backend.update(index, current_qs, commit=commit) File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 190, in update bulk(self.conn, prepped_docs, index=self.index_name, doc_type='modelresult') File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 188, in bulk for ok, item in streaming_bulk(client, actions, **kwargs): File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 160, in streaming_bulk for result in _process_bulk_chunk(client, bulk_actions, raise_on_exception, raise_on_error, **kwargs): File "/home/user/tdjango2/venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 132, in _process_bulk_chunk raise BulkIndexError('%i document(s) failed to index.' % len(errors), errors) elasticsearch.helpers.BulkIndexError: (u'4 document(s) failed to index.', [{u'index': {u'_type': u'modelresult', u'_id': u'auth.user.4', u'ok': True, u'_version': 30, u'_index': u'haystack-test'}}, {u'index': {u'_type': u'modelresult', … -
Django: correct way to display dynamic images from arbitrary path
In my django app there is a model with CharField "avatar", storing the filename of object's picture (different for each object). Pictures themselves are stored in certain directory on the same host, but not inside the app directory. Say, django app is in /home/djadmin/myapp and images are in /tmp/avatars. Objects and images are frequently added/updated/deleted via other process (basically, images are uploaded to my host by ftp). I need to show these images in django template. Say, if field "avatar" stores "123.jpg" than I have to show image from path /tmp/avatars/123.jpg. How can I display these images using "img" tag in django template? I guess addind /tmp/avatars to STATICFILES_DIRS is not an option, because my images are not 'static'. -
ngnix - duplicate upstream "app_server" in /etc/nginx/sites-enabled/django
Accidentally deleted conf nginx filled/etc/nginx/sites-enabled/django , then filled it with the same configuration settings. got the following error: Feb 02 12:56:53 solomon nginx[32004]: nginx: [emerg] duplicate upstream "app_server" in /etc/nginx/sites-enabled/django.save:1 Feb 02 12:56:53 solomon nginx[32004]: nginx: configuration file /etc/nginx/nginx.conf test failed Feb 02 12:56:53 solomon systemd[1]: nginx.service: Control process exited, code=exited status=1 Feb 02 12:56:53 solomon sudo[31990]: pam_unix(sudo:session): session closed for user root Feb 02 12:56:53 solomon systemd[1]: Failed to start A high performance web server and a reverse proxy server. -- Subject: Unit nginx.service has failed -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit nginx.service has failed. -- -- The result is failed. Feb 02 12:56:53 solomon systemd[1]: nginx.service: Unit entered failed state. Feb 02 12:56:53 solomon systemd[1]: nginx.service: Failed with result 'exit-code'. Configuration, which worked before for sure. Have I done something incorrectly ?: upstream app_server { server 127.0.0.1:9000 fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/django_project/static; } location / { proxy_set_header … -
NoReverseMatch in django-machina, if forum's title in Russian language
Installation was successful, forums and topics are fine, but there is a problem - if I post a topic in Russian, there NoReverseMatch: NoReverseMatch at /forum/ Reverse for 'forum' with arguments '('', 6)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['forum/forum/(?P<slug>[\\w-]+)-(?P<pk>\\d+)/$'] I understand that the problem of encoding. The problem is that I just do not know which file and how to edit to correct the error. For example, it is necessary to put prsto # - * - coding: utf-8 - * -. But where? -
How dose soundcloud features divided in django apps
I have read a lot about the rule in django that an app should be focused, an app should do one thing and do it well so if we are talking about 3 main features in a website like sound cloud Album: which have many songs Song: only one song , it could be part of an album Play list: has an album or some songs how it would be divided into apps in django should each one have it's own app with it's own models file and use each app in the other as the have relations -
Django - d3 make small display of part of page
How to make something like this: I'm interested in top right corner where is in new window displayed small image with rectangle over zoomed part. My web application is written in Django using d3 for visualization. -
django allauth install migrate
I build a site with django/ When I install django-allauth I get error on MIGRATE step (according to this instruction) D:\prj\cool> python manage.py migrate ........................... File "D:\Python3\lib\site-packages\openid\yadis\etxrd.py", line 31, in <module> SafeElementTree = importSafeElementTree() File "D:\Python3\lib\site-packages\openid\oidutil.py", line 83, in importSafeElementTree return importElementTree(module_names) File "D:\Python3\lib\site-packages\openid\oidutil.py", line 106, in importElementTree ElementTree = __import__(mod_name, None, None, ['unused']) File "D:\Python3\lib\site-packages\defusedxml\cElementTree.py", line 16, in <module> from .ElementTree import DefusedXMLParser, _IterParseIterator File "D:\Python3\lib\site-packages\defusedxml\ElementTree.py", line 62, in <module> _XMLParser, _iterparse, _IterParseIterator, ParseError = _get_py3_cls() File "D:\Python3\lib\site-packages\defusedxml\ElementTree.py", line 56, in _get_py3_cls _IterParseIterator = pure_pymod._IterParseIterator AttributeError: module 'xml.etree.ElementTree' has no attribute '_IterParseIterator' Any ideas? Python 3.6, django 1.10, django-allauth -
Using ws4redis with Channels installed
We need to keep running ws4redis next to channels if we want to make the change, because we cannot guarantee everyone updates their mobile app that uses websockets. I succeeded in the configuration of Ngnix, Supervisor and Django for sockets through asgi and our old way of serving through wsgi runs alongside just fine. It's just that I can't get ws4redis to work. It seems like because it still uses a runserver command instead of calling uwsgi directly the process gets highjacked by Daphne and it fails. Now I don't know if I should file an issue at Channels, ws4redis or somewhere else. Maybe someone here knows how to proceed. supervisor config: [program:platform_production_uwsgi-main] command=/srv/platform/production/env/bin/uwsgi --ini=/etc/platform-serverconf/website.com/production/uwsgi-main.ini [program:platform_production_uwsgi-websockets] command=/srv/platform/production/env/bin/uwsgi --ini=/etc/platform-serverconf/website.com/production/uwsgi-websockets.ini [program:platform_asgi_daphne] directory=/srv/platform/production/src/ command=/srv/platform/production/env/bin/daphne -u /srv/platform/production/daphne.sock asgi:channel_layer [program:platform_asgi_workers] command=/srv/platform/production/env/bin/python /srv/platform/production/src/manage.py runworker process_name=asgi_worker%(process_num)s numprocs=4 ws4redis ini: [uwsgi] socket = /srv/platform/production/uwsgi-websockets.sock chmod-socket = 770 uid = deploy gid = www-data vacuum = true master = true single-interpreter = false enable-threads = true home = /srv/platform/production/env/ chdir = /srv/platform/production/src/ module = wsgi:_websocket_app touch-reload = /srv/platform/production/src/wsgi.py limit-as = 2047 logto = /srv/platform/production/logs/uwsgi-websockets.log logfile-chown = deploy:deploy buffer-size = 32768 cheaper = 5 cheaper-initial = 5 workers = 10000 cheaper-step = 2 uwsgi-websockets traceback: Traceback (most recent call last): … -
django template tags in ng-app element not working
So I have a code like below scene :1 {% block navigation %} {% include 'manage_navigation.html' %} {% endblock navigation %} {% block content %} <div ng-app="UserModule"> <div ui-view=""> </div> </div> {% endblock content %} This works fine, but when I do below scene :2 <div ng-app="UserModule"> {% block navigation %} {% include 'manage_navigation.html' %} {% endblock navigation %} {% block content %} <div ui-view=""> </div> {% endblock content %} </div> It doesn't work at all. I want to use scene :2, because that contains navigation bar and I want to call states defined in $stateProvider on click of menu items placed in navigation bar. -
TIMEOUT not working django-redis-cache
I have the settings cache and my TIMEOUT not working. My cache never do update. CACHES = { 'default': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': 'localhost:6379', 'TIMEOUT': 5, 'OPTIONS': { "SOCKET_CONNECT_TIMEOUT": 5, # in seconds "SOCKET_TIMEOUT": 5, # in seconds 'DB': 1, 'PASSWORD': '', 'PARSER_CLASS': 'redis.connection.HiredisParser', 'PICKLE_VERSION': 2, }, }, } -
Celery not starting on AWS EB instance
I have celery/redis setup for runnning tasks. Everything is working locally when i start my redis server & celery service. However, when I try to run celery -A myproj worker -l info in the aws eb instance, I get the error from the AppRegistry that the Apps aren't loaded. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm not finding why this is happening nor why it's related to starting my celery service. Here is my celery.py file which is in my project folder from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. settings = os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.dev") app = Celery('myproj') # namespace='CELERY' means all celery-related configuration keys should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) And also here's the full stacktrace Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/bootsteps.py", line 115, in start self.on_start() File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/apps/worker.py", line 143, in on_start self.emit_banner() File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/apps/worker.py", line 158, in emit_banner ' \n', self.startup_info(artlines=not use_image))), File "/opt/python/run/venv/local/lib/python3.4/site-packages/celery/apps/worker.py", line 221, in startup_info results=self.app.backend.as_uri(), File "/opt/python/run/venv/local/lib/python3.4/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) … -
How can I render values from a loop from views to template?
I'm creating a private 1 to 1 chat between users and I'd like to show the last sent message, the problem is that I'm looping every room's last message and filtering/ordering the last submitted data. Here is what I have in my views.py: def my_rooms(request, username): user = User.objects.get(username=username) room_user = Room.objects.all() print('----------------------------------------') for room in room_user: room_seller = room.gig.user rooms = room.messages.filter(Q(Q(seller=room_seller) & Q(client=request.user)) | Q(Q(seller=request.user) & Q(client=room_seller))).order_by('-timestamp')[:1] print(rooms) return render(request, "my_room.html", { 'rooms': rooms, }) print(rooms), (each article has their own private chat room): ------------------------------- [] [<Message: 02-02-2017 09:50AM, user01 to user02 : hey>] #room1 [] [<Message: 02-02-2017 10:52AM, user01 to user02 : Fine and you ?>] #room2 my_room.html {% for room in rooms %} <p>{{ room.client }} : {{ room.message }}</p> <p>{{ room.timestamp }}</p> {% endfor %} What happens in my template ? I just get : [<Message: 02-02-2017 10:52AM, user01 to user02 : Fine and you ?>] #room2 's datas published but NOT [<Message: 02-02-2017 09:50AM, user01 to user02 : hey>] #room1 Why so ? How can I show all concerned rooms datas ? -
django-taggit views don't find table
I have problem. mysql has table named Taggedsubjects and Taggedsources. but I made Taggedsubject not Taggedsubject"s". problem is that 1146. "table 'myapp.photo_taggedsubject' doesn't exist" I think my views has problem. but i don't find it. please help me thanks. this is my models. from taggit.managers import TaggableManager from taggit.models import TaggedItemBase class Taggedsource(TaggedItemBase): content_object= models.ForeignKey('Photo', on_delete=models.CASCADE) class Admin: pass class Taggedsubject(TaggedItemBase): content_object= models.ForeignKey('Photo', on_delete=models.CASCADE) class Admin: pass class Photo(models.Model): user = models.ForeignKey(User) image_file = ProcessedImageField(upload_to='static_files/uploaded/%Y', format='JPEG', options={'quality': 100 }) source = TaggableManager(through=Taggedsource, related_name='source') subject = TaggableManager(through=Taggedsubject, related_name='subject') description = models.TextField(max_length=500, blank=True) Comments = models.PositiveSmallIntegerField(default=0, null=True) posted_on = models.DateTimeField(default=datetime.now) this is my form. from django import forms from photo.models import Photo class PhotoEditForm(forms.ModelForm): class Meta: model = Photo fields = ('image_file','source','subject', 'description',) this is my views. from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from photo.models import Photo, Taggedsubject, Taggedsource from photo.forms import PhotoEditForm from django.conf import settings from django.contrib.auth.decorators import login_required import datetime from django.core.urlresolvers import reverse # Create your views here. @login_required def new_photo(request): if request.method == 'POST': form = PhotoEditForm(data=request.POST, files=request.FILES) if form.is_valid(): photo = Photo(user=request.user, subject=Taggedsubject.objects.get(id=request.POST['subject']), source=Taggedsource.objects.get(id=request.POST['source']), description=request.POST['description'], image_file=request.FILES['image_file'], posted_on=datetime.datetime.now()) photo.save() return redirect(photo.get_absolute_url()) else: form = PhotoEditForm() context = { 'form': form } return render(request, … -
Django : Exception Value 'str' object has no attribute 'resolve'
I migrated my localhost Django project to an Ubuntu server. I'm working with Django 1.10.5 and I get a pretty strange error : Environment: Request Method: GET Request URL: http://172.30.10.112/ Django Version: 1.10.5 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'BirthCertificate', 'Identity', 'bootstrapform', 'Accueil', 'captcha', 'django_countries', 'log', 'Mairie'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware'] Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py" in resolve 272. sub_match = pattern.resolve(new_path) Exception Type: AttributeError at / Exception Value: 'str' object has no attribute 'resolve' But, If I press Enter one more time in my URL bar, I can access to my Django website. This is my urls.py file : from django.conf.urls import url, include from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from BirthCertificate import views from Identity import views from Accueil import views from log import views from Mairie import views from Accueil.views import main_view urlpatterns = [ url(r'^$', main_view, name='index'), url(r'^admin/', admin.site.urls), url(r'^BirthCertificate/', include('BirthCertificate.urls')), url(r'^Identity/', include('Identity.urls')), url(r'^Accueil/', include('Accueil.urls')), url(r'^Home/', include('log.urls')), url(r'^captcha/', include('captcha.urls')), url(r'^Mairie/', include('Mairie.urls')), ] Accueil urls.py : … -
Regexfield insufficient to validate text input (Django form)
In a Django form, users set their usernames. The username field in the form is defined like so: username = forms.RegexField(max_length=50,regex=r'^[\w.@ +-]+$', help_text=_("Required. 50 characters or fewer. Letters, digits and " "@/./+/-/_ only."), error_messages={ 'invalid': _("This value may contain only letters, numbers and " "@/./+/-/_ characters.")}) Validation occurs when the regular expression is matched, otherwise not. For instance, setting the username Bender* is invalid, whereby Bender@ is valid. I've noticed that my form throws a nasty error if the user enters arabic or persian text, instead of elegantly invalidating it. E.g. if one tries العربی as the username, the following is thrown: UnicodeEncodeError at /keep_username/ 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128) Why doesn't this piece of text invalidate like normally (and What can I do to fix this)? Thanks in advance! -
Storing billions of IPv6 with Django
I've faced the problem to track usage of IPv6 in our network. Currently Django have GenericIPAddressField that handles both IPv4 and IPv6 addresses and stores them as CHAR(39) in MySQL. For some time it was enough for our needs to process IPv4 and IPv6 the same way. BUT, now we have clients with hundreds of thousands of allocated IPv6 and with potential billions of IPv6 there must be completely different approach to store. I even think we must store them separately and not in MySQL. What is the proven way to deal with billions of objects (not only IPv6)? -
what are differences between data, and validated data in django rest framework?
What transformations does django rest framework make to data after validation ? Does it only parse strings to int when possible ? -
Django: uploaded files lost when using inline formset
I need to add a simple messaging feature to a Django 1.8 application. I have a Message model and the following Attachment model: class Attachment(models.Model): message = models.ForeignKey(Message) file = models.FileField() It should be possible for a user to create a message with multiple attachments using this formset: AttachmentFormset = inlineformset_factory(Message, Attachment, extra=1, exclude=[], can_delete=False) This is how all the forms are rendered in my template: <form action="" method="post"> {% csrf_token %} {{ msg_form.as_p }} {{ attachment_formset.management_form }} {% for form in attachment_formset.forms %} {{ form.as_p }} {% endfor %} <input class="button" type="submit" value="{% trans 'Send'%}"></input> </form> This is how I process the forms in my view: if request.method == "POST": msg_form = MessageForm(request.POST) attachment_formset = AttachmentFormset(request.POST, request.FILES) sender = request.user if msg_form.is_valid() and attachment_formset.is_valid(): msg = msg_form.save(sender=sender) for aform in attachment_formset: a = aform.save(commit=False) a.message = msg a.save() The problem is that somehow, request.FILES is always empty and the attachment form's cleaned_data is empty as well. What's happening to the uploaded file?! What's the correct way to process an inline formset with a FileField? -
View being called twice/object created twice
I have a Comment model with 2 views: 1 for parent comment and one for replies. The parent view works fine but for some reason my reply view gets called twice, which creates 2 reply objects at once. So first off here's a .reply button the user clicks which brings up the comment form and giving that comment form an onclick value of reply_comment(): $('.reply').on('click', function(e) { var clone = $('.comment_form').clone(); parent_id = $(this).closest('.comment_div').data('comment_id'); $(this).closest('.comment_div').after( clone ); clone.addClass('reply_comment_form').removeClass('comment_form'); clone.attr('onclick', 'reply_comment()'); clone.data('comment_id', parent_id); $(this).next().css('display', 'inline-block'); $(this).css('display', 'none'); $('.reply_comment_form').css('padding', '1px'); }); And here's the actual function: function reply_comment() { $('.reply_comment_form').on('submit', function (e) { e.preventDefault(); parent_id = $('.reply_comment_form').data('comment_id'); $.ajax({ type: 'POST', url: '/comment_reply/', data: { reply_text: $(this).find('.comment_text').val(), parent_id: parent_id, id: path, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, success: function(data) { $('.reply_comment_form').replaceWith("<div class='comment_div new_comment'><div class='left_comment_div'>" + "<div class='username_and_votes'><h3><a href='#' class='username'>" + data.username + "</a></h3><span class='upvotes' style='margin: 0 6'>0</span><span class='downvotes'>0</span></div><br><p>" + data.reply_text + "</p></div><a href='#'><span class='comment_delete'>x</span></a></div>"); $('.new_comment').css({ 'width': '72%', 'margin': '0 70 10 0', 'float': 'right', }); $('.new_comment').next().css('clear', 'both'); $('.new_comment').prev().find('.cancel_comment').css('display', 'inline-block') .find('.cancel_comment').css('display', 'inline-block'); } }); }); } this AJAX call successfully appends the reply, and is sent to this view to save it to the database: def comment_reply(request): print('reply') if request.is_ajax(): comment = CommentForm(request.POST or None) reply_text = … -
mezzanine change history in admin
Change history of page are display incorrectly in admin panel. It show some-thing like raw data Instead of describing changes, for example: [{"changed": {"fields": ["content", "keywords"]}}] Settings file below: from __future__ import absolute_import, unicode_literals import os from django import VERSION as DJANGO_VERSION from django.utils.translation import ugettext_lazy as _ ###################### # MEZZANINE SETTINGS # ###################### ADMIN_REMOVAL = ( "mezzanine.generic.models.ThreadedComment ", "mezzanine.pages.models.Link", "mezzanine.forms.models.Form", "mezzanine.galleries.models.Gallery", ) PAGE_MENU_TEMPLATES = () USE_MODELTRANSLATION = False ######################## # MAIN DJANGO SETTINGS # ######################## SECRET_KEY = <some_data> NEVERCACHE_KEY = <some_data> ALLOWED_HOSTS = ['localhost', '127.0.0.1'] FILEBROWSER_EXTENSIONS = { 'Image': ['.JPG', '.JPEG', '.GIF', '.PNG', '.TIF', '.TIFF'], } TIME_ZONE = 'Asia/Yekaterinburg' USE_TZ = False LANGUAGE_CODE = "ru" LANGUAGES = (('ru', _('Russian')),) DEBUG = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True SITE_ID = 1 USE_I18N = True AUTHENTICATION_BACKENDS = ("mezzanine.core.auth_backends.MezzanineBackend",) FILE_UPLOAD_PERMISSIONS = 0o644 ############# # DATABASES # ############# DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "dev.db", "USER": "", "PASSWORD": "", "HOST": "", "PORT": "", } } ######### # PATHS # ######### PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__)) PROJECT_APP = os.path.basename(PROJECT_APP_PATH) PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH) CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_APP STATIC_URL = "/static/" STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/")) MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(PROJECT_ROOT, MEDIA_URL.strip("/")) ROOT_URLCONF = "%s.urls" % PROJECT_APP TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(PROJECT_ROOT, "templates") … -
i want to call two different class "You cannot access body after reading from request's data stream"
i want to call two different class from one class in viewset of Django class SocialLoginViewSet(viewsets.ModelViewSet): permission_classes = (permissions.AllowAny,) def social_login(self, request): email = request.data['email'] if email: user_qs = MobileUser.objects.filter(email__iexact=email, is_active=True) if user_qs.exists(): ExtendedJSONWebTokenAPIView.as_view()(self.request) else: NormalUserCreateViewSet.as_view()(self.request) both viewset i am calling through Post method -
Django Model Authorisation
In my django app, I've some CRUD opeaeations over some models, which I want to be accessed only by the user who created that row. Here its not role based authorisation as all users are same, I want them to be identified by the user who created it. I tried something like class someModel(models.Model): user = models.ForeignKey(User, db_index=True) .... In my views, I would do the checking by def view(request, id): model = somemodel.objects.get(id=id, user=request.user) if model.user = request.user: ... Would this be the easiest and yet be correct way to do row level authorisation? -
Pass Queryset list to javascript function with date time field
With a query set from my django model, I would like to print a LineChart using Google Chart with date time in X values. The date time in javascript need to be in this format : new Date(YEAR, MONTH, DAY, HOUR, MINUTE) I need to pass a list like this one to Google Chart: data.addRows([ [new Date(2000, 8, 5), 1200], [new Date(2001, 8, 5), 1223], [new Date(2002, 8, 5), 1240] ] In my django views.py file, I am doing this : def Function(request, page_id): query_set = MyModel.objects.filter(page__pk=page_id) list_impressions = query_set.values_list('created_at', 'page_impressions') context = {'impressions': list_impressions} return render(request, 'datacenter/facebook/impressions.html', context) In my django template, {% for record in impressions %} {{ record }} {% endfor %} I get : (datetime.datetime(2017, 2, 1, 8, 17, 49, 732016, tzinfo=<UTC>), 219482) (datetime.datetime(2017, 2, 1, 8, 52, 11, 912992, tzinfo=<UTC>), 219482) But I need to pass to javascript : var data = google.visualization.arrayToDataTable( [new Date(2017, 2, 1, 8, 17, 49), 1200], [new Date(2017, 2, 1, 8, 52, 11), 1223] ); Where should I make the link between the representation of date time in Django and Javascript ? Views, template ? I tried to use many other questions in stack overflow with no success. I also … -
Django create user instance without password field
Currently i am trying to make an app which doesn't require password for user login. But the user model has a password field in it. Is it possible to create user auth model with out password field with overriding or customizing? I'm using django 1.9.