Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to populate django nvd3 line chart as in the context?
I am very new to Django chart. I was looking at the nvd3 line chart example online, and was trying to try it myself. It uses the return render_to_response('index.html', data) method to return the chart. However, I have other components in my webpage that is rendered by the context. Is there any way i can render the django line chart through the context like the other components? Thanks! view.py def index(request): 'Chart' xdata = ["Apple", "Apricot", "Avocado", "Banana", "Boysenberries", "Blueberries", "Dates", "Grapefruit", "Kiwi", "Lemon"] ydata = [52, 48, 160, 94, 75, 71, 490, 82, 46, 17] chartdata = {'x': xdata, 'y': ydata} charttype = "pieChart" chartcontainer = 'piechart_container' data = { 'charttype': charttype, 'chartdata': chartdata, 'chartcontainer': chartcontainer, 'extra': { 'x_is_date': False, 'x_axis_format': '', 'tag_script_js': True, 'jquery_on_ready': False, } } return render_to_response('index.html', data) #html {% load static %} <link media="all" type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.css"> <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script> <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.min.js"></script> {% load nvd3_tags %} <head> {% load_chart charttype chartdata "linechart_container" True "%d %b %Y %H" %} </head> <body> {% include_container "linechart_container" 400 600 %} </body> -
Django - TypeError at feeds() missing 1 required positional argument: 'id'
I'm trying to add comments to my project and I've got this error: feeds() missing 1 required positional argument: 'id'. Here is my code. views.py @login_required def feeds(request, id): feeds_list = Feed.objects.all() feed = get_object_or_404(Feed, id=id) users = User.objects.filter(is_active=True) if request.method == 'POST': # Komentarz został opublikowany. feed_form = FeedForm(request.POST) if feed_form.is_valid(): # Utworzenie obiektu Comment, ale jeszcze nie zapisujemy go w bazie danych. new_feed = feed_form.save(commit=False) new_feed.user = request.user new_feed.date = timezone.now # Zapisanie komentarza w bazie danych. new_feed.save() else: feed_form = FeedForm() context = {'section': feeds, 'users': users, 'feeds_list': feeds_list, 'feed_form': feed_form} return render(request, 'feed/list.html', context) I think that's here is problem: feed = get_object_or_404(Feed, id=id), but I don't know how to solve it. Thanks for help. Edit: urls.py from django.contrib.auth.urls import url from . import views app_name = 'feedApp' urlpatterns = [ url(r'^$', views.feeds, name='feeds'), url(r'^feed/new$', views.post_new, name='post_new'), url(r'^feed/(?P<id>[0-9]+)/$', views.feed, name='post_detail'), # url(r'^feed/(?P<id>[0-9]+)/comment$', # views.comment_feed, # name='comment_feed'), url(r'^feed/(?P<id>[0-9]+)/delete/$', views.feed_delete, name='feed_delete'), ] -
How to design the user table in database?
I want to develop a server side of an app that holds users. Of course I need a table in database holding the user information. At first I may write class User(models.Model): # using django models userid = ... password = ... which gives me a database table containing userid and password. However, I might want to add some attributes (maybe Credit, Birthday...so on) to each user in the future. I just can't think up all of them right now. And I can't know what attributes I would really need in the future. How can I deal with it? -
Django : Html in Django Admin field?
I want to have a hyperlink in my Django Admin Dashboard. But Django admin is escaping the html. I looked at this answer. But doesnt seem to work. I think allow_tags has been deprecated. What are my options? -
ImportError: No module named 'settings'
I have two versions of python installed 2.7 and 3. and created a virtualenv and assigned python34 to that new environment. When I activate that virtualenv and run python manage.py runserver then I get the following output. (casenv) C:\pyprojects\focus\site>python manage.py Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\virtualenvs\casenv\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\virtualenvs\casenv\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\virtualenvs\casenv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\virtualenvs\casenv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\virtualenvs\casenv\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\virtualenvs\casenv\lib\importlib\__init__.py", line 104, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2231, in _gcd_import File "<frozen importlib._bootstrap>", line 2214, in _find_and_load File "<frozen importlib._bootstrap>", line 2203, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1448, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "C:\pyprojects\focus\site\general\models.py", line 8, in <module> from focus2.util import HashedPk File "C:\pyprojects\focus\site\focus2\util.py", line 3, in <module> from settings import Hasher ImportError: No module named 'settings' File - manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "focus2.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may … -
Django: how to insert data into 2 tables
I am trying to create an application that takes the URL of a website and returns its TLD. TLD is the foreign key of its respective table. I want to insert into the URL table that takes the TLD and inserts it into the TLD table. So that when I access the URL table I see only the ID of the TLD This is my models. TLD class TLD(models.Model): name = models.CharField(max_length=10, unique=True) def save(self, *args, **kwargs): super(TLD, self).save(*args, **kwargs) def __str__(self): return str(self.name) UrlExtractor class UrlExtractor(models.Model): url = models.CharField(max_length=255) tld_id = models.ForeignKey(TLD, null=True, blank=True) status = models.BooleanField(default=True) created = models.DateTimeField(auto_created=True, auto_now=True) def save(self, *args, **kwargs): super(UrlExtractor, self).save(*args, **kwargs) def __str__(self): return str(self.url) This is my view functions: def tld_of_url(thestring): link = "" for i in thestring[::-1]: link += i if i == ".": break tld_more = link[::-1] tld = "" for i in tld_more: if i != "/": tld += i else: break return tld class UrlExtractorView(View): def get(self, request): the_form = UrlExtractorForm() context = { "title": "Enter website", "form": the_form } return render(request, "website.html", context) def post(self, request): url_form = UrlExtractorForm() if url_form.is_valid(): url_form = UrlExtractorForm(request.POST) url = url_form.cleaned_data.get('url') true_tld = tld_of_url(url) tld = TLD(name=true_tld) tld_form=TLDForm(request.POST) if tld_form.is_valid(): … -
Django calculation based on calculated value
Hello there Django goods. I need your help once more. I am working on a project for my wargaming group. It is a simple ranking site. So we have players, they participate in tournaments and get points. I got to the point where I am able to assigne players to tournaments, assign place they took at the tournament to their name. Now I have to calculate points. Algoritm is simple, but I have problems passing a value from Tournament model to Ranking. Each Tournament has a calculated rating (based on other things, mostly bigger tournament, bigger rating) and in other models I wa unable to use it and need your help with it. On top of that ... would be awsome if changing a rating value in Tournament would force update of all dependent calculations. So we have models like that: class Player(models.Model): class Meta: name = models.CharField(max_length=50) nicname = models.CharField(max_length=50,blank=True) army = models.CharField(max_length=50) def __unicode__(self): return self.name def __str__(self): return self.name class Tournament(models.Model): class Meta: name = models.CharField(max_length=100) date = models.DateTimeField('date') player_num = models.IntegerField points = models.FloatField(default=1000.00) def __unicode__(self): return self.name def __str__(self): return self.name And then I have a ranking model of this kind: class TournamentStandings(models.Model): tournament = … -
django 1.8 application migrated to new server rises strange exception
We had this Django 1.8 application working in the server we setup 6 months ago (Fedora 24 64-Bit). Yesterday we setup a new server with same packages and now we suddenly get this error: Django Version: 1.8 Exception Type: TypeError Exception Value: _new_pool() got an unexpected keyword argument 'request_context' Exception Location: /usr/lib/python2.7/site-packages/urllib3/poolmanager.py in connection_from_pool_key, line 262 Python Executable: /usr/bin/python Python Version: 2.7.11 Seemingly offending code: # Make a fresh ConnectionPool of the desired type 259 scheme = request_context['scheme'] 260 host = request_context['host'] 261 port = request_context['port'] 262 pool = self._new_pool(scheme, host, port, request_context=request_context) 263 self.pools[pool_key] = pool May the Django 1.8 files have changed in repository so this doesn't work anymore? seems very strange to me. -
How to perform a fulltext search in djang array field
I have an ArrayField of strings and I want to search if any of the items are contain any of the items within an intended set of strings. I have defined the field like following: class Path(models.Model): path = models.TextField() files = ArrayField(models.CharField(max_length=300)) server_name = models.CharField(max_length=50) def __str__(self): return self.path And I want to check let's say if the files are contain any name that may contains one of these strings ['foo', 'bar', 'baz']. That means if the files is contain the following items: ['example', 'examplebar'] I want it to return true. I already looked into all the related methods for an ArrayField but non of them seems to work. I want something that is a combination of contains and overlap. -
How to have nested base.html in django's templates?
I am rebuilding all my templates so it becomes a lot more manageable and custom, the tree would look like this : ├───core │ └───templates │ └───base.html (original, touches every page) │ ... │ ├───app1 │ └───templates │ ├───base.html (extends from core/base.html, only touches app1) │ └───file1.html (extends from app1/base.html) │ ... │ └───app2 └───templates ├───base.html (extends from core/base.html, only touches app2) └───file2.html (extends from app2/base.html) ... To connect app1's template to core's I use {% extends '../../core/templates/base.html' %}, in the core app there'll be {% block container %}{% endblock %} as example and in app1, app2 there'll be other {% block other_content %}{% endblock %} blocks. as you can see blocks are nested too. The issue is that I get this error : The relative path ''../../core/templates/base.html'' points outside the file hierarchy that template 'base.html' is in. Question: I was wondering what was the best approach to resolve this issue without hardcoding it? -
Is django-channels suitable for real time game?
I want to make a real time game, I wanted to use NodeJS-SocketIO or aiohttp, Until I met django-channels, then i read its documentation. This is a good module Questions: Is django-channels suitable for real time game? Does django-channels have an advantage over aiohttp/nodejs-socketio? Is it suitable for all client (android, IOS, desktop)? -
Is mod_WSGI replacing what apache is doing and how I can make wsgi work at a specific path only
I am quite new to Apache and WSGI, there are a lot of things confusing me. After a fresh install of apache2 on ubuntu, I can open this URL to see the default apache page http://localhost/index.html, the file is residing in /var/www/html. So this is the function that apache server provices, serving http connection. Here's the current situation: I've created a simple Django project and install mod_wsgi onto my apache server,and finally I managed to deploy the project to apache and the page iIve created can be accessed correctly. BUT now when I try to access the index.html i mentioned above, it shows the url mapping cannot be found(yes I do not have this mapping in the django project).Is Django taking over all the path that point to the server? How can I make the django project only map to a specific path like http://localhost/Django/[MY URL MAPPING] and keep other url mapping untouched. So I can access the static HTML(index.html) by accessing http://localhost/index.html/ and access my Django project by accessing http:/localhost/Django/[xxx] Is this possible? or I have to use another virtual host at another port? Any help will be much appreciated. -
Django:"RuntimeError: maximum recursion depth exceeded" on get_queryset function
I am getting RuntimeError: maximum recursion depth exceeded on the below code class BookingViewSet(viewsets.ModelViewSet): queryset = Booking.objects.all() serializer_class = BookingSerializer def get_queryset(self): queryset = self.get_queryset().filter(owner=self.request.user) return queryset I found that the problem is with the get_queryset function, but i can't find what is its cause. -
Custom queryset for change_view in Django admin
I have overloaded a default queryset to exclude objects with 'deleted' flag. But I would like to have an option to edit them in Django admin panel (but don't need to have them in list of all objects there). As I understand, it is possible to override queryset for the whole 'Admin' class, but is it possible to override it only for a single view? -
Extra column in annotation or combining math functions with F objects (Django)
I need your help: I need to calculate sth in "annotate" part: I have tried two approaches but non of them has not had the expected results Model class Observation(models.Model): residual = models.FloatField(null=False, verbose_name="Residual [mm]") agl = models.FloatField(null=False, verbose_name="Agl [deg]") b = models.FloatField(null=False, verbose_name="B [deg]") (1 approach) Using math library and making computation in annotate function on F objects import math as m query1 = Observation.objects.filter(**filterargs).exclude(**filterargsExclude) .annotate(slope_egl=RegrSlope('residual',m.degrees(m.acos(m.cos(m.radians(F('b')))*m.cos(m.radians(F('agl'))))))) This aprroach brings the Type Error a float is required (2 approach) Using extra select to make additional column and and trying to execute annotate function with alias of this column query2 = Observation.objects.filter(**filterargs).exclude(**filterargsExclude) .extra(select={'egl':"degrees(acos(cos(radians(o.b))*cos(radians(o.agl))))"}) .annotate(slope_egl=RegrSlope('residual','egl'))))) This aprroach brings the Field Error Cannot resolve keyword 'egl' into field I will be very grateful for your help :) -
admin.py completely ignored when app is in: /myvenv/myproject/apps/myapp/
Recently I upgraded my project to latest Django (from 1.8 to 1.11.4) and my models don’t show up anymore in the Django Admin interface. The weird thing is that the app itself works as expected. The full path /myvenv/myproject/apps/myapp/ A part of the structure: /myvenv/ /bin /etc /myproject /templates /settings/settings.py /apps /myapp /templates/myapp/myview.html /views.py Some other symptoms: 'manage runserver' also misses this file for auto reload My custom management commands in that app are unknown since the update nb: The 'myproject' is actually called 'project' (clash?) When forcing import from /myvenv/myproject/apps/myapp/__init__.py/ from .admin import * it breaks on the first admin.site.register() with: LookupError at /admin/ No installed app with label 'myapp'. I’ve: disabled as much as possible in the settings file removed all (old) admin autodiscover code disabled as much imports as possible (cleaning redundancy) added 'django.setup()’ recently to settings, but not sure after/before what settings it should go. Installed apps (seen from manage shell): <module 'django.contrib.auth' from '/srvapp/local/lib/python2.7/site-packages/django/contrib/auth/__init__.pyc'> <module 'django.contrib.contenttypes' from '/srvapp/local/lib/python2.7/site-packages/django/contrib/contenttypes/__init__.pyc'> <module 'django.contrib.sessions' from '/srvapp/local/lib/python2.7/site-packages/django/contrib/sessions/__init__.pyc'> <module 'django.contrib.messages' from '/srvapp/local/lib/python2.7/site-packages/django/contrib/messages/__init__.pyc'> <module 'django.contrib.staticfiles' from '/srvapp/local/lib/python2.7/site-packages/django/contrib/staticfiles/__init__.pyc'> <module 'django.contrib.sites' from '/srvapp/local/lib/python2.7/site-packages/django/contrib/sites/__init__.pyc'> <module 'bootstrap3' from '/srvapp/local/lib/python2.7/site-packages/bootstrap3/__init__.pyc'> <module 'django.contrib.admin' from '/srvapp/local/lib/python2.7/site-packages/django/contrib/admin/__init__.pyc'> <module 'django.contrib.admindocs' from '/srvapp/local/lib/python2.7/site-packages/django/contrib/admindocs/__init__.pyc'> <module 'myapp' from '/srvapp/project/apps/myapp/__init__.pyc'> The init's: /myvenv/myproject# find . … -
Passing info from the page to the server in Django
I'm new to Django and I'm facing something pretty frustrating. There is an app that I've written a few months ago and I've recently decided to make it into a web application. I already have both client and server side written and working and I already set up the Django server to work. The only thing I'm struggling with is passing data from the page to the server. I am able to transform info to the page in the views file using the code below, but I simply can't find a good explanation online on how to transfer info from the page to the server. I'm assuming its not a simply form-action like in classic HTML with other frameworks (like PHP), but its something that still should be relatively straight-forward and I'd be glad if anyone could point me in the right direction. Here's the code I'm using in the app's views.py file to transfer data back to the page, but I need the 'info' string to be taken from the page first. return render(request, "mypage.html", {'content':[imported function from my app]('info')} -
Count online users - django
I want to count my l users where they logged or they are just visitor . is there any library to do this for me?or is there any way to do that?(i want just a way or library) Tnx all💛 -
Django talking to multiple servers
There's a lot of info out there and honestly it's a bit too much to digest and I'm a bit lost. My web app has to do so some very resource intensive tasks. Standard setup right now app on server static / media on another for hosting. What I would like to do is setup celery so I can call task.delay for these resource intensive tasks. I'd like to dedicate the resources of entire separate servers to these resource intensive tasks. Here's the question: How do I setup celery in this way so that from my main server (where the app is hosted) the calls for .delay are sent from the apps to these servers? Note: These functions will be kicking data back to the database / affecting models so data integrity is important here. So, how does the data (assuming the above is possible...) retrieved get sent back to the database from the seperate servers while preserving integrity? Is this possible and if so wth do I begin - information overload? If not what should I be doing / what am I doing wrong? -
django orm how to use values and still work with modeltranslation
I am using django v1.10.2 I am trying to create dynamic reports whereby I store fields and conditions and the main orm model information into database. My code for the generation of the dynamic report is class_object = class_for_name("app.models", main_model_name) results = class_object.objects\ .filter(**conditions_dict)\ .values(*display_columns)\ .order_by(*sort_columns)\ [:50] So main_model_name can be anything. This works great except that the related models are actually registered with django-modeltranslation and their names do not appear with the right translation field. So for one of the reports main_model is ProductVariant. ProductVariant hasMany Pattern. My display columns are :serial_number, created_at, pattern__name The first two columns are fields that belong to ProductVariant model. The last one is from Pattern Pattern model looks like this: from django.db import models from django.utils.translation import ugettext_lazy as _ class Pattern(models.Model): name = models.CharField(_('Pattern Name'), max_length=400) serial_number = models.CharField(_('Pattern Number'), max_length=100, unique=True) def __str__(self): return str(self.name) + ' (' + str(self.serial_number) + ')' class Meta: verbose_name = _('Pattern') verbose_name_plural = _('Patterns') The queryset calling values() does not return me the expected language zh_hans for the field pattern__name. I read the documentation about multilingual managers at http://django-modeltranslation.readthedocs.io/en/latest/usage.html#multilingual-manager but I still do not know how to make this work. Bear in mind that the … -
django orm how to use values and still work with choicefield
I am using django v1.10.2 I am trying to create dynamic reports whereby I store fields and conditions and the main orm model information into database. My code for the generation of the dynamic report is class_object = class_for_name("app.models", main_model_name) results = class_object.objects\ .filter(**conditions_dict)\ .values(*display_columns)\ .order_by(*sort_columns)\ [:50] So main_model_name can be anything. This works great except that sometimes associated models of the main_model has choicefield So for one of the reports main_model is Pallet. Pallet hasMany PalletMovement. My display columns are :serial_number, created_at, pallet_movement__location The first two columns are fields that belong to Pallet model. The last one is from PalletMovement What happens is that in PalletMovement model looks like this: class PalletMovement(models.Model): pallet = models.ForeignKey(Pallet, related_name='pallet_movements', verbose_name=_('Pallet')) WAREHOUSE_CHOICES = ( ('AB', 'AB-Delaware'), ('CD', 'CD-Delaware'), ) location = models.CharField(choices=WAREHOUSE_CHOICES, max_length=2, default='AB', verbose_name=_('Warehouse Location')) Since the queryset will return me the raw values, how do I then make use of the choicefield in PalletMovement model to ensure that the pallet_movement__location gives me the display of AB-Delaware or CD-Delaware? Bear in mind that the main_model can be anything depending on what I store in the database. Presumably, I can store more information in the database to help me do the filtering and … -
Image upload in ImageFileFormat in django python
I am save upload file in my database. The image Field is ImageFieldFormat This is my model of the project. I want to upload file but it is showing me the error above -
Django Many-to-Many data model
I'm trying to create a data structure that involves Products, Customers and Orders. Customers and Products are independent tables, while the Orders references Products and Customers. Orders table fields: Time stamp Customer Product along with Quantity Here is my attempt at creating a django model to achieve this: from django.db import models class Customer(models.Model): name = models.CharField(max_length=30) latitude = models.FloatField(default=0) longitude = models.FloatField(default=0) class Product(models.Model): name = models.CharField(max_length=30) weight = models.FloatField(default=0) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) products = models.ManyToManyField(Product) quantity = ? How do I create a quantity field that maps to a particular product? Alternate models to achieve the same results are also welcome. -
django rest framework how to implement temporary users like django lazysignup
i'm writing a Angular 2 webapp that consumes a DRF api in the backend. When a user visits the site, he or she should be able to interact with the site without logging in. However, in the backend, i cant have Anonymous users due to the way i fetch data in the database. Currently, i'm using auth0 to receive JWT tokens, which are then sent as Authorization headers to the API. These tokens will automatically create a user if one doesn't exist already. This is all good, but for those users who dont sign in, i have no JWT token to send. The problem here is essentially recreating django lazysignup but for Django rest framework. Any ideas? -
How to aggregate a Subquery?
There are 2 models: class Candidate(Model): name = CharField(max_length=1024, primary_key=True) class Votes(Model): how_many = PositiveIntegerField() candidate = ForeignKey(Candidate, on_delete=CASCADE) Now I'd like to annotate each Candidate with how many votes did he receive. From what I read in the documentation https://docs.djangoproject.com/en/1.11/ref/models/expressions/#subquery-expressions I suppose I could do it like that: sub = Votes.objects.filter(candidate=OuterRef('pk')) annotated_candidates = Candidate.objects.all().annotate( score=Subquery(sub).aggregate(res=Sum('how_many')))['res'] ) However, I can't. I get: 'Subquery' object has no attribute 'aggregate' How to achieve what I'm trying to achieve? Note: I know in this particular case I could do this easier this way: annotated_candidates = Candidate.objects.annotate( score=Sum('votes__how_many') ) The reason I'm trying a subquery instead is that this is a simplified case, in reality I want to do some extra filtering on Votes.