Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom prefetch and conditional annotate
I am using custom prefetch object to get only some related objects, ex: unreleased_prefetch = Prefetch("chants", Chant.objects.with_audio()) teams = Team.objects.public().prefetch_related(unreleased_prefetch) This works well, but I also want to know count of these objects and filter by these. I am happy that I can at the moment use queryset as parameter to Prefetch object (as I heavily use custom QuerySets/Managers). Is there way how I can reuse this query, that I pass to Prefetch object same way with conditional annotate? So far my conditional annotate is quite ugly and looks like this (it does same thing as my original chant with_audio custom query/filter): .annotate( unreleased_count=Count(Case( When(chants__has_audio_versions=True, chants__has_audio=True, chants__flag_reject=False, chants__active=False, then=1), output_field=IntegerField())) ).filter(unreleased_count__gt=0) It works, but is quite ugly and has duplicated logic. Is there way to pass queryset to When same way I can pass it to prefetch to avoid duplications? -
Django cache and usernames
So I have this site (Django 1.8) which has a master template where the name of the logged-in user is displayed, so the template contains {% if user.is_active %} {% trans 'Welcome,' %}{% filter force_escape %}{% firstof user.first_name user.username %}{% endfilter %} {% endif %} So notice it only displays when the user is active. I now setup caching where I use redis as the cache storage: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', }, "KEY_PREFIX": "mycache", } } Caching works correctly, but I notice that also that username is cached in the frontend. This means that when the user loggs off, his name is still visible like he is logged in and even worse, sometimes it displays the name of another user that logged in just before and triggered the caching. It is logical of course as I think the caching framework caches the whole page. My question is: how do you deal with this? Do I need some user-based caching of some sorts or are there better ways to avoid this? I mean, there must have been other people encountering the same problem? -
Django DetailView with form for comments
I have this url mapping: url(r'^article/(?P<slug>[-\w]+)/$', views.ArticleView.as_view(), name='article-detail'), and I have this view: class ArticleView(DetailView): model = Article template_name = 'template/article.html' context_object_name = 'article' def get_context_data(self, **kwargs): context = super(ArticleView, self).get_context_data(**kwargs) context['comments'] = self.object.comment_set.filter(approved=True) return context I've already displayed all the approved comments (as you see), but I don't know how to create a comment form inside that ArticleView. I have this ModelForm: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = '__all__' and... Comment model: class Comment(models.Model): author = models.CharField(max_length=100) article = models.ForeignKey(Article, on_delete=models.CASCADE) email = models.EmailField() message = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) The problem with CommentForm is that I don't know how to 'hide' article and approved fields and how to fill article field with the article got in the ArticleView. I've tried to combine FormMixin with DetailView but.. when I submit the comment form, console displays: Method not Allowed (POST). How can I create a form view into ArticleView? If you didn't get something, please ask me, I know my grammar is bad. I will try to be clear as much as possible. Thanks in advance for answers. -
Fail to Deploy the Django App in the Heroku Cloud
I was trying to deploy a Django app in the Heroku following the official instruction. The project structure is as following, It's good to mention that, I can run heroku locally from the src folder, heroku local web. Also the app create works fine, heroku create. While I tried to deploy the app using the command git push heroku master, I get the error message in the terminal, remote: -----> Failed to detect app matching https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz buildpack remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to sheltered-sea-46201. remote: To https://git.heroku.com/sheltered-sea-46201.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/sheltered-sea-46201.git' What should I need to do to resolve the issue? -
Intersection of two django model?
I have To models and iIwant to find out the common sets of values on the basis of there ids first model:- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # WE ARE AT MODELS/UNIVERSITIES class Universities(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") name = models.CharField(db_column="name", max_length=255, help_text="") abbreviation = models.CharField(db_column="abbreviation", max_length=255, help_text="") address = models.CharField(db_column="address", max_length=255, help_text="") status = models.BooleanField(db_column="status", default=False, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") modifiedAt = models.DateTimeField(db_column='modifiedAt', auto_now=True, help_text="") updatedBy = models.ForeignKey(User,db_column="updatedBy",help_text="Logged in user updated by ......") class Meta: managed = False get_latest_by = 'createdAt' db_table = 'universities' and the other model:- from __future__ import unicode_literals from django.db import models class NewsUniversityMappings(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") newsMappingId = models.IntegerField( db_column='newsMappingId' ,max_length=11, help_text="") universityId = models.IntegerField( db_column='universityId', max_length=11, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") class Meta: managed = False db_table = 'news_university_mappings' now in my views i have created objects for both models:- def add_promoter_news(request, mapping_id=None, news_virtual_id=None): try: university_all_list = Universities.objects.using("cms").all published_university_list = NewsUniversityMappings.objects.using("cms").filter(newsMappingId=news_virtual_id).all() I wanted to finds the common of both the models on the basis of in of universit model and universityId of NewsUniversityMappings.Any help would be appreciated. THanks in advance -
Ajax Requests Slow in Django
I have the following ajax request in my django template: $('#subjects').on('change', function() { var subject = $('#subjects').find(":selected").text(); $.ajax({ type: "GET", url: "/classes/" + term + "/" + subject , // or just url: "/my-url/path/" dataType: "html", success: function(data) { $('#classes').html(data); } }); //remove courses //remove overview //get courses for specified subject //put them under course }); The "subject" id is for a select form like this: <select size="7" class="form-control" id="subjects"> {% for subject in subjects %} <option>{{ subject }}</option> {% endfor %} </select> So, when a subject is changed, I send an ajax request to the server so that I can get the classes for that subject from the database (as there are thousands of classes). However, this takes ~1 second. If a user simply arrows down my list of subjects, then tens of ajax requests will be fired off in a second, causing a backup and slowing down the data being displayed properly. I tried aborting all previous ajax requests before sending another one, but the problem is the server will still process these, so it did not fix the problem. Is there any way to speed this up, and somehow only take 1 second any time a user … -
AJAX not working after deployment
I am facing this problem after putting my website online! The AJAX requests are not being processed at all. I have put a logger in the view function to know whether the view method is being called or not and no, it is not although it gives Success in the front end! When I retry it offline, it works perfectly. The JQuery code: function interactive_search(query) { $.ajax({ url: window.location.href, type: "POST", data: { query: query, csrfmiddlewaretoken: getCookie('csrftoken') }, success: function (json) { receive_neurons(json, true, 'checkbox'); }, error: function (xhr, errmsg, err) { console.log(xhr.status + ": " + xhr.responseText); } }); } The view function @ensure_csrf_cookie def interactive_search(request): log = open('Neurons_search_log.txt', 'a') log.write('Call'+'\n') if request.method == POST: if request.is_ajax(): log.write('Ajax'+'\n') query= request.POST.get('query') retrieved_neurons = search_for_neurons(query); retrieved_neurons_for_ajax = get_neurons_dictionary_for_ajax(retrieved_neurons) return JsonResponse({'neurons': retrieved_neurons_for_ajax}) return render_to_response('neurons_database/pages/interactive_search.html', {}, context_instance=RequestContext(request)) Thank you very much -
Ctype Windows access violation reading 0xBFF3555F
I use Ctype in my Django project but when I use this method : def requete_smartphone(self, bande, debut_a, debut_m, debut_j, fin_a, fin_m, fin_j, sens, fvitesse, fstat, affmes, min, max, moyenne, ecart, algofusion, s_route, vitesse, s_capteurs, s_typeveh, s_marque, s_modele, s_immatriculation, s_pseudo, ecart_moyenne, nombre): """ Permet de faire la requete smarphone avec tout les paramètre qu'elle demande Paramètres : Les même que pour la DLL, suivre ce qui est écrit sur la fiche de la DLL Renvoie """ bande = bande.encode('utf-8') debut_a = int(debut_a) debut_m = int(debut_m) debut_j = int(debut_j) fin_a = int(fin_a) fin_m = int(fin_m) fin_j = int(fin_j) sens = sens.encode('utf-8') fvitesse = fvitesse.encode('utf-8') fstat = fstat.encode('utf-8') affmes = affmes.encode('utf-8') min = min.encode('utf-8') max = max.encode('utf-8') moyenne = moyenne.encode('utf-8') ecart = ecart.encode('utf-8') algofusion = algofusion.encode('utf-8') s_route = s_route.encode('utf-8') vitesse = float(vitesse) s_capteurs = s_capteurs.encode('utf-8') s_typeveh = s_typeveh.encode('utf-8') s_marque = s_marque.encode('utf-8') s_modele = s_modele.encode('utf-8') s_immatriculation = s_immatriculation.encode('utf-8') s_pseudo = s_pseudo.encode('utf-8') ecart_moyenne = float(ecart_moyenne) nombre = nombre.encode('utf-8') DLLFunction = self.libraryBase.requete_smartphone DLLFunction.argtypes = [c_char, c_int, c_int, c_int, c_int, c_int, c_int, c_char, c_char, c_char, c_char, c_char, c_char, c_char, c_char, c_char, c_char_p, c_float, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_float, c_char] DLLFunction.restype = c_bool resultFunction = DLLFunction(bande, debut_a, debut_m, debut_j, fin_a, fin_m, fin_j, sens, fvitesse, fstat, … -
retrieve data from a django model When a users payment is overdue by 2 days
I am trying to retrieve data from my payments model, When a users payment is overdue by 2 days. The below code is what I have already tried . expected_payment_date = datetime.date.today() + datetime.timedelta(+int(2)) users = Payment.objects.filter(expected_payment_date=expected_payment_date) -
PostgreSQL query slow, what's the issue?
I'm trying to store some measurement data into my postgresql db using Python Django. So far all good, i've made a docker container with django, and another one with the postgresql server. However, i am getting close to 2M rows in my measurement table, and queries start to get really slow, while i'm not really sure why, i'm not doing very intense queries. This query SELECT ••• FROM "measurement" WHERE "measurement"."device_id" = 26 ORDER BY "measurement"."measure_timestamp" DESC LIMIT 20 for example takes between 3 and 5 seconds to run, depending on which device i query. I would expect this to run a lot faster, since i'm not doing anything fancy. The measurement table id INTEGER measure_timestamp TIMESTAMP WITH TIMEZONE sensor_height INTEGER device_id INTEGER with indices on id and measure_timestamp. The server doesn't look too busy, even though it's only 512M memory, i have plenty left during queries. I configured the postgresql server with shared_buffers=256MB and work_mem=128MB. The total database is just under 100MB, so it should easily fit. If i run the query in PgAdmin, i'm seeing a lot of Block I/O, so i suspect it has to read from disk, which is obviously slow. Could anyone give me a … -
NotImplementedError: HiddenField.to_representation() must be implemented for field
I have a embedded document field in our django-mongoengine model like this. I am using django rest framework. Models are like this : class ProjectExpertsList: Name = StringField() class Project: Experts = ListField(EmbeddedDocumentField(ProjectExpertsList)) class ExProject: project = ReferenceField('Project') Serializers implemented is like this, where ProjectExpertsSerializer is Embedded Document Serializer. class ProjectSerializer(serializers.DocumentSerializer): preferred_experts = PreferredExpertsSerializer(ProjectExpertsList, many=True) Similarly I have ExProject Document Serializer. I have implemented document serializers for Project & Exproject with depth = 1 . But when i added this field this started throwing error. NotImplementedError: HiddenField.to_representation() must be implemented for field . If you do not need to support write operations you probably want to subclass ReadOnlyField instead. With the help of this link i have added serializers for embedded document. then also it's throwing the above error. -
can't update .po file in Django 1.8.8
I'm new to Django and now I am practicing Django Internationalization, intending to show my webpages in Chinese, however: Whatever changes i've made into the django.po file, and used compilemesseages to generate the .mo file, the pages still returned the previous translations, even if i delete the .po file and to generate a new one. Am I missing something? If so, please tell me, thank you :) This is my settings: LANGUAGE_CODE = 'zh-CN' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ('en', ('English')), ('zh_CN', ('中文简体')), ('zh-hant', ('中文繁體')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) also I've add the 'django.middleware.locale.LocaleMiddleware'into settings.py, just like this: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) what i was test is this function in views.py: def test1_view(request): n = 2 weekdays = [_('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'), _('Friday'), _('Saturday'), _('Sunday')] return HttpResponse(weekdays[n]) the django.po file generated at /locale/zh_CN/LC_MESSAGES/django.po, and i'm sure i had delete the #,fuzzy: #: testdeploy/views.py:64 msgid "Monday" msgstr "一" #: testdeploy/views.py:64 msgid "Tuesday" msgstr "二" #: testdeploy/views.py:64 msgid "Wednesday" msgstr "三" #: testdeploy/views.py:64 msgid "Thursday" msgstr "四" #: testdeploy/views.py:64 msgid "Friday" msgstr "五" #: testdeploy/views.py:64 msgid "Saturday" msgstr "六" #: … -
Can't send task to celery from python with apply_async
I'm using: celery[mongodb]==3.1.23 django-celery==3.1.17 Problem is - sometimes (really often) i can't start tasks from django shell or from my other tasks using apply_async, program just hang on this command. I try run code like: my_task.apply_async( args=[object_id], queue='my_queue') And its just hangs without any result. I cant figure out why can this happened. If i need to provide more detailed data, let me know. i try using strace on process django shell got this log (attaching last lines of it) when calling apply_async: socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP) = 13 connect(13, {sa_family=AF_INET6, sin6_port=htons(27026), inet_pton(AF_INET6, "4a67:6b8:0:f0e:7543:7rh8:a28:gtbc", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, 28) = 0 getsockname(13, {sa_family=AF_INET6, sin6_port=htons(60033), inet_pton(AF_INET6, "2a45:6b8:0:f0e:8034:7gtd:a28:hy6b", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, [28]) = 0 connect(13, {sa_family=AF_UNSPEC, sa_data="\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}, 16) = 0 connect(13, {sa_family=AF_INET, sin_port=htons(27026), sin_addr=inet_addr("86.223.186.12")}, 16) = 0 getsockname(13, {sa_family=AF_INET6, sin6_port=htons(50388), inet_pton(AF_INET6, "::ffff:37.9.91.95", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, [28]) = 0 close(13) = 0 socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP) = 13 setsockopt(13, SOL_TCP, TCP_NODELAY, [1], 4) = 0 fcntl(13, F_GETFL) = 0x2 (flags O_RDWR) fcntl(13, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(13, SOL_SOCKET, SO_KEEPALIVE, [0], 4) = 0 connect(13, {sa_family=AF_INET6, sin6_port=htons(27026), inet_pton(AF_INET6, "2a45:6b8:0:f0e:8034:7gtd:a28:hy6b", &sin6_addr), sin6_flowinfo=0, sin6_scope_id=0}, 28) = -1 EINPROGRESS (Operation now in progress) poll([{fd=13, events=POLLOUT}], 1, 4000) = 1 ([{fd=13, revents=POLLOUT}]) getsockopt(13, SOL_SOCKET, SO_ERROR, [0], [4]) = 0 fcntl(13, F_GETFL) … -
chain filter in django rest framework
I need some guidance on how can I solve the problem I'm having, so I want to display my leads by next_action_date and status order. I don't want to refresh my page so I'm passing date from my datepicker field to the angularjs controller and sending it to restapi where I'm doing this filter, so once again I want to filter by next_action_date and status order, and display them in the table, so can someone help me and show me so I can understand how to properly chain filter this, currently my main problem is that my selected_date = self.request.query_params.get('date', None) is returning None when I debug it, and for the rest of the logic I'm not shure if I'm doing the right thing, so can someone help, thanks. my view in which I'm working on filtering logic: class LeadContactViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user if user.has_perm('cms_sales.can_view_full_lead_contact_list'): queryset = LeadContact.objects.all() elif user.has_perm('cms_sales.can_view_lead_contact'): queryset = LeadContact.objects.filter(account_handler=user) selected_date = self.request.query_params.get('date', None) virgin_data = LeadContact.objects.filter(status=LeadContactConstants.STATUS_PRISTINE) contacted_data = LeadContact.objects.filter(status=LeadContactConstants.STATUS_CONTACTED) qualified_data = LeadContact.objects.filter(status=LeadContactConstants.STATUS_QUALIFIED) client_data = LeadContact.objects.filter(status=LeadContactConstants.STATUS_CLIENT) order_data = list(client_data) + list(qualified_data) + list(contacted_data) + list(virgin_data) if selected_date: queryset = queryset.filter(select_date=selected_date, next_action_date=datetime.datetime.now(), status=order_data) return queryset datefield and controller: app = angular.module 'cms.sales' app.controller … -
Proper Django CSRF validation using fetch post request
I'm trying to use javascript's fetch library to make a form submission to my django application. However no matter what I do it still complains about CSRF validation. The docs on ajax mentions specifying a header which I have tried. I've also tried grabbing the token from the templatetag and adding it to the form data. Neither approach seems to work. Here is the basic code that includes both the form value and the header: let data = new FormData(); data.append('file', file);; data.append('fileName', file.name); // add form input from hidden input elsewhere on the page data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value')); let headers = new Headers(); // add header from cookie const csrftoken = Cookies.get('csrftoken'); headers.append('X-CSRFToken', csrftoken); fetch("/upload/", { method: 'POST', body: data, headers: headers, }) I'm able to get this working with jquery, but wanted to try using fetch. -
How to format Django setting file for flake8
I am kinda obsessed with formating my python code with flake8. However, I cannot find a good way to solve E501 (line too long x > 79 characters) in settings file of Django. First it was like this (4xE501): AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] and then I came up with this: AUTH_PASSWORD_VALIDATORS = [{ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] But still 'NAME':django.contrib.auth.password_validation.UserAttributeSimilarityValidator', is too long. Is there a way to format this or should I ignore this one? -
I used easyui datagrid.When I expand the editor to filebox.I can only get the file path
How can I get the file itself?My backstage is python django. backstage:request.POST['licence'] can only get the path. Code: 供应商名称 联系人 联系人电话 主营业务 公司地址(快递寄送地址) 营业执照 供应商编码 {# 扩展filebox #} $.extend($.fn.datagrid.defaults.editors,{ filebox:{ init:function(container,options){ var input=$("<input name='image'/>").appendTo(container); input.filebox(options); return input; }, getValue:function(target){ console.log(target) console.log($(target).data()) return $(target).filebox("getValue"); }, setValue:function(target,value){ $(target).filebox("setValue",value); }, resize: function (target, width) { var input = $(target); if ($.boxModel == true) { input.resize('resize', width - (input.outerWidth() - input.width())); } else { input.resize('resize', width); } } } }); -
django endless pagination {% load endless %} error
So I'm newly in this. I followed this tutorial and did everything as should but I get this error: TemplateSyntaxError at /match_list/ 'endless' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz In setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'endless_pagination',] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.request', ], }, },] In page_content.html: {% load endless %} {% paginate type %} {% for element in type %} ... {% endfor %} {% show_pages %} Can someone please help? Thanks! -
Handle form submission in bootstrap modal with ajax and class based views
i'm quite new using django and i've been stuck in this problem for several days. I have a form.Form in a bootstrap modal on my template with only 1 field (email_field) and basically i need to submit that form via ajax, check if that email address is registered in the database, then send an invitation to that email and close the modal. if the email is not registered show the form errors without closing the modal. I've tried with different examples but can find the solution either because the examples don't handle errors or the form is not inside a modal or not using class based views . I'm having 2 issues with my code: Not sure what to return in my view if the form is valid or invalid and how to handle errors in my js code to show them on the modal.(return tha form to render the errors or a JSON response??). After the first success submission is made the form cannot be used again.(The size of the submit button changes and if you click it return a error : CSRF token missing or incorrect) Form.py class CollaboratorForm(forms.Form): email_address = forms.EmailField(required=True,widget=forms.TextInput(attrs={'class': 'form-control focus-text-box', 'type': 'email', 'placeholder': 'Enter … -
"Blog App By Django " error: comment_list can't by displayed currectly
There is a blog app by Django 1.9. But when I want to show a comment_list in article.html, there has some trouble. Comment_list can't be displayed in Article Page. Article Page view.py is below: 46 def article(request): 47 try: 48 id = request.GET.get('id', None) 49 try: 50 article = Article.objects.get(pk=id) 51 # 评论表单 52 comment_form = CommentForm({'author': request.user.username, 53 'email': request.user.email, 54 'url': request.user.url, CC 55 'article': id} 56 if request.user.is_authenticated() 57 else {'article': id}) 58 59 comments = Comment.objects.filter(article=article).order_by('id') 60 comment_list = [] 61 for comment in comments: 62 for item in comment_list: 63 if not hasattr(item, 'children_comment'): 64 setattr(item, 'children_comment', []) 65 if comment.pid == item: 66 item.children_comment.append(comment) 67 break 68 if commend.pid is None: 69 comment_list.append(comment) 70 except Article.DoesNotExist: 71 return render(request, 'failure.html', {'reason': '没有对应的文章'}) 72 except Exception as e: 73 print e 74 logger.error(e) 75 return render(request, 'article.html', locals()) 76 html is here: <ol class="commentlist"> {% for comment in comment_list %} <li id="comment-59418"> <div class="top"><a href='{{ comment.url }}' rel='external nofollow' class='url'>{{ comment.username }}</a><span class="time"> @ <a href="#comment-59418" title="">{{ comment.date_publish | date:'Y-m-d H:i:s' }}</a></span></div> <div><img alt='' src='{% static 'images/default.jpg' %}' class='avatar avatar-32 photo' height='32' width='32' /></div> <div class="body"> <p>{{ comment.content | safe }}</p> </div> </li> {% for … -
Import a class into the urls.py in Django
In the last few weeks I've switched from developing an application that processes a simple XML file, then writes its contents to an Oracle DB (cx_Oracle) and outputs in HTML, to using a Django framework. The Django framework switch wasn't necessary, but since I have an opportunity to develop something by using Django, I thought why not as it is a new area for me and can't damage my CV. Anyway, I'm having issues with knowing what to write in my urls.py file when importing a Class from the views.py file. Here are the current contents: urls.py from myproj.views import Pymat_program pymatProgram = Pymat_program() urlpatterns = ( url(r'^pymat/$', pymatProgram.abc), ) views.py class Pymat_program: def abc(self, request): test = "<html><body>Random text.</body></html>" return HttpResponse(test) I've tried various permutations of using request, not using request, and also how the class is called in the url tuple, all to no avail. When I use a definition outside of the class (i.e. not in any class), then this is correctly displayed in HTML. -
Why do I get a ModuleNotFoundError when switching my Django project to Python 3.6?
I use to run Python 2 and had a fully working Django application. I have now decided to switch to Python 3 and went with 3.6. When I try to run my tests I now get the following stack trace: Traceback (most recent call last): File "/Users/jonathan/Work/GenettaSoft/modeling-web/modeling/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/core/management/__init__.py", line 324, in execute django.setup() File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 22, in ready self.module.autodiscover() File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/Users/jonathan/anaconda/lib/python3.6/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/Users/jonathan/anaconda/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/jonathan/Work/GenettaSoft/modeling-web/modeling/licenses/admin.py", line 2, in <module> from models import LicenseModel ModuleNotFoundError: No module named 'models' Some googling first led me to http://www.daveoncode.com/2017/03/07/how-to-solve-python-modulenotfound-no-module-named-import-error/ but I don't think any of those situations apply --- after all, it was running fine in Python 2. Next I … -
Want to draw data using chartjs in django
My view is: def get_temperature_show(request): all_temperatures = Temper.objects.all() dates_label = [] sensor1_temp = [] sensor2_temp = [] sensor3_temp = [] sensor4_temp = [] for model in all_temperatures: dates_label.append(model.date) sensor1_temp.append(model.sensor1_temp) sensor2_temp.append(model.sensor2_temp) sensor3_temp.append(model.sensor3_temp) sensor4_temp.append(model.sensor4_temp) data = { 'dates': dates_label, 'sensor1': sensor1_temp, 'sensor2': sensor2_temp, 'sensor3': sensor3_temp, 'sensor4': sensor4_temp } return render(request, 'weather/showtemper.html', json.dumps({"data":data})) But it shows an error datetime.date(2017, 4, 4) is not JSON serializable My template example is like this: var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'], datasets: [{ label: 'apples', data: [12, 19, 3, 17, 6, 3, 7], backgroundColor: "rgba(153,255,51,0.4)" }, { label: 'oranges', data: [2, 29, 5, 5, 2, 3, 10], backgroundColor: "rgba(255,153,0,0.4)" }] } }); -
Multiple File Uplaod in django
I am using Django Rest Framework to upload a file. I want to upload multiple image files to a folder. My view file looks like this. How to give path to the image folder and save images in that folder. And Image Uploading not working properly @api_view(['PUT']) @permission_classes(()) def file_upload(request): parser_classes = (FileUploadParser,) def put(self, request, filename, format=None): file_obj = request.data['file'] return Response({'upload': 'success'}) -
Open bootstrap modal from other modal
I use bootstrap 4 and AJAX in my project. In page with 2 models. Inside first modal (id='#modal-lg') I have button which must to open second modal (id='#modal'). When I click that button it didnt open second modal. It just close first modal. How to fix this problem? Where I did mistake? template.html: {# FIRST MODAL #} <div class="modal fade" id="modal-lg"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-body"> <button id="requirement-add-button" data-url="{% url 'project:requirement_add' %}"> {% trans 'Add New Requirement' %} </button> </div> </div> </div> </div> {# FIRST MODAL #} {# SECOND MODAL #} <div class="modal fade" id="modal"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> </div> {# SECOND MODAL #} js: $(function () { var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal").modal("show"); }, success: function (data) { $("#modal .modal-content").html(data.html_requirement_form); } }); }; var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#requirement-table tbody").html(data.html_requirement); $("#modal").modal("hide"); } else { $("#modal .modal-content").html(data.html_requirement_form); } } }); return false; }; // CREATE $("#requirement-add-button").click(loadForm); $("#modal").on("submit", ".js-requirement-add-form", saveForm); });