Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
difference between authentication and perimssion in django rest-frammework
What is the difference between authentication and perimssion in django rest-frammework? How does this two classes copperate each other? -
django save websocket to redis without closing it
Is there a way to keep websocket open using redis for future use ? I need my django server to communicate with a websocket backend service on behalf of the client. It means that I need to save the websocket open between multiple http requests of the client. can I use redis for this purpose or is there any other way to do so ? Thanks. -
Django 1.10.6 Limiting Querysets to return lastly entered records?
Refer - https://docs.djangoproject.com/en/1.10/topics/db/queries/#limiting-querysets I searched SO dont find the required info. Need to retrieve only 5 lastly entered records , within a Querset.. Documentation linked here - Refer - https://docs.djangoproject.com/en/1.10/topics/db/queries/#limiting-querysets shows how to retrieve the earliest entered records . -
Customize Django poll admin functionality
I would like to customize the admin poll functionality in Django. Is it possible to override or add to existing functionality of admin site? For example in the screenshot shown, I would like to add different functionality than what it automatically does when I click on "SAVE". I am new to Django and html, a brief procedure is greatly appreciated. -
unable to create a new project in django got error. Fatal error in launcher: Unable to create process using '"'
unable to create a new project in django got error. it display error django-admin startproject someproject Fatal error in launcher: Unable to create process using '"' i have django version 1.10.6 an python27 installed. -
django model required positional argument: 'instance'
I want add is_end field in Event model def get_is_end(instance): if instance.created_at > instance.deadline_at: return True return False class Event(models.Model): title = models.CharField( max_length=50, ) created_at = models.DateTimeField( auto_now_add=True, ) deadline_at = models.DateTimeField( default=datetime.now()+timedelta(days=30), ) is_end = models.BooleanField( default=get_is_end, ) when I makemigrations, migrate and login admin page and add Event post get_is_end() missing 1 required positional argument: 'instance' I think get_is_end method need self argument So I add default=get_is_end => default=get_is_end(self), and makemigrations, migrate name 'self' is not defined how can I settings is_end field? -
Django: When to run run makemigrations?
In addition to adding/deleting/modifying field to model, Django also detects changes when I add or modify methods to the model. So my question is should I run makemigrations every time I change or add a new method in models ? -
How to convert a plain text password to sha1 django
I am trying to allow users to update there password, currently when I store the updated password in the database in looks like this. I am allowing users to update there own password, how do I get the current hash to the django default sha1 hash. password = hashlib.sha1(password).hexdigest() output be86dd8176c748e5a5676f3c7c32eeafe62ed764 expected output pbkdf2_sha256$30000$6nrsbWJ7QoNg$Clt2K2iaucZJnm5Bx+h+H/Q5Tc/v08BB7qp4dZpZ/p8= -
Django istartswith to match separate words within phrase
This post is exactly what I am looking for. But I wasn't able to achieve the goal using the info provided in the answer. I'll illustrate my goal by an example. For example, I have three strings: John Smith Lee, John Micheal Bolton I am looking for a Django filter that would select first(John Smith) and second(Lee, John) strings, and exclude (filter out) the last one. My code now looks like this: if 'search_text' in request.POST: text = request.POST['search_text'] text = re.escape(text) qs = qs.filter(name__iregex=r"(^|\s)%s" % text) Any ideas? -
django-recommend not running the crontab
I have set the RECOMMENDS_TASK_CRONTAB = {'minute': '*/1'} in the setting , so this should repeat this every 1 minute. And its not working, Any one who have used this package https://djangopackages.org/packages/p/django-recommends/ could tell me what im doing wrong This is my Models # models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Product(models.Model): """A generic Product""" name = models.CharField(blank=True, max_length=100) sites = models.ManyToManyField(Site) def __str__(self): return self.name @models.permalink def get_absolute_url(self): return ('product_detail', [self.id]) def sites_str(self): return ', '.join([s.name for s in self.sites.all()]) sites_str.short_description = 'sites' @python_2_unicode_compatible class Vote(models.Model): """A Vote on a Product""" user = models.ForeignKey(User, related_name='votes') product = models.ForeignKey(Product) site = models.ForeignKey(Site) score = models.FloatField() def __str__(self): return "Vote" This is my recommendations.py # recommendations.py from django.contrib.auth.models import User from recommends.providers import RecommendationProvider from recommends.providers import recommendation_registry from .models import Product, Vote class ProductRecommendationProvider(RecommendationProvider): def get_users(self): return User.objects.filter(is_active=True, votes__isnull=False).distinct() def get_items(self): return Product.objects.all() def get_ratings(self, obj): return Vote.objects.filter(product=obj) def get_rating_score(self, rating): return rating.score def get_rating_site(self, rating): return rating.site def get_rating_user(self, rating): return rating.user def get_rating_item(self, rating): return rating.product recommendation_registry.register(Vote, [Product], ProductRecommendationProvider) This is settings.py """ Django settings for smartTutor project. Generated by 'django-admin startproject' … -
Celery with Supervisord
Image task1 and task2 are not getting called isolated.if I called task2 celery runs task1 location of task1 :- project1/app1/task1.py location of task2 :- project2/app2/task2.py -
Importing modules in Angular 2 with Django
I have some trouble importing a module in an Angular 2 app served using Django. I've been working on combining Angular 2 and Django, loosely following this page: https://4sw.in/blog/2016/django-angular2-tutorial/. In settings.py of Django I added ANGULAR_URL = '/ng/' ANGULAR_ROOT = os.path.join(BASE_DIR, 'ngApp/src') and I add a line baseURL: '/ng/', to systemjs.config.js. After changing the index.html to this: {% load static %} <html> <head> <title>Angular 2 QuickStart</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <base href="/"> <!-- Polyfill(s) for older browsers --> <script src="{{ ANGULAR_URL }}node_modules/core-js/client/shim.min.js"></script> <script src="{{ ANGULAR_URL }}node_modules/zone.js/dist/zone.js"></script> <script src="{{ ANGULAR_URL }}node_modules/systemjs/dist/system.src.js"></script> <script src="{{ ANGULAR_URL }}systemjs.config.js"></script> {# Write your django logics here #} <script> window.ANGULAR_URL = "{{ ANGULAR_URL }}"; System.import('/ng/main.js').catch(function(err){ console.error(err); }); </script> </head> <body> <my-app>Loading...</my-app> </body> </html> when I go to localhost:8000, my app loads well. However, when I load an extra module (Google Maps for Angular 2) by adding: 'angular2-google-maps': 'npm:angular2-google-maps/core/', to map{} in systemjs.config.js and import { AgmCoreModule } from 'angular2-google-maps'; in app.module.ts, npm start produces an error src/app/app.module.ts(7,31): error TS2307: Cannot find module 'angular2-google-maps'. even though it's installed and in the folder node_modules. My folders look as follows: /DjangoProject - settings.py - /ngApp -- /src --- systemjs.config.js --- /node_modules ---- … -
Separate access levels for different apps in Django
I have 4 apps in my Django project. I want to create a login for each of them. But a user signed up for app1 shouldn't be able to access the pages of app2. If I give this user the access to app1 models only from django admin, he won't be able to affect the app2 models but will he still be able to view the pages created in app2? I just want to display a permission denied message if such a user tries to login to app2. How can I achieve this? -
django <model>.objects manager shows undefined variable from export in pydev + eclipse
In a django model the objects manager is auto created. However you can also manually specify an objects manager. It appears that adding a objects manager to the model class confuses pydev and all class methods on the manager appear as undefined variables from import Model.objects.all() However it works for inherited model managers -
Calling super method in Django TestCase causes RecursionError
According to Django's document: Warning SimpleTestCase and its subclasses (e.g. TestCase, ...) rely on setUpClass() and tearDownClass() to perform some class-wide initialization (e.g. overriding settings). If you need to override those methods, don’t forget to call the super implementation: class MyTestCase(TestCase): @classmethod def setUpClass(cls): super(MyTestCase, cls).setUpClass() ... @classmethod def tearDownClass(cls): ... super(MyTestCase, cls).tearDownClass() ...... I decided to follow this practice when writing tests: class AuthorListViewTest(TestCase): @classmethod def setUpTestData(cls): number_of_authors = 13 for author_num in range(number_of_authors): Author.objects.create(first_name='Christian %s' % author_num, last_name='Surname %s' % author_num,) super(AuthorListViewTest, cls).setUpTestData() # testing functions But I get an RecursionError when running tests: <hundreds of identical lines omitted> File "/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/test/testcases.py", line 1025, in setUpClass cls.setUpTestData() File "/Users/sunqingyao/Documents/Projects/locallibrary/catalog/tests/test_models.py", line 10, in setUpTestData super(AuthorModelTest, cls).setUpClass() File "/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/test/testcases.py", line 1025, in setUpClass cls.setUpTestData() File "/Users/sunqingyao/Documents/Projects/locallibrary/catalog/tests/test_models.py", line 10, in setUpTestData super(AuthorModelTest, cls).setUpClass() File "/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/test/testcases.py", line 1025, in setUpClass cls.setUpTestData() File "/Users/sunqingyao/Documents/Projects/locallibrary/catalog/tests/test_models.py", line 10, in setUpTestData super(AuthorModelTest, cls).setUpClass() File "/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/test/testcases.py", line 1025, in setUpClass cls.setUpTestData() File "/Users/sunqingyao/Documents/Projects/locallibrary/catalog/tests/test_models.py", line 10, in setUpTestData super(AuthorModelTest, cls).setUpClass() File "/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/test/testcases.py", line 1025, in setUpClass cls.setUpTestData() File "/Users/sunqingyao/Documents/Projects/locallibrary/catalog/tests/test_models.py", line 10, in setUpTestData super(AuthorModelTest, cls).setUpClass() File "/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/test/testcases.py", line 1025, in setUpClass cls.setUpTestData() File "/Users/sunqingyao/Documents/Projects/locallibrary/catalog/tests/test_models.py", line 10, in setUpTestData super(AuthorModelTest, cls).setUpClass() File "/Users/sunqingyao/Envs/django_test/lib/python3.6/site-packages/django/test/testcases.py", line 1025, in setUpClass cls.setUpTestData() File "/Users/sunqingyao/Documents/Projects/locallibrary/catalog/tests/test_models.py", … -
I am trying to send user an email using Django but redirected to a blank page
For the above stated problem I am using a form so that as soon as there is a click email is sent to user models.py from django import forms class Notification(forms.Form): email = forms.EmailField() message = forms.CharField() This is views.py from django.shortcuts import render from django.conf import settings from django.core.mail import send_mail from .models import Notification def notification(request): form = Notification(request.POST or None) if form.is_valid(): message = form.cleaned_data["message"] email = form.cleaned_data["email"] subject = 'Order Status at Table' from_email = settings.EMAIL_HOST_USER to_email = [email,] contact_message = "%s"%( message) send_mail(subject, contact_message, from_email, to_email, fail_silently=True) context = { "email": email, "message": message } return render(request, "send.html", context) send.html <form name="notification" method='POST' action= "">{% csrf_token %} <select name="message"> <option value="5 min">5 min</option> <option value="10 min">10 min</option> <option value="15 min">15 min</option> <option value="20 min">20 min</option> </select> <select name="email"> <option value="example@example.com">example@example.com</option> </select> <br><br> <input type="submit"> </form> As soon as I click the submit button I am redirected to a blank screen(and email is not sent) In the console I can see the message and the user email passing but email is not sent In my settings I have configured the mail and its working -
Django and Firebase - how does it work together for authentication?
I find Firebase very good for authentication. but how can it be use along with Django. Should I redesign my Django registration and login system from scratch! Since I'm using postgresql. All together I find that I would be using analytics and storage as well, is it possible to use all Firebase features for my Django project? Are there any online resources? Apart from the Firebase docs? More specific to Django or python. -
Django selenium TypeError: assertIn() missing 1 required positional argument: 'container'
I am trying to do testing with selenium and django StaticLiveServerTestCase driver = webdriver.Firefox() driver.get('%s%s' % (cls.live_server_url, reverse("home:index"))) self.assertIn("Hello", self.driver.title) It shows error. TypeError: assertIn() missing 1 required positional argument: 'container' -
Django 404 Page not loading
I have made a simple django application for creating my custom 404 page. I have created 404.html and 500.html in my page,According to Django Documentation.Then I tried two methods to render the 404 Error message. 1)I made simple 404.html and 500.html page and did nothing then. I was successful in getting the 500 page. Correct url to the page was:localhost:8000/book And I supplied localhost:8000/book/fgfg And there was no entry according to the input.But it was sending me to the 500 page but not to the 404 page as I expected. This is Internal App's Urls.py: from django.conf.urls import url from django.conf.urls import ( handler400, handler403, handler404, handler500 ) from bookform import views from . import views urlpatterns = [ url(r'^$', views.index, name='index'),] And this is External Project's urls.py: from django.conf.urls import url,include,handler404,handler500 from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^book/', include('bookform.urls')), ] # handler404='bookform.views.handler404' # handler500='bookform.views.handler500' I have commented the handler404 and 500 here which I uncommented in 2nd method. In first method I did nothing except adding the 404 and 500 html files and Django tried to find out the url and resulted in 500 error but I was expecting it to be 404 error. It showed … -
Python2.7 __init__.py error - ValueError: Empty module name
I am new to Django python framework and as a beginner, I am going through the documentation of Django from the official website. But at Part-2, When I run the makemigration command I get this error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/shivams334/venv1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/shivams334/venv1/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/shivams334/venv1/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/shivams334/venv1/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/shivams334/venv1/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ValueError: Empty module name I also tried to locate the /usr/lib/python2.7/importlib/init.py file, here it is: """Backport of importlib.import_module from 3.x.""" # While not critical (and in no way guaranteed!), it would be nice to keep this # code compatible with Python 2.3. import sys def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError("attempted relative import beyond top-level " "package") return "%s.%s" % (package[:dot], name) def import_module(name, package=None): """Import a module. The … -
Django not working on windows 10
I am trying to run django on windows 10. I installed virtual environment using: python -m pip install virtualenvwrapper-win then I entered the virtual environment: mkvirtualenv project Then I installed django using pip: python -m pip install django Everything went fine and i got a message that django was installed succesfully. After that I ran: django-admin startproject mysite cd mysite Up to this point everything was going fine but then when I tried to start it using: python manage.py runserver I got an error saying: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Does anyone have experience with this error and if yes does anyone know how to fix it? -
My for loop is working but when the if is included within the template it is not working in django
principal.html this is the code of my template.The is_hod field is a Boolean field <table class="table" style="text-align: left;"> <thead> <tr> <th>Requested by</th> <th>Requested on</th> </tr> </thead> {% for request in all_requests %} <tbody> {% if retest.is_hod %} <tr> <td>{{ request.name }}</td> <td>{{ request.date }}</td> <td><button onclick="location.href= '/retest/{{ request.id }}/';">View details</button></td> <tr> {% endif %} </tbody> {% endfor %} </table> -
Possible to load a Django returned JSON string into a local JavaScript variable?
For this particular technique, I have searched the internet and SO for a while without answers. My attempt is to allow JavaScript/jQuery to receive a JSON string returned from Django. Why? Because I need to constantly query the server side for new data. I have identified 2 possibilities, but neither of them appears to solve my problem. First, I understand that this could be done by an AJAX call. But the issue associated with this approach is the asynchronous nature, which requires the data manipulation to be done in the success call back. Second, I could have Django Template Language to receive this JSON string and further pass it to JavaScript. This approach, however, appears to feed the data directly to the template. As the data needs to be frequently refreshed, I am not sure this is a good option. What is desired here is a direct approach to allow a local JavaScript variable to receive the JSON string returned from Django and to be further used for data manipulation. Put in a simple way: Is it possible to allow JavaScript to receive a JSON string from Django and store it locally (not in a local file)? Due to my … -
Django: "Form object has no attribute..." error
I'm new in Django ,and I'm trying to develop a simple Django application which takes two numbers from the user with a form and do some operation with those numbers and print the result with a Http Response. My code is the following: forms.py class SimpleForm(forms.ModelForm): a = forms.IntegerField(label='first' ) b = forms.IntegerField(label='second' ) def result(self): return doSomething(self.a, self.b) views.py class MainPage(FormView): template_name = 'simple.html' success_url = '/result/' form_class = SimpleForm def form_valid(self, form): return HttpResponse(form.result()) However, when I run this code on my localhost, it gives the error like SimpleForm object has no attribute 'a' So, what can be the problem? How can I get the user input in order to use it in my "result" function? Thanks in advance... -
Django channels for real time app
I have started working on Django application which should have a WEB UI to run my custom scripts on another server and I need to see the output in the UI in real time. Importent to see step by step script execution. Question is - how to redirect script output (print, logger for python script) to channels and then push it to the client?