Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django object related categories and subcategories shown in form
maybe somebody can help me, I use Django with the following models.py: class FilterCategory(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class FilterValue(models.Model): category = models.ForeignKey(FilterCategory) value = models.CharField(max_length=50) class Video(models.Model): title = models.CharField(max_length=500) filters = models.ManyToManyField(FilterValue, blank=True) Now what I need is to show HTML form in template where user can choose filters for Video in separate fields, so lets say in Box A User can choose one or more filters from Category A Does anybody have ideas what is the best approach? -
Change time format of HH:MM:SS
I have an api served with django (django-rest-framework) which return a movie object and its related information into a Vue app. One of the information is the movie duration. object: { "movie_id": 13, "duration": "17:52:14", ... ... }, template: <div id="movieDetailSynopsis"> ... ... <p>Duration: {{movie.duration}}</p> </div> The duration is in this format HH:MM:SS eg: 02:22:08 But what I want it to look like is in this way 2h 22m Is there anyway to achieve this in django or vuejs or javascript? -
Cannot connect to localhost when running Django
I am trying to run my Django project and I encountered the following problem: ^C(venv) tests-MacBook-Pro-2:hearinsights morganlai$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x103fc46e0> Traceback (most recent call last): File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check_migrations() File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 163, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 176, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/django/db/backends/postgresql/base.py", line 175, in get_new_connection connection = Database.connect(**conn_params) File "/Users/morganlai/Desktop/hearinsights-heap/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port … -
Get all item from a related Models in Django
I have Two models related: class Author(models.Model): ---- class Article(models.Model): author = models.ForeignKey(Author) .... I have an instance of the class author. How can I get all articles of the author? Such as: articles = author.article_set.getAllArticlesFromAuthor() I know it can be obtained from a query, but I would like to know if exists a short method provided by Django -
Routing not working for my AJAX request
I currently have a url pattern defined as follows: url(r'^potato/(?P<slug1>[-\w])/(?P<slug2>[-\w]+)/potatoajax/$', views.potatoajax, name='potatoajax'), and in my views a function: def potatoajax(request): print 'Potato Ajax' if request.method == 'POST': print 'more potatoes' else: print 'dont print Potato AJax' My ajax request is as follows: var url = 'potatoajax/'; $.ajax({ url: url, data: { 'hello': 'hello world', 'csrfmiddlewaretoken': getToken(), }, type: 'POST', dataType: 'json', success: function (data) { $('#message').html(data.message); } However, I keep getting 404's on my requests =( I strongly suspect this is related to my routing in the url pattern, but have no idea how to correct this. here is the error message: POST http://localhost:8000/potato/potato1/potato2/potatoajax/ 404 (Not Found) -
Installing .whl file on Heroku
I am currently trying to host my Python Django-powered website on Heroku but the CLI failed during installation of a required package, Numpy+Mkl (pip could not find links for the package). I have installed the package on my dev server through the .whl file I have download in Christoph Gohlke's online repository of python packages. I am wondering if are there some ways I could install this package on Heroku? Or do I have to find other hosting sites? If yes, can you recommend a better hosting site? -
Using DICT.get(key) but still getting KeyError in Django
A bit of background info about the project I'm doing... It's an automatic essay checking system and the admin user (myself) should be able to add, edit, and attempt questions in the system. I'm able to add essays to the system but was not able to edit and attempt. Whenever I try to edit and attempt, KeyError appears. I'm honestly not sure what went wrong because I recreated the system using my professor's code and his worked. Here is the KeyError message for edit & attempt question: http://imgur.com/iH9OG07.png And here is the code for views.py (its quite long): http://pastebin.com/88vvZJ6J I've read a lot of solutions on stackoverflow regarding KeyError but none of them seem to help except for this which comes close to my problem: Getting KeyError in my django code According to users from that post, he was able to solve the KeyError by changing some lines. And a lot of users mention about using DICT.get(key) but it seems to me that my current code (views.py) is already using the DICT method...? (please correct me if I'm wrong!) I'm a real noob in Django and would really, really appreciate any help to solve them. If you need more info … -
input username check unique immediately with django rest framework
I want to realize like this: if I input any character in username input tag I can check the username if unique in server. I know I can do like this: use javascript + debounce, after user input characters stop 0.5 second, then I send username to server(I can create single view to handle this solution), and if find duplication, I can hint some error near it. But in fact, I am not only handle the username, I want to handle all of config form, I want to every form's field can be test before send whole form data to server like this. There may be 100 fields, I dont' want to write a view for every field, so does django-rest-framework support some function? or is there any package suuport it, or somebody have any idea for it?? in fact, I use reactjs, but I don't think it have any relationship with this problem -
Uncaught Error: Exception in makeTransliteratable: Invalid element id lang
I am using the following js code to convert local language from English in a django app. // Load the Google Transliteration API google.load("elements", "1", { packages: "transliteration" }); function onLoad() { var options = { sourceLanguage: 'en', destinationLanguage: ['ml'], shortcutKey: 'ctrl+m', transliterationEnabled: true }; // Create an instance on TransliterationControl with the required // options. var control = new google.elements.transliteration.TransliterationControl(options); // Enable transliteration in the textfields with the given ids. var ids = [ "lang", "langu", "language" ]; control.makeTransliteratable(ids); // Show the transliteration control which can be used to toggle between // English and Hindi and also choose other destination language. // control.showControl('translControl'); } google.setOnLoadCallback(onLoad); The error on console is Uncaught Error: Exception in makeTransliteratable: Invalid element id lang at Yy (transliteration.I.js:178) at Xy.Q.ij (transliteration.I.js:323) at onLoad ((index):551) Thanks in advance for your help. -
CSS is not working in Django app, no clue what is wrong
I know this is a repeated question, but I am unable to find any answers that would make the static files run for me. I am using Django version: 1.10.5 and python version: 3.4.3... I have read the official documentation too, no luck in solving my problem... The following is my project structure: myproject4 /myapp/ /__pycache__/ /migrations/ __init__.py admin.py apps.py models.py tests.py views.py /myproject/ /__pycache__/ __init__.py settings.py urls.py wsgi.py /static/ /css/ hpage.css robot.css /images/ -- Images -- /js/ -- JavaScript Files -- /template/ hello.html manage.py Here's what all I have tried: {% load staticfiles %} for my hello.html page, right at the top, <link href="{%static 'css/hpage.css' %}" rel="stylesheet" /> <link href="{%static 'css/robot.css' %}" rel="stylesheet" /> for linking my CSS files in hello.html (it makes use of 2 CSS files). I have tried {{ STATIC_URL }} way of doing the same and the necessary stuffs I am supposed to do too, but found no luck there. When I use the <style> </style> tags, the css works perfectly, but that's not what I am looking for. settings.py: DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] #Other stuffs go here STATIC_ROOT = 'staticfiles' STATIC_URL … -
Ranking players using Django ORM (Postgres - RANK)
I have a Profile model that has a points field as follows: class Profile(models.Model): user = models.OneToOneField(User) avatar = models.ImageField(default=None, null=True) experience = models.IntegerField(default=10) island = models.ForeignKey(Island, default=None, null=True) fcm_token = models.CharField(max_length=255, default=None, null=True, unique=True) points = models.DecimalField(default=0.0, max_digits=12, decimal_places=10) What I want to do is that rank the users according to their points. I can do it using a simple raw SQL query which is as follows- select id, RANK() over (order by points desc) as rank from player_profile ; Which gives me the following output- id | rank ----+------ 1 | 1 2 | 2 3 | 2 4 | 2 (4 rows) The initial data was- id | avatar | experience | fcm_token | user_id | island_id | points ----+--------+------------+-----------+---------+-----------+-------------- 2 | | 10 | | 3 | 4 | 0.0000000000 3 | | 10 | | 4 | 3 | 0.0000000000 4 | | 10 | | 5 | 1 | 0.0000000000 1 | | 10 | | 2 | 3 | 5.1010101010 (4 rows) The problem is that I am unable to write an quivalent query using Django's ORM -
Celery/Django: Test if task ETA is set correctly in relation to datetime
I have a django model that stores a datetime, and I need to create a celery task that runs X days before this datetime, and one that runs at (or slightly after) this datetime. How would I go about creating a unit test that checks whether the tasks ETA is set correctly in relation to the datetime? I'm using Django 1.8, Celery and RabbitMQ -
Dynamically adding and removing fields with CSS written Panels in Django?
I have a Panel with header Tabs were written in Pure CSS, I would like to add a (+) and (-) signs to that panel, which let me Dynamically add or remove extra filed to the panel. -
i want make a sequence of questions one by one in for a test in django
im new to django and i want to put a series of questions such that when we answer one only then next one appears and the question no should no be stored in the url , i thought of using a model attribute for question attempt but just i want to know if there is a simpler way views.py class testpage(View): template_name = "test.html" i=1 def get(self, request, test_id): test = get_object_or_404(Apt_Test, pk=test_id) if self.i <= test.apt_qns_set.count(): q=test.apt_qns_set.get(pk=self.i) context = { "q": q } return render(request, self.template_name, context) def post(self, request, test_id): test = get_object_or_404(Apt_Test, pk=test_id) if Testscore.objects.filter(user=request.user).exists(): score = Testscore.objects.get(user=request.user, test=test) else: score = Testscore.objects.create(user=request.user, test=test) try: q = test.apt_qns_set.get(pk=request.POST['question']) selected_choice = q.answers_set.get(pk=request.POST['choice']) except(KeyError, Answers.DoesNotExist): context = { "t": test, "error": "you didnt select a choice" } return render(request, self.template_name, context) else: if selected_choice.correct_set.filter(pk=request.POST['choice']).exists(): if q.correct_set.get(pk=request.POST['question']) == selected_choice.correct_set.get( pk=request.POST['choice']): score.score += 1 score.save() self.i+=1 return HttpResponseRedirect(reverse('test', args=(test_id))) else: self.i+=1 return HttpResponseRedirect(reverse('test', args=(test_id))) -
Django Custom Backend Documentation Discrepancy
I am having difficulty understanding how Django's documentation has outlined the overriding of the authenticate method in contrib.auth.models.Users. According to the code below from here, wouldnt the authenticate method succeed if the method was passed a valid username and a valid hash that exists anywhere in the database regardless of whether it matches the password for the supplied primary key field (username, email, etc...) or not. Is there something that check_password is doing that I am not seeing like ensuring that the field that was passed alongside of the password is checked behind the scenes? Because this supplied example appears to have a flaw. # From Django 1.10 Documentation def authenticate(self, username=None, password=None): login_valid = (settings.ADMIN_LOGIN == username) pwd_valid = check_password(password, settings.ADMIN_PASSWORD) if login_valid and pwd_valid: try: user = User.objects.get(username=username) except User.DoesNotExist: # Create a new user. There's no need to set a password # because only the password from settings.py is checked. user = User(username=username) user.is_staff = True user.is_superuser = True user.save() return user return None Thanks. -
Django Rest Framework post parameters in schema
I'm trying to create a custom API (not using models), but its not showing the request definition in the schema (in consequence, not showing it in swagger). My current code is: views.py class InfoViewSet(viewsets.ViewSet): @list_route(methods=['POST']) def some_method(self, request): data = JSONParser().parse(request) serializer = GetInfoSerializer(data=data) serializer.is_valid(raise_exception=True) info = get_data_from_elsewhere(serializer.data) return Response(info) urls.py router.register(r'^info', InfoViewSet, base_name='info') serializers.py class InfoSomeMethodSerializer(serializers.Serializer): list_id = serializers.ListField(child=serializers.IntegerField()) password = serializers.CharField() And it appears in swagger, but just the response part. How can I register the post parameters? I'm also not sure if I'm using DRF correctly (I'm new) so any correction will be appreciated. -
`related_names` not available as a reverse relationship
I have the following models: models.py class Invoice(models.Model): # invoice fields class LineItems(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='lineitems') code = models.ForeignKey(Code, on_delete=models.CASCADE, related_name='lineitems') # other fields I believe I should be able to access related objects of Invoices through invoice.lineitems.all() and of Code through code.lineitems.all() where invoice and code are instances of the Model classes. However, if I do: x = Invoice.objects.last() x.lineitems.all() I get the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "../.venv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 816, in __get__ return self.related_manager_cls(instance) File "../.venv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 683, in __init__ super(RelatedManager, self).__init__() TypeError: __init__() takes exactly 2 arguments (1 given) Am I accessing this incorrectly? Perhaps there is a name clash somewhere? -
django import export import xls, get column value through the foreignkey of related model
i'd like to import data to my Score model. My problem is i can't figure out how to properly "write" this section: widget=ForeignKeyWidget(Player.gamesiteaccount_set, 'score_nick')) to make it work. I'd like to get Player id through the realated model (GamesiteAccount) field 'score_nick' I don't know if my explanation is understandable enough, but the following code should clarify everything. models class Player(models.Model): active = models.BooleanField(default=True, null=None, blank=None) nick = models.CharField(max_length=25, unique=True) created = models.DateTimeField(default=timezone.now, null=True, blank=True) class GamesiteAccount(models.Model): active = models.BooleanField(default=True, null=None, blank=None) player = models.ForeignKey(Player, null=False, blank=False, on_delete=models.CASCADE) gamesite = models.ForeignKey('gamesites.Gamesite', null=True, blank=True, on_delete=models.CASCADE) login = models.CharField(max_length=20, unique=True) password = models.CharField(max_length=20, unique=False) score_nick = models.CharField(max_length=60, unique=True) class Gamesite(models.Model): active = models.BooleanField(default=True, null=None, blank=None) name = models.CharField(max_length=25, unique=True) created = models.DateTimeField(default=timezone.now, null=True, blank=True) url = models.URLField(null=True, blank=True) class Score(models.Model): player = models.ForeignKey('players.Player', null=True, blank=True, on_delete=models.SET_NULL) gamesite = models.ForeignKey('gamesites.Gamesite', null=True, blank=True, on_delete=models.SET_NULL) score = models.DecimalField(max_digits=6, decimal_places=2) date = models.DateTimeField(default=timezone.now, null=True, blank=True) import table: #id | score_nick | score_usd | gamesite | date #================================================ # | therock211 | 14.00 | Gamesite1 | 2017-02-05 # | asdasd | 5.15 | Gamesite2 | 2017-02-05 resource.py class ScoreResource(resources.ModelResource): player = fields.Field( column_name='player', attribute='player', widget=ForeignKeyWidget(Player.gamesiteaccount_set, 'score_nick')) gamesite = fields.Field( column_name='gamesite', attribute='gamesite', widget=ForeignKeyWidget(Gamesite, 'name')) class Meta: model = Score … -
CkEditor ImportError: No module named ckeditordebug_toolbar
I'm having this issue while trying to install CkEditor by following instructions listed here: https://github.com/django-ckeditor/django-ckeditor I pip installed ckeditor, added it to my installed apps in settings.py and then did a python collectstatic and I got this error: ImportError: No module named ckeditordebug_toolbar Is this a known issue or am I doing something wrong? -
Bootstrap Popover not centered
I hope you can help me out with a little problem. Right now I am working a little Listing-App project with Django. I have created my main HTML File for it and have a small table, where Django loads a list of movies inside, those movies have a Title that is a link and if you hover over this link a popover (from bootstrap 4) shows up with a small preview image from the movie. Now the problem is that the Popover is not always 100% centered. Most of the time the popover looks like this: But then again, sometimes (like 2 out of 7 movies) it looks like this: The weird thing is that this mostly happens when you hover for the first time over the link AND it doesn't occur all the time, sometimes it also occurs after you hovered like 2-3 times over it. I looked for a lot of solutions, but can't find any help. My Code is below: {% extends "consilium/base.html" %} {% block body %} <table class="table"> <thead> <tr> <th></th> <th colspan="2">My Movielist</th> <th> </tr> <tr> <th></th> <th>TITLE</th> <th>GENRE</th> <th>RELEASE DATE</th> <th>DIRECTOR</th> <th>RUNTIME</th> <th>STATUS</th> <th>IMDB</th> <tr> </thead> </tbody> {% if latest_movie_list %} {% for … -
Pyexcel get records from excel upload
I'm trying to integrate pyexcel into a Django project and trying to follow the example on the docs. I'm trying to replicate this functionality: import pyexcel as pe records = pe.iget_records(file_name="your_file.xls") for record in records: print("%s is aged at %d" % (record['Name'], record['Age'])) How do I go about opening the records via a file upload. I've tried to do this with no luck: if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) records = pe.iget_records(file_name=request.FILES['file']) for record in records: .. This line is bugging out: records = pe.iget_records(file_name=request.FILES['file']) -
django template show content only in a jquery dialog
I have a Django HTML template as follows: {% extends 'base.html' %} {% block title %}Cloud | Review {% endblock %} {% block content %} {% load static %} {% load render_table from django_tables2 %} <div id="dialog" title="Dialog"> <p>Testing a simple Dialog box.</p> </div> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> function EditDialog() { $( "#dialog" ).dialog(); return false; } </script> <div class="function-page"> <div class="table-form"> <div class="function-container"> {% render_table reviews %} </div> </div> </div> {% endblock %} The jquery dialog box is launched when the user clicks a link. The issue is when the page is loaded, the div contents are shown at the top of the page <div id="dialog" title="Dialog"> <p>Testing a simple Dialog box.</p> </div> Is it possible to show this content only in the jquery dialog and not in the usual page content. Also, once I show the dialog box by called EditDialog() the div disappears from the main underlying page. -
Django: queryset - get a specfic column from DB in plain text
I am trying to list out names of associations from database in plain text but what i get is this: https://gyazo.com/6588724ee73431e10e88bcfa3650f99d How can I exclude parenthesis, comma and ticks? Still a newbie so appreciate your help! Forms.py class RegForm(forms.ModelForm): ... association = forms.ModelChoiceField( queryset=Association.objects.values_list("asoc_name"), widget=forms.Select(attrs={'class': 'form-control'}), required=True) Models.py class Association(models.Model): ... asoc_name = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'Association' -
Simple Ajax call to Django server results with slow response time - slow TTFB
First of all, I do not have lots of experience with django, js and ajax, but this is quite a simple example and I cannot find the reason why my ajax calls take a lot of time. My current dev configuration is: windows 7, python 3.6, django 1.10.5 Basically, I click on a button (in specific buttons group), this activates ajax and depending on the reply, color of the button is updated. Info: In reality, I use something a bit more complex, but since it was also slow I tried to simplify it, to see where it goes wrong, but I still cannot find the reason. Code ajax: $('body').on('click', '.some_module', function(){ var $something= $(this); $.ajax({ url: 'some_function/', type: 'GET', data: {'some_name' : "just_example"}, dataType: 'json', success: function(data){ ...some_action_where_i_change_color_of_button... ...not important because even if it's empty, it's slow... } }); }); Code django, views.py: def change_module(request): # ...for example using hardcoded return... data = { 'success': True, 'curr': 'something', 'selected': [], 'previous': [] } return HttpResponse(json.dumps(data), content_type='application/json') # tried also JSONResponse, the same feedback So by using this example, I wait for an update for more than 1s and TTFB is always around 1s. TTFB is related to server side, but … -
How to limit results in reverse relation in Django
I have two tables, one called Company and the other called User, each user is related to one company using ForeignKey. So I can use reverse relation in Django to get all users for specific company (e.g. company.users) In my case, I'm building ListAPIView which return multiple companies, and I'd like to return latest created user. My problem is that I don't want to use prefetch_related or select_related so it will load all the users, as we might end up having thousands of users per each company! Also I don't want to load each latest user in a separate query so we end up having tens of queries per API request! I've tried something like this: users_qs = models.User.objects.filter(active=True).order_by('-created') company_qs = models.Company.objects.prefetch_related( Prefetch('users', queryset=users_qs[:1], to_attr='user') ).order_by('-created') In this case, prefetch_related failed as we can't set limit on the Prefetch's queryset filter (it gives this error "Cannot filter a query once a slice has been taken.") Any ideas?