Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django geoposition map doesn't appear in admin
I'm using django-geoadmin in a project and added it to my admin. When I access it, it shows the lat field, long, but not the google map. There are no errors in the browser console. I have the application configured correctly in settings.py: INSTALLED_APPS and GEOPOSITION_GOOGLE_MAPS_API_KEY. What can cause this? -
TemplateDoesNotExist at / in Django/Python Application
I am trying to run a Django Application with PyCharm and getting this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.7.1 Python Version: 2.7.14 Installed Applications: ('django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'compressor', 'menu', 'django_extensions', 'estabelecimento', 'bootstrap3', 'django_autocomplete', 'easy_select2', 'daterange_filter', 'qrcode') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', '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') Template Loader Error: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: Using loader django.template.loaders.app_directories.Loader: C:\Users\Marcos\PycharmProjects\japedi\django_admin_bootstrapped\templates\index.html (File does not exist) C:\Python27\lib\site-packages\django\contrib\admin\templates\index.html (File does not exist) C:\Python27\lib\site-packages\django\contrib\auth\templates\index.html (File does not exist) C:\Python27\lib\site-packages\rest_framework\templates\index.html (File does not exist) C:\Python27\lib\site-packages\compressor\templates\index.html (File does not exist) C:\Python27\lib\site-packages\django_extensions\templates\index.html (File does not exist) C:\Users\Marcos\PycharmProjects\japedi\bootstrap3\templates\index.html (File does not exist) C:\Users\Marcos\PycharmProjects\japedi\daterange_filter\templates\index.html (File does not exist) C:\Users\Marcos\PycharmProjects\japedi\qrcode\templates\index.html (File does not exist) Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 137. response = response.render() File "C:\Python27\lib\site-packages\django\template\response.py" in render 103. self.content = self.rendered_content File "C:\Python27\lib\site-packages\django\template\response.py" in rendered_content 78. template = self.resolve_template(self.template_name) File "C:\Python27\lib\site-packages\django\template\response.py" in resolve_template 54. return loader.select_template(template) File "C:\Python27\lib\site-packages\django\template\loader.py" in select_template 194. raise TemplateDoesNotExist(', '.join(not_found)) Exception Type: TemplateDoesNotExist at / Exception Value: index.html There are some directorys called templates inside the project. For every specific application there is one folder templates inside them. Anybody could help me with this? There is a version in a production environment with … -
When is template_name required in a ListView
I defined a Horario class in my models and I have a horario_list.html in my templates directory. If I define this class, everything works fine: class HorariosView(generic.ListView): model = Horario def get_queryset(self): return Horario.objects.all() However, if I change the return type by a list, like this class HorariosView(generic.ListView): model = Horario def get_queryset(self): return list(Horario.objects.all()) I get an exception TemplateDoesNotExist. Now, if I add a template_name property in my class, everything works again: class HorariosView(generic.ListView): model = Horario template_name = 'horario_list.html' def get_queryset(self): return list(Horario.objects.all()) When and why is template_name required? -
Manual activation of new user accounts in Django
I created a working "Log in with facebook" setup with django-allauth. However, I want those new user accounts that allauth creates to not be activated automatically. Basically I want to activate all new accounts from the Django admin pages. What would be a best practice solution to this? Thanks -
How can I consume real-time data from alphavantage API in python?
I try to use alphavantage API with my Django project. At the moment I am going to parse the JSON data in this way: from alpha_vantage.timeseries import TimeSeries def AlphaVantage(symbol): ts = TimeSeries(key='mykey') data = ts.get_intraday(symbol, interval='1min') print(str(data)) AlphaVantage('MSFT') In response I get data in this form: { "Meta Data": { "1. Information": "Intraday (1min) prices and volumes", "2. Symbol": "MSFT", "3. Last Refreshed": "2017-09-29 16:00:00", "4. Interval": "1min", "5. Output Size": "Compact", "6. Time Zone": "US/Eastern" }, "Time Series (1min)": { "2017-09-29 16:00:00": { "1. open": "74.4550", "2. high": "74.5041", "3. low": "74.4300", "4. close": "74.4900", "5. volume": "4761846" }, "2017-09-29 15:59:00": { "1. open": "74.4944", "2. high": "74.5000", "3. low": "74.4500", "4. close": "74.4550", "5. volume": "217391" }, "2017-09-29 15:58:00": { "1. open": "74.4400", "2. high": "74.5000", "3. low": "74.4400", "4. close": "74.4900", "5. volume": "157833" } ... However I would like to get only the most current data, in this case: "2017-09-29 16:00:00": { "1. open": "74.4550", "2. high": "74.5041", "3. low": "74.4300", "4. close": "74.4900", "5. volume": "4761846" } Any ideas how can I solve it? -
Django Rest DRF : getting count of objects for reverse relation
Let's say I have two models. Model class Item(models.Model): name = models.CharField(max_length=32) # other fields class ItemRelation(models.Model): item = models.ForeignKey(Item, related_name='relations_item') user = models.ForeignKey(User, related_name='relations_user') has_viewed = models.BooleanField(default=False) has_loved = models.BooleanFields(default=False) Now, what I want to do is I want to get the view_count and love_count for all items using django rest api. views.py class ItemView(ListAPIView): queryset = Items.objects.all().prefetch_related(Prefetch('relations_item', queryset=ItemRelation.objects.filter(Q(has_viewed=True) | Q(has_loved=True)) ) serializer_class = ItemSerializer Well, this was the plan but I have absolutely no idea how to get the view_count and love_count for each item in the list-api-view. I tried quite a few things on my serializer but I don't think it's going to work. I can however use SerializerMethod() to do the work, but that would go through the DB N+1 number of times. I have read through the docs along with a few other blogs for prefetch_related and I was able to do things easily until this count problem showed up. Just a sample from my serializer. class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['name', 'relations_item'] -
python for loop output as list
I need to get some calculations for a range of elements at an array. So, at my views.py my code is: (...) for f in enumerate(array) calc1 = value_x calc2 = value y (...) and, when I print calc1, for example, my output returns 1 1 1 1 1 0.98 1 1 1 1 1 1 and, my output has to be like this ['1', '1', '1', '1', '1', '0.98', '1', '1', '1', '1', '1', '1'] I've already tried to do something like testLi = [] for f in enumerate(array): testLi.append(str(TPR_class)) print 'testLI {}'.format(testLi) but it gives me testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98', '0.98'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] testLI ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', … -
Django migrations failing with fresh database
wondering if anyone else is experiencing frustrating behavior with Django migrations. I have looked at several related posts on SO but have not found anything addressing this specifically. This keeps happening to me, and it MUST be a common scenario, so what am I missing? My scenario: List item I've built a Django application, iterating using sqlite on my local machine I now want to deploy to a production Postgresql db (AWS or elsewhere) I set up my new database, add it to my settings, and run python manage.py makemigrations I get a SQL error telling me that one of my model tables doesn't exist. Duh! That's why I'm running makemigrations. I end up having to hand-make tables, do weird things like python manage.py migrate <app_name> --fake which creates further issues with packages like simple_history I'm sure there must be an obvious answer -- what should I do to set up database schema on a brand new, clean database? -
Django ORM query, left join with where
I need to translate one query. Models class Publication_dependecy(models.Model): def __str__(self): return(str(self.id)) class Publication(models.Model): def __str__(self): return(self.name) name = models.TextField() class Publication_relationship(models.Model): def __str__(self): return(self.publication_from + '#' + self,publication + '#' + self.publication_dependecy_id) from_publication = models.ForeignKey(Publication, related_name='from_publication', on_delete=models.CASCADE) to_publication = models.ForeignKey(Publication, related_name='to_publication', on_delete=models.CASCADE) publication_dependecy = models.ForeignKey(Publication_dependecy, on_delete=models.CASCADE) SQL query: select Publication.id from Publication left join Publication_relationship on Publication.id = Publication_relationship where publication_dependecy is NULL or Publication_dependecy = 1 I need to retrive all publications that are not in Publication_relationship or his publication_dependecy is 1. In other words publication_dependency is 1 or NULL -
How to change Django paths/project/app
After going through How to change the name of a Django app? I am still having issues with my django setup The last time my django project 'ran' my setup was like this /resume ~/repos/resume /resume /apps /static /templates __init__.py settings.py urls.py wsgi.py ... manage.py requirements.txt ... The project name was resume and was in /repos/resume I changed the project name to portfolio and the directory to /repos/portfolio so that it becomes /portfolio ~/repos/portfolio /resume /apps /static /templates __init__.py settings.py urls.py wsgi.py ... manage.py requirements.txt ... I renamed them using pycharm's rename feature. I believe the references and such are updated correctly. Now when I am running python manage.py migrate (portfolio) nono@nono:~/repos/portfolio$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/nono/.virtualenvs/portfolio/src/django/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/nono/.virtualenvs/portfolio/src/django/django/core/management/__init__.py", line 300, in execute settings.INSTALLED_APPS File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/nono/.virtualenvs/portfolio/src/django/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/nono/.virtualenvs/portfolio/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
Sending uploaded file to another pc over network
i am new to Django and just discover how to select and upload images using "https://github.com/axelpale/minimal-django-file-upload-example". now i want to again select a image from a uploaded files and send that select image to another computer over network. i want all this to be done in python and Django. search a lot but did not find any thing useful -
Django ImageKits "ImageSpecField" with values_list()
Im using Django ImageKit to generate thumbnails. I would like to get a "preview" Image from the existing ImageField. ImageKit provides a ImageSpecField model field but I have trouble using it in combination with values_list(). Since the ImageSpecField isn't a real database field ("ImageSpecFields, on the other hand, are virtual—they add no fields to your database and don't require a database. "), it can't be called through values_list(). Anybody an idea how to get the value of the ImageSpecField into the values_list? How does the ImageSpecFields exactly work? Is an Image generated each time the model gets called? I'm curios for efficiency reasons. What I tried? In the current state I would add a URLField into the model and write a function to save the output of self.thumbnail.url into the URLField but this doesn't seem very practical... -
how to write join query in django?
I have googled several hours but couldn't understand how to write sql join(raw or ORM) related queries. Below is my model with two tables sandBox1 and licenseType where they will have common item "email" on which join will be performed class sandBox1(models.Model): email = models.EmailField(unique=True) name = models.CharField(max_length=200) website = models.TextField(validators=[URLValidator()]) comment = models.TextField(default='-') gender = models.CharField(max_length=6) def __str__(self): return self.email class licenseType(models.Model): #1=other, 2=two-wheeler 4=four-wheeler licenseId = models.IntegerField() sandboxId = models.ForeignKey(sandBox1) template file : index.html <html><form id="form1" method="post" action="{% url "sandbox" %}"> {% csrf_token %} Name: <input type="text" name="name" > <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website" > <span class="error"></span> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <hr>Check the license type you have:-<br> <input type="checkbox" name="license[]" value=2 > 2 wheeler<br> <input type="checkbox" name="license[]" value=4 > 4 wheeler<br> <input type="checkbox" name="license[]" value=1 > Other <br> <br> <input type="submit" name="submit" value="Submit"> </form> <div> {% for obj in sandBoxObj %} <p> {{ obj.name }}<br> {{ obj.email }}<br> {{ obj.website }}<br> {{ obj.gender }}<br> {{ obj.comment }}<br> {% endfor %} </div> </html> here is a view file that needs correction. I want to show the result of this sql query: select … -
Django/Python TypeError unorderable types: float() < HighscoreEasy()
I copied my working Django-App to a new Project and now I have an issue I can not resolve. I will check if the new playtime is lower than the old one. if playtime < HighscoreEasy.objects.filter(player=player).order_by('score').first(): Environment: Request Method: POST Request URL: https://www.maik-kusmat.de/kopfrechnen/results/ Django Version: 1.11.5 Python Version: 3.5.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'home', 'contact', 'kopfrechnen', 'braces'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware'] Traceback: File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pi/Dev/mkenergy/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/pi/Dev/mkenergy/src/kopfrechnen/views.py" in kopfrechnen_results 168. if playtime < HighscoreEasy.objects.filter(player=player).order_by('score').first(): Exception Type: TypeError at /kopfrechnen/results/ Exception Value: unorderable types: float() < HighscoreEasy() Here is the snippet from my Code with the issue: def kopfrechnen_results(request): end_time = time.time() if 'start_time' in request.session: start_time = request.session['start_time'] else: template = loader.get_template('kopfrechnen/kopfrechnen.html') context = {'error': 'Starte ein neues Spiel immer von hier.'} return HttpResponse(template.render(context, request)) if 'tasks' in request.session: tasks = request.session['tasks'] else: template = loader.get_template('kopfrechnen/kopfrechnen.html') context = {'error': 'Starte ein neues Spiel immer von hier.'} return HttpResponse(template.render(context, request)) if 'difficulty' in request.session: difficulty = request.session['difficulty'] … -
Django Project- CSS
I have a base.html file in my Django project in a the templates directory that is in the main project folder. I want my base.html to locate my file, so where should I be putting it in the project? I'm new to Django. -
Include jinja2 from django template
How can I include Jinja2 template from Django template? I'm using Django 1.11.5 and django-jinja 2.4.0. -
Aldryn News & Blog Instance Namespace
I have a question regarding Django CMS, in particular the "Aldryn News and Blog" apphook. I refer to this article on creating multiple "News and Blog" apphook. http://aldryn-newsblog.readthedocs.io/en/latest/how-to/apphook_configurations.html Everything works fine in development and I see a field "Instance Namespace". But in production, the "Instance Namespace" field is gone. Kindly refer to picture below. Any idea why? Thanks very much. Picture of Instance Namespace Screen -
How to sum three columns using django ORM
I'd like to execute such query using djagno models: SELECT id, ( first+second+third ) FROM testTable Without grouping. Was trying to find the solution using google but unsuccessfully. Thanks in advance, -
Wrapping the code
I have a friend who wants to pull NHL data from an API in such a way he could treat it directly in Excel. In fact, he has got a tremendous experience with Excel and wants to make predictions with it. I would like to create a little web application so that he could make his request easily, directly from an interface. https://www.quora.com/Is-there-any-JSON-API-available-for-getting-NHL-information-rosters-lineups-statistics-etc Questions: If I pull NHL data inside a .xlsx file, will he be able to process information in Excel from that file? If so, if I update the file twice a day and do its calculations in the same file, but on a different page, will the update delete its calculations? Assume I finished this web application, and the API used is no longer supported. I will need to change of API and refactor the entire code so that it will work with the new one. Is there a sort of wrapper I could use to avoid that kind of problem? A type of problem I could encounter is to have to reformat the 'pulling file' so that it could work with my application. -
How Should Django´Views be In this example?
https://www.w3schools.com/bootstrap/trybs_theme_company_full.htm In this example,the homepage view should return the entire page? And the buttons in the navbar just scrolls the page to a certain area of the page. How should I do it with Django? -
Django: disable initial system checks in production?
I've scoured the documentation and am looking for a Django setting that disables system checks (not just silences them) in production. I have a project with 20,000+ models which are autogenerated to create RESTful endpoints. These system checks take quite some time: https://docs.djangoproject.com/en/1.11/ref/checks/#models Having the systems check in development is necessary, even though it causes manage.py 20-30 minutes to fire up. However, any time I publish a new version to production, the first HTTP request to a production node takes 20-30 minutes to respond as well! I'd obviously like to avoid this, because after the initial request, the site is lightning fast. I've looked around for a setting like DISABLED_SYSTEM_CHECKS but have only come across SILENCED_SYSTEM_CHECKS (see here), but that just seems to silence the output rather than not running the checks that take the time. Does such an animal exist? I'm running mod_wsgi in production. I've seen requires_system_checks for individual commands, but am looking for a project-wide solution. Thanks very much. -
How do I prevent Anonymous Users from accessing certain parts of my website?
I want to prevent a user from seeing certain links on my navigation bar if the user is not logged in. I am using the if statement in my template to do this. When I am logged in it shows the correct set of links but when I signed out it does not. It should show the ul with the sign in links. WHat am I doing wrong? This is my code : <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> {% block head %} {% endblock %} </head> <body> <style> ul, li { margin: 0px 14px; } </style> <nav class = "navbar fixed-top navbar-light bg-light justify-content-between flex-nowrap flex-row"> <div class = " container"> <a class = "navbar-brand float-left" href = "{% url 'Identities:nest'%}">nest</a> {% if user.is_authenticated %} <ul class = "nav navbar-nav flex-row float-left "> <li class = "nav-item "><a class = "nav-link" href = "{% url 'Identities:logout'%}">Sign Out</a></li> <li class = "nav-item"><a class = "nav-link" href = "{% url 'Identities:view_profile' %}">view Identity </a></li> <li class = "nav-item"><a class = "nav-link" href = "{% url 'Identities:edit_profile' %}">edit Identity </a></li> </ul> {% else %} <ul class = "nav navbar-nav flex-row float-left "> <li class = "nav-item "><a class="nav-link" href = "{% … -
Nested routes with APIViews in Django Rest Framework
I'm writing my school project, building Django Rest API. And i have next entities: Profiles, Albums, Images, Comments, Likes. What i want is to make resources accessible in this way: api/v1/profiles/1/albums --> to get all the albums from profile with id 1 On examples i found, there is ViewSet used, instead APIView which i wanted to use ( I'm really newbie and i don't even know can i use ViewSet for CRUID operations ). I tried to implement next: https://blog.apptension.com/2017/09/13/simple-nested-api-using-django-rest-framework/ Routing API Views in Django Rest Framework? http://chibisov.github.io/drf-extensions/docs/#routers and many others, but i can't get it worked... If there is some detailed tutorial, please reference it, i really need to be fast. Thanks everybody! -
Allow different views for different types of users in django rest class based views
How do I write the following views using class based view? @api_view(['GET', 'POST']) def hotel_list(request): # List all hotel or add new . if request.method == 'GET': if request.user.is_authenticated: # Allow GET request for all authenticated users hotels = models.Hotel.objects.all() serializer = serializers.HotelSerializer(hotels, many=True) return Response(serializer.data) return Response({"message": "not authorized"}, status=status.HTTP_401_UNAUTHORIZED) elif request.method == 'POST': if request.user.is_superuser: # Allow POST method for super users only serializer = serializers.HotelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({"message": "not authorized"}, status=status.HTTP_401_UNAUTHORIZED) I want to allow different permissions for different groups of user. -
How to filter out queryset based on model method?
I have this query et: plist = UserProfile.objects.filter(q).order_by('-created_at') The model is: class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=30, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) def online(self): if self.last_seen(): now = datetime.datetime.now() if now > self.last_seen() + datetime.timedelta( seconds=settings.USER_ONLINE_TIMEOUT): return False else: return True What I want to achieve is to filter out further plist to contain only online users. I tried different tricks, like: for p in plist: if p.online: print 'profile onlnine \n', p.id online_plist.append(p) plist = online_plist But it does not work. So appreciate your hints.