Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Errors not showing on page, connection timeout error thrown after a while
I'm having this issue that suddenly appeared with no obvious reasons. Initially, the errors and exceptions were being displayed both on the page and the console. However, whenever I get or reproduce any kind of error and refresh the page to see the results, the page loads for too long and nothing appear in the python server console. After few minutes, I get this error on the page A server error occurred. Please contact the administrator. And this in the console: Django version 1.7.1, using settings 'snb_mail.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 64, in __call__ return self.application(environ, start_response) File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__ response = self.get_response(request) File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 199, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 231, in handle_uncaught_exception 'request': request File "/usr/lib/python2.7/logging/__init__.py", line 1193, in error self._log(ERROR, msg, args, **kwargs) File "/usr/lib/python2.7/logging/__init__.py", line 1286, in _log self.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 1296, in handle self.callHandlers(record) File "/usr/lib/python2.7/logging/__init__.py", line 1336, in callHandlers hdlr.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 759, in handle self.emit(record) File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/utils/log.py", line 132, in emit connection=self.connection()) File "/home/hamza/envsite/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 98, in mail_admins β¦ -
Django - What is the best way to have multi level status before login
I have one scenario, there is a user registration and it should have multiple status(may be is_active - but this is boolean by default) List item Code - 0 -> Pending for Email Confirmation List item Code - 1 -> Account Activated/Active(Only after email confirmed admin will approve it) List item Code - 2 -> Email Confirmed I am using django allauth, I was browsing to achieve it, but unable to find some close match of it. For your info I also have Profile OnetoOne model for User model -
Django: Is CBV or FBV is better?
I am developing a project from scratch. How can I determine is the project should use CBV or FBV. Is it a best practice to use the mix of these inside a views.py? -
integrate OpebCV python with web app(HTML and Javascript) for face-detection
I am using OpenCV library for Face-detection with Python. I am using Django as my server. And I am sending images for face-detection via curl. Actually I followed this tutorial. I want to integrate OpenCV with my HTML page so that I can detect faces directly from my web app. I want some tutorial or examples to do that. But I am preferring Python for server-side and Javascript for client-side. Any kind of technic or example will be helpful. Thank you. -
Solr-Thumbnail not Rendering Thumbnails
I'm trying to implement solr-thumbnail on a django form, but whenever I choose an image it does not render the thumbnail on my form. Here is the code: Models.py from sorl.thumbnail import ImageField class user(models.Model): first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) image = ImageField(upload_to='whatever', blank=True, null=True) Forms.py class AdminImageWidget(AdminFileWidget): def render(self, name, value, attrs=None): output = [] if value and getattr(value, "url", None): t = get_thumbnail(value,'80x80') output.append('<img src="{}">'.format(t.url)) output.append(super(AdminFileWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) class UserDataForm(forms.ModelForm): class Meta: model = user fields = '__all__' widgets = { 'image': AdminImageWidget} Template.html <form method="post"> {{ formUser.as_p }} <input type="submit" value="Submit" /> </form> -
How do i configure django urls to make it so if it displays 404, it reroutes to Reactjs
The title is terrible - sorry about that. So say I have a website say www.myhairynose.com/. I've configured my urls.py so that whenever the person enters www.myhairynose.com it redirects them to the index.html (where it displays the reactjs application). I've set reactjs with react-router and made it so when you click a button on the index page it goes to www.myhairynose.com/#/webpage. Thing is... I don't want that. I want it to go to www.myhairnose.com/webpage. I want react to handle this however and not django. ALL of this url thing should be in the same application of index.html. How do I configure django urls.py so that if I enter www.myhairynose.com/webpage it goes to the index of www.myhairnose.com ReactJs's application and then it checks to see if the route has webpage. Otherwise say if I went to www.myhairynose.com/asdkjaskldsaj (which the react route doesn't have) it should display a 404. ______TLDR______ Basically what I want to happen: User goes to website.com/name >if website.com/name exists in django - it returns a html doc >if not then it redirects to website.com/ where ReactJs will handle the url and see if it matches any of the routers ...> if it does, then it displays that route β¦ -
django logging configuration not working as it should
I have project with (Django=1.9.7) and celery, the project structure is as such myproject -- manage.py -- myproject -- config -- config.py -- logging_config.py -- celery_config.py -- settings.py -- app_1 -- models.py -- tasks.py -- views.py -- app_N -- models.py -- tasks.py -- views.py Here is my logging_config.py Note : LOGGING_LEVEL = 'DEBUG' The logging config work perfectly in local server.. all the logs gets set to the respective file, but on PROD it fails.. only django logger works but rest of the loggers don't print to the respective file Can anyone help.. as I am not able to pin point what i am doing wrong? -
Django django.test django.db.models.fields.related_descriptors.ManyRelatedManager
Please assert type: 'django.db.models.fields.related_descriptors.ManyRelatedManager'. In other words, how to import the module in order to assert that the field 'user.groups' is of type 'django.db.models.fields.related_descriptors.ManyRelatedManager'? from django.db.models.fields import related_descriptors # AttributeError: 'module' object has no attribute 'ManyRelatedManager' self.assertIsInstance(user.groups, related_descriptors.ManyRelatedManager) print(type(dummy_user.groups)) # <class 'django.db.models.fields.related_descriptors.ManyRelatedManager'> Here's the error: AttributeError: 'module' object has no attribute 'ManyRelatedManager Thanks -
Character escaping in templates
The good explanation of the roots of this problem Apparently, there is no obvious way to use some special characters in the Django template URLs. For example # always gets converted into %23. The thing is, I want to use HTML5 video tag to play videos, and the way to control start and end time of the clip is to append #t=[start,end] at the end of the scr argument. For example : <video><source src = "/static/video.mp4#t=5,10"> </source></video> wont work if # gets translated into %23. As I understand, there is no clean general solution for this problem, but may be there is a workaround specific to my situation? Thank you. -
Heroku Django Migrate Not Working
I am in my way learning python with django, and when I tried to sync with Heroku, there's an error showing I haven't migrated them yet. I am pretty sure have done it, but the console still saying so. Iam sure I left an obvious part. But still can't find which one. This image reflected exactly what I am talking about -
django - How to customise Model save method when a specified field is changed
I have a model, let's save A, the definition is as below: class A(models.Model): name = models.CharField('name', max_length=10) enabled = models.BooleanField('enabled', default=False) field1 = models.CharField('field1', max_length=10) field2 = models.CharField('field2', max_length=10) field3 = models.CharField('field3', max_length=10) parent = models.ForeignKey('self', null=True, blank=True) # hierarchy and some object instances of this model, a, b, c, d. the hierarchy is represented by the parent field. a |-- b |-- c |-- d So, what I need to do is, when b.enabled change from False to True, or vice versa, I need to update c.enabled and d.enabled to value: b.enabled. That's say, I need to broadcast the change to the children instances when the parent's enabled field was changed. For performance consideration, I only need to broadcast the changes when enabled field is really changed. And don't want to always update the child instance whenever the parent is save, e.g. only updating field1 or field2. So, do anyone knows, what is the best way to implement this logic? Thanks in advance. -
clear dropdown values before form submit
I tried lot of posts but none seem to work for me. I have 2 drop downs inside same form element and they should work in toggle manner, with following properties: selecting any drop down should clear the other one and auto submit the form. Also on form submit I am retaining the value of selecting drop down to display user what value had been selected. For auto submit I have used .change and fformid.submit. But issue is if i selected dropdown 1, form get submitted and page is displayed with dropdown1_value 1 selected and now when i make selection of 2nd drop down, both fdropdown 1 and dropdown 2 value gets submitted. I tried using dropdown2_id.remove(), .emtpy(). .val(""). All these seem to visually remove elements, but form gets submitted with the value previously selected. And i dont want to use Ajax, since I am using Django, doing Ajax will return result to js which is difficult for me to render than using html itself. -
Django Allauth and urls
I have a dev environment for a test of Django. I am running Python 3.5.2 out of a "local" pyenv install. I have Django 1.10.2. I discovered the allauth registration plugin yesterday and have been playing with it but have hit a snag. My site is "dev.my.domain.com". The intent is that there will not be any "public" information on the production version of this site. The production version will be called something like: "members.my.domain.com". So, I wonder if it is possible for the "allauth" plugin to have all non-/adomn inbound requests check for auth? So, requests to: dev.my.domain.com dev.my.domain.com/foo dev.my.domain.com/foo/../bar/... should all be checked for auth. If not there then I assume "allauth" will redirect to a login/signup page. I have tried setting the Members/urls.py file as: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^$', include('allauth.urls')), url(r'^admin/', admin.site.urls), ] but that bombs with a Page Not Found error and the DEBUG message: Using the URLconf defined in Members.urls, Django tried these URL patterns, in this order: ^$ ^ ^signup/$ [name='account_signup'] ^$ ^ ^login/$ [name='account_login'] ^$ ^ ^logout/$ [name='account_logout'] ^$ ^ ^password/change/$ [name='account_change_password'] ^$ ^ ^password/set/$ [name='account_set_password'] ^$ ^ ^inactive/$ [name='account_inactive'] ^$ ^ ^email/$ [name='account_email'] ^$ β¦ -
WebDev/Design Using the appropriate tools (when?) [on hold]
Im currently learning html,css,javascript and ive been using boostrap. My uncle has a small construction business and has asked me if i could build the site. So here is my question since the site would have 4 pages and have a huge gallery of pictures maybe over 100(i still dont know how imma do this lol..). My question is i know boostrap is used for static websites (right? im a noob sorry), so when would it be appropriate to say hey i should build this using ruby , php, python. Since im trying to upload all those photos would it be better to use a language mentioned above. Would those languages only be utilized if the website is used for e-commerce, having his clients login to see their estimates, etc. -
Django REST Custom View Parameters in Viewset with CoreAPI
If I define a django-rest-framework view framework as: class ProblemViewSet(viewsets.ModelViewSet): queryset = Problem.objects.all() serializer_class = ProblemSerializer @detail_route(methods=['post'], permission_classes=(permissions.IsAuthenticated,)) def submit(self, request, *args, **kwargs): # my code here return Response(...) When I look at the CoreAPI schema that is defined, I find this: problems: { create(title, text, value, category, hint) destroy(pk) list([page]) partial_update(pk, [title], [text], [value], [category], [hint]) retrieve(pk) submit(pk) update(pk, title, text, value, category, hint) } I'd like the submit API endpoint to take an additional parameter, called answer, but so far I haven't figured out how to add such a custom parameter. I know I can just pass in the POST array, but that seems inelegant and un-RESTful. Any ideas? -
How to get Character Value from an Integer database field
I have an integer field in db, which is option field. I'm saving the options in terms of id in to the db, but I also have to display the value in that field pertaining to certain operations. Can anyone here please tell me how to get a text value from an int field and display it? Below is my code: Html: <th col width="55%"><label><strong>Risk Estimation</strong></label> <select ng-model="arform.risk_estimate" ng-options="item for item in risk_estimate"> <option style="display:none" value=" risk_estimate.text"></option> </select> </th> Controller: {{ngapp}}.controller( "SiVerifyAddReviewController", function($scope, $http, $modalInstance, r_header){ $scope.risk_estimate = ['High','Medium', 'Low'];}; Will be able to provide if further part of code is required for understanding. Thanks. -
Where should I place the login and logout in Django?
I am beginner using Django. I was wondering what is the best practice to place the user login and logout. I already have a global static folder and templates. Should I create a view.py under my Project-Root folder for the functions?? or should I create a separate APP just con handle this events ?? Thanks in Advance. projectname]/ <- project root βββ [projectname]/ <- Django root β βββ __init__.py β βββ settings/ β βββ urls.py β βββ wsgi.py βββ apps/ β βββ __init__.py β βββ manage.py β βββ static/ β βββ GLOBAL STATIC FILES βββ templates/ βββ GLOBAL TEMPLATES -
NoReverseMatch Error using Haystack + Elasticsearch
Caught an NoReverseMatch exception while rendering a page returned by a search. I am using Python 3.5.2, Django 1.10.2, Haystack 2.5.0 and Elasticsearch 1.7.5. This is the views.py: def show_posts_by_author(request, author_id): all_categories = Category.objects.all() author = Author.objects.get(pk = author_id) posts_list = Post.objects.filter(author = author, status = 'Published').order_by('-created_at') paginator = Paginator(posts_list, 3) # Show 3 posts per page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. posts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. posts = paginator.page(paginator.num_pages) context ={ 'posts': posts, 'categories': all_categories, 'author': author, } return render(request, 'blog/home.html', context) def posts_search(request): all_categories = Category.objects.all() form = PostsSearchForm(request.GET) posts = form.search() msg = "I enter on the right view" context = { 'categories': all_categories, 'posts': posts, 'msg': msg, } return render_to_response('blog/home.html', context) This is the urls.py urlpatterns = [ url(r'^$', views.home, name='blog.home'), url(r'category/(?P<category_id>\d+)/$', views.show_posts_by_category, name='blog.posts_by_category'), url(r'author/(?P<author_id>\d+)/$', views.show_posts_by_author, name='blog.posts_by_author'), url(r'post/(?P<post_id>\d+)/$', views.show_post, name='blog.post'), url(r'^search/$', views.posts_search, name='blog.search.posts'), ] This is the home.html: {% extends "blog/layout.html" %} {% block content %} <section> {% for post in posts %} <article> <h2> <a href="#">{{ post.name }}</a> </h2> <p class="lead"> by <a href="{% url 'blog.posts_by_author' post.author.pk β¦ -
Converter file service on ubuntu server
I'm using python/django on ubuntu server and exporting PDF's There's a way to use a service to converte those PDF's to MS Word files? Or maybe HTML to PDF/DOC/DOCX The point is avoid making 3 different programs when I can use a converter. Thanks -
Django 1.9: constrain model fields such that both cannot be 'True'
class Foo(models.Model): bar = models.BooleanField(default=False) baz = models.BooleanField(default=False) How can I constrain this model such that bar and baz cannot both be True? -
Sending emails with django/AWS-SES and handling bounces
I am trying to send emails via AWS-SES from a django app. In the settings.py I define: DEFAULT_FROM_EMAIL = "Site <no-reply@site.com>" This is then used when message is sent: from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): def handle_noargs(self, **options): subject = "Some subject" from_email = settings.DEFAULT_FROM_EMAIL email = "Test <test@site.com>" msg = EmailMultiAlternatives(subject, from_email=from_email, to=email) msg.send() Now, AWS-SES forwards bounced emails to no-reply@site.com. Is there a way of setting this up so that from_email field remains no-reply@site.com, but that bounces go to e.g. bounces@site.com? Does someone know how to define the return path? -
server 500 error python
I'm developing a python app using Djgango and I'm getting the server 500 error. I believe my paths are set correctly, the python manage.py runserver returns that the server is running. When I look at developer tools on the page it says "Failed to load resource: the server responded with a status of 404 (not found) http://localhost:64915/favicon.co" and "failed to load resource: the server responded with a status of 500 (internal server error) http://localhost:64915/." I don't know what is going on? I'm new to Django coming from asp.net which runs without all the go around. can you help me? Here is my wsgi.py file code. """ WSGI config for SmartShopper project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. β¦ -
Django send email with gmail SMTP only works on localhost (fail on DigitalOcean)
I'm using Django allauth to manage the my user registration. When the user create an email account, he receive a confirmation email. He cannot login to the site if the email is not confirmed. All work well on localhost (the email is sent, the confirmation works, and if the user try to connect before having confirmed the email, the connection fails with the appropriate error message). But the problem comes when I try my app on my digitalocean server. The mail is not sent and the user can connect even if the email is not confirmed. My Django email settings are: EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'your-username@gmail.com' EMAIL_HOST_PASSWORD = 'your-password' EMAIL_PORT = 587 EMAIL_USE_TLS = True Where does the problem comes from? I think it's something with my digitalocean server but I'm not sure at all. -
Methods for cloning a remote database to a local Django MySql database periodically
I'm currently building a webapp that supplies kiosks with up-to-the-minute information. All queries are SELECT only and my user for the remote database has read-only permissions. I have created some models in Django which allow me to access the data via the ORM. My issue is that the information requested by each kiosk must be retrieved via Django which accesses the source db remotely through a VPN for each update. However this can be slow! Even for small queries it can take from 5 to 30 seconds before I see a response - and if each kiosk does this for each update it surly can't be good. So I was hoping to create a clone that stores all of the relevant information and is scheduled to copy over only once per minute. Then have the kiosks pull from the local db instance instead. I have been looking into using Celery beat to accomplish this though I have never used it. However what I'm not certain of is a good approach to create the clone (aka copying one model to another)? I'll try to elaborate: In the past I have used Python and MySqlDb with Linux Cron to periodically run a β¦ -
How to make REMOTE_USER private for the logged user in WSGI?
I have developed a custom OAuth2 middleware in Python which sets the REMOTE_USER variable for the logged user, however I'm unable to make this variable private for visitors of the site. https://bitbucket.org/tkadm30/django-hotsauce/src/fe96dc13edf65003e9453150a6fcd7059ab85461/lib/notmm/controllers/wsgi.pyx?at=default&fileviewer=file-view-default In my main WSGI middleware (BaseController.init_request), I create the WSGI request object using the following code: try: _locals.environ = _locals.request.environ except AttributeError: _locals.environ.update(environ) request = request_class(_locals.environ) if request.environ != _locals.environ: self.logger.debug("Updating environment") request.environ.update(_locals.environ) return request Note: _locals is a threading.local object. The same code with gevent.local doesn't work.