Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elastic Search not Indexing
When trying to index new users in out Django app, Elastic is unable to index...returning a key error of key ['created'] Traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home//venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/app/management/commands/index_users.py", line 19, in handle bulk_indexing(User) File "/home/uapp/management/commands/index_users.py", line 12, in bulk_indexing bulk(client=es, actions=(m.indexing() for m in model.objects.all())) File "/home/venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 257, in bulk for ok, item in streaming_bulk(client, actions, **kwargs): File "/home//venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 180, in streaming_bulk client.transport.serializer): File "/home/venv/local/lib/python2.7/site-packages/elasticsearch/helpers/__init__.py", line 58, in _chunk_actions for action, data in actions: File "/home/app/management/commands/index_users.py", line 12, in <genexpr> bulk(client=es, actions=(m.indexing() for m in model.objects.all().iterator())) File "/home/app/models.py", line 137, in indexing obj.save(index="users") File "/home/venv/local/lib/python2.7/site-packages/elasticsearch_dsl/document.py", line 418, in save return meta['created'] KeyError: 'created' I believe the iterator I am just unsure as what actually happening. Can provide more code if needed. -
Django combine foreign keys in a single queryset
I have a model in a Django application that is being referenced by multiple other models as a ForeignKey. What I am looking for is for a way to create a single queryset for all objects of this class that are being referenced as ForeignKey by the rest of the classes based on some criteria. I am not even sure if this is possible, but I thought about asking anyway. class Person(models.Model): pass class Book(models.Model): year_published = models.PositiveIntegerField() author = models.ForeignKey(Person) class MusicAlbum(models.Model): year_published = models.PositiveIntegerField() producer = models.ForeignKey(Person) recent_books = Book.objects.filter(year_published__gte=2018) recent_music_albums = MusicAlbum.objects.filter(year_published__gte=2018) # How can I create a **single** queryset of the Person objects that are being referenced as `author` in `recent_books` and as `producer` in `recent_music_albums`? Thanks for your time. -
Allauth Social Login with DRF JWT
I am using DRF, DRF-JWT, Allauth and Res-auth and djangorestframework-jwt-refresh-token in my Django Application. I have a custom JWT Register Serializer to collect some additional user info and create and create a refresh-token that is used to refresh expired JWT tokens. We have that working across backend and ios Application with no problems for email signup. I am now trying to implement the JWT with the sociallogin element of allauth in particular facebook as a provider. I can create a refresh token against a facebook user by overriding the DefaultSocialAccountAdapter but I'm struggling to return a Json response with a JWT with said refresh token to mobile client. This creates refresh token: class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form): user = super(CustomSocialAccountAdapter, self).save_user(request, sociallogin, form) app = 'users' user.refresh_tokens.create(app=app) return user I can create JWT manually with this: jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) I'm just having difficulty putting it all together, should I be overriding the adapter or using pre_social_login signal. Any pointers appreciated. -
MySQL Test DB Failing
I set up a Django 2 app (and Python 3.6) with a remote MySQL DB (using mysqlclient), with proper permissions. When I run my unit test, I get the following error: django.db.utils.ProgrammingError: (1146, “Table ‘test_<db>.<db>’ doesn’t exist”). Technically I could create a local dev DB for testing, but I would prefer to figure out this error. -
Upgrading to django 1.11 many to many column not found
I'm upgrading a project from Django 1.10.8 to 1.11 and am suddenly getting weird bugs in my unit tests. I've used a slight hack to update an existing many-to-many relation to use a custom 'through' table with an extra 'order' field. All worked fine in 1.10 but now fails in 1.11 with django.db.utils.ProgrammingError: column api_session_pollgroups.pollgroup_id does not exist My model code looks like this: class SessionPollGroup(models.Model): session = models.ForeignKey('api.Session') pollgroup = models.ForeignKey('api.PollGroup') order = models.PositiveSmallIntegerField(default=0) class Meta: db_table = 'api_session_pollgroups' ordering = ('order',) the table 'api_session_pollgroups' was preexisting when the initial many-to-many relation was made and I 'hijacked it' to add the extra order field. relation on the session model looks like this pollgroups = models.ManyToManyField('api.PollGroup', related_name='sessions', through=SessionPollGroup) Anyone know why this would fail to either generate or find the correct db schema in django 1.11 and not 1.10 ? Note: this seems to only appear during unit tests, when i create a new database using regular migrations the tables appear to be created correctly in my development db ( postgres ) but not in the unit test db ( sqlite ) thanks! -
Why do I get redirected to https://www.facebook.com/dialog/return/close#_=_ instead of the main facebook page?
So, I have a project in Django that is supposed to post some stuff on facebook, which apparently it does, but instead of opening the proper page it goes to blank https://www.facebook.com/dialog/return/close#= instead. Very inconvenient for a potential client. -
Django object filtering across multiple models
I have a Django app for articles. Each article can be commented on and articles can be published as a set of articles with an optional pre-face (which can be also commented upon). I allow tagging of articles and pre-faces, tags are hierarchical (eg category Culture covers Theater, Movies etc). Tags can be extracted from pre-faces and articles directly, or from comments. Tags form comments are relevant to the article / pre-face they belong to too. If a pre-face contains a tag, it is relevant for all articles in the set. So if we have a set with a pre-face and two articles, and the pre-face is in the comment tagged as Theater, this tag is relevant for given comment, pre-face and all articles. If article 1 in the set is tagged with a Movies tag, that tag is relevant only for the article itself. Part of models.py, keeping out fields that shouldn't be relevant to question (like headlines, text etc): class TagName(models.Model): value = models.CharField(max_length=255, unique=True) class TagCategory(models.Model): # Allow association with both articles and comments content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() belongs_to = GenericForeignKey('content_type', 'object_id') tags_in_category = models.ManyToManyField(TagName) # Contains eg regex pattern for category extraction category_info … -
About pythonType
I want ask you about Type of value in Django 2.0.2, I have code ======================================== in file with name (models.py) class AutherDetalis(models.Model): author = models.ForeignKey(Author,on_delete=models.PROTECT) post = models.ForeignKey(Post,on_delete=models.PROTECT) def __str__(self): return "{} - {}".format(self.author,self.post) ======================================== in file with name (views.py) class AuthorView(DetailView): model = AutherDetalis template_name = "AuthorView.html" context_object_name = "authorview" slug_field = "author" ======================================== in file with name (urls.py) path('AuthorView/<slug>/',AuthorView.as_view(),name="AuthorView"), when I write " /AuthorView/ " they ValueError comes and he says : invalid literal for int() with base 10: '<name_of_author>' ======================================== I want ask about the value of <name_of_author> What is ? and how I can solve the problem ? -
How to set option additional option to map in django-leaflet
I need to set an option {editable: true} at the moment i create map object like this: var map = L.map('map', {editable: true}); But i'm using django-leaflet extension where i just subscribe on callback and get already created map object: {% leaflet_map "map_frame" callback="window.show_layers" %} function display_layers(map, options){ ... } May be it possible that i somehow pass this option to template tag or some other way to activate leaflet Editable plugin. https://github.com/Leaflet/Leaflet.Editable -
CSRF and CORS with Django (REST Framework)
We're in the process of moving our frontend into a separate project (out of Django). It's a Javascript single page application. One of the reasons is to make it easier for our frontend developers to do their work, not having to run the entire project -- including the API -- locally. Instead, we'd like them to be able to communicate with a test API we've set up. We've managed to solve most of the CORS/CSRF issues along the way. But now we've run into something I can't find a solution for anywhere, despite reading lots of documentation and SO answers. The frontend and the API are served from different domains (during development localhost and test-api.example.com). Until now, while served from the same domain, the frontend has been able to get the CSRF token from the csrftoken cookie set by the API (Django). But when served from different domains, the frontend (localhost) can't access the cookies of the API (api-test.example.com). I'm trying to figure out a way to work around this, to somehow deliver the CSRF token to the frontend. The Django docs recommend to set a custom X-CSRFToken header for AJAX requests. Would we compromise the CSRF protection if we … -
Should I use groups in live chat made with Django Channels 2?
I am trying to create a live chat for a website where the admin can chat with everyone individually from the backend. But users can only chat with the admin, not with each other. I was reading up on the docs for channels and I read: Anyone who has the name of a channel can send a message to the channel. So do I need to create a group for each user with that user and the admin in that group for them to chat? Or can I just use the channel name from the consumer instance and use that somehow for the admin to chat with the user? -
application of simple choice task in django
I have just finished the django tutorial here https://docs.djangoproject.com/en/2.0/intro/tutorial01/. But I am still not sure to write the following intended application. The application asks an user to enter his/her name, then to make 30 choices. At the end I need to record those choices under the user's name. The major part I am confusing is about data export and import. The tutorial shows how to enter the questions in a shell. But I would like to the program to read parameters from a matlab matrix(say 30*10 matrix), or whatever files possible. Here the number of rows is equal to 30, which is equal to the number of task. Essentially I only need one form. The form should literately read one row from the matrix hence shows a parameterised choice task to the user. The user makes a choice and proceeds to next form. The next form will read the next row from the matrix and shows a new choice task. I suspect for a simple application like this I may not even need to create a database. Just create a list and export it will do the work. Is any one can let me know where to find an example/ … -
Django how to check if objects contains string in multiple fields
So I have a model called Puzzle which contains a title, question, and a subject. I want to be able to search for puzzles by entering a string. My search bar also contains three checkboxes: - title - question - subject I want to somehow be able to query my database to see if the ticked fields contain the search text. For example, if title and question were ticked, I would query to see if the puzzle's title contains this string OR its questions contains the string. Is there any way to query this in Django? I know that if I wanted to check just one of these fields, for instance the title, I could just do this: Puzzle.objects.filter(title__contains=search_text) But I want to be able to dynamically query the fields that are ticked. Currently, my view contains three boolean values: title, question, and subject. The boolean is True is it is ticked, and false if it is not ticked. How can I manipulate these three booleans along with Django queries to be able to dynamically query my database? Thank you -
Django foreignkey
I am trying to add new patient details to the following piece of code and linking to mysql database as i have created in the settings.. I am getting an error OperationalError at / (1054, "Unknown column 'patCube_patientlist.no_id' in 'field list'")but i never created such a column. why did this happen.. models.py from django.db import models from django.utils import timezone class PatientList(models.Model): no = models.ForeignKey('auth.User', on_delete=models.CASCADE) patientID = models.CharField(primary_key = True,max_length=200) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) address = models.CharField(max_length=200) age = models.IntegerField(max_length=200) ssn = models.CharField(max_length=200) added_date = models.DateTimeField( default=timezone.now) created_date = models.DateTimeField( blank=True, null=True) def create(self): self.published_date = timezone.now() self.save() def __str__(self): return self.patienID views.py from django.shortcuts import render from .models import PatientList from django.utils import timezone def plist(request): patient = PatientList.objects.filter(created_date__lte=timezone.now()).order_by('created_date') return render(request, 'patCube/plist.html', {'patient': patient}) def patient_detail(request, pk): pat = get_object_or_404(Post, pk=pk) return render(request, 'patCube/patientdetail.html', {'pat': pat}) def add_patient(request): if request.method == "POST": form = PatientForm(request.POST) if form.is_valid(): newpatient = form.save(commit=False) newpatient.no = request.user newpatient.created_date = timezone.now() newpatient.save() return redirect('patient_detail', pk=newpatient.pk) else: form = PatientForm() return render(request, 'patCube/add_patient.html', {'form': form}) plist.html {% extends 'patCube/base.html' %} {% block content %} {%for pat in patient%} <div class="patient"> <div class="date">{{ pat.created_date }}</div> <h1><a href="{% url 'patient_detail' pk=pat.pk %}">{{ pat.patientID }}</a></h1> … -
Django Error While Submitting Forms
Performing system checks... Unhandled exception in thread started by .wrapper at 0x75abfcd8> Traceback (most recent call last): File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 673, in exec_module File "", line 222, in _call_with_frames_removed File "/home/pi/tango_with_django_project/tango_with_django_project/urls.py", line 25, in url(r'^rango/', include('rango.urls')), File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in … -
Invalid block tag on line 5: 'else'. Did you forget to register or load this tag?
I am getting this irritating error and even after half an hour i am not able to resolve it. In beginning of my index.html file i am putting this code. {% load static %} {% if user.is_authenticated %} {% extends 'dashboard.html' %} {% else %} // Some other html {% endif %} dashboard.html is in the same directory as of index.html.I would love to get corrected. -
Django Tutorial part 2 Field Error
I got a field error when I was trying to run the tutorial of Django Part 2. I'm using Python 3.6 and Django 1.11. models.py import datetime from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Working with the tutorial, step by step. I was running the python manage.py shell: >>> from polls.models import Question, Choice >>> Question.objects.all() <QuerySet [<Question: What's up?>]> >>> Question.objects.filter(id=1) <QuerySet [<Question: What's up?>]> >>> Question.objects.filter(question_text__startswith='What') I got the following error after Question.objects.filter(question_text__startswith='What'): django.core.exceptions.FieldError: Cannot resolve keyword 'question_text_startswith' into field. Choices are: choice, id, pub_date, question_text I don't know what to do to repair this error, maybe I put something wrong at models, that's why I share models.py with You. I hope you can help me -
Django: How to import CSS libraries in Ajax template
I am using Ajax in my Django project to implement some simple searching. In my template folder, I have created an html file called "ajax_search.html" where I write how I want my objects to be displayed on a page. Right now it looks like this: {% if puzzles.count > 0 %} {% for puzzle in puzzles %} <a href="{% url 'puzzle' puzzleID=puzzle.id %}"> {{puzzle.title}} </a> <br> {% endfor %} {% elif search_len < 3 %} {% else %} No puzzles match the search {% endif %} This works fine, but I wanted to style it to look better. Is there any way I could import some CSS into this template? Thank you! -
Number of forms in js don't reset after page refresh, django and django-dynamic-formsets
I have a django formset in which a form is dynamically being added and removed using jquery.formset.js. It keeps track of number of forms that are currently in a formset. But when I refresh the page, the number of forms in a formset doesn't get rest to 1, and due to min and max number of forms that can be added in the formset, it doesn't allow more forms to be added. Initial form: With Two forms: After Refresh: I should not have the choice to remove the form but I can see it, because the number of forms still is stored as 2. And I can add only 1 more form, because maximum number of forms that can be added is 3. Please help me handling this issue. -
django.db.utils.ProgrammingError: column cms_page.path does not exist
I just upgraded my djangoCMS environment to the versions listed below. When I'm trying to access the page I get this error: Traceback (most recent call last): File "/home/admin/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/home/admin/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/admin/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/admin/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin/.local/lib/python3.5/site-packages/cms/views.py", line 48, in details page = get_page_from_request(request, use_path=slug) File "/home/admin/.local/lib/python3.5/site-packages/cms/utils/page_resolver.py", line 120, in get_page_from_request page = get_page_from_path(path, preview, draft) File "/home/admin/.local/lib/python3.5/site-packages/cms/utils/page_resolver.py", line 76, in get_page_from_path return get_page_queryset_from_path(path, preview, draft).get() File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/query.py", line 379, in get num = len(clone) File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/query.py", line 238, in len self._fetch_all() File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all self._result_cache = list(self.iterator()) File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/query.py", line 54, in iter results = compiler.execute_sql() File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql cursor.execute(sql, params) File "/home/admin/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/admin/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/admin/.local/lib/python3.5/site-packages/django/db/utils.py", line 94, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/admin/.local/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/admin/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column cms_page.path does not exist LINE 1: SELECT DISTINCT "cms_page"."id", "cms_page"."path", "cms_pag... I did run … -
What is difference between instance namespace and application namespace in django?
I am referring https://www.webforefront.com/django/namedjangourls.html to understand django urlconfs. I have encountered terms instance namespace and application namespace. I know about namespaces in urlsconfs. But I don't know the difference between them. I referred django docs for it. It mentions that instance and app namespaces, comes into picture, when multiple instances of same app is used in django project. But still, I am not able to understand it. I have googled out, but couldn't find any help on it. Thanks in advance. -
Django Division in models return integer only
good morning, Trying to do a weighted average with some values in my models. def get_resultavg(self): return Result.objects.filter(employee_id=self, eval_at__isnull=False).exclude(evaluation_value=0).aggregate(average=Sum(F('evaluation_value')*F('question__question_weight')/100, output_field=FloatField())) and In my template <td class="text-center align-middle">{% with averagecalc=employee.get_resultavg %} {% if averagecalc %} <small> {{ averagecalc.average|floatformat:"-2"|default:"-" }} </a> </small> {% endif %} {% endwith %}</td> The result in template should be 4.2 based on numbers for question_weight and evaluation_value. But it brings me 4.00, I know the problem is when I include the division. I tried with float(100), mutiplying * 0.01 but nothing. What am I doing wrong here guys? Thanks -
Django Admin. Disable `list_editable` fields for editing after date?
Django 2.0.3, Python 3.6.1 I have standard Django admin panel. For one of my model I create list_editable for some fields (price and provider_price on screenshot). Question is: How to disable this list_editable fields for edit after some date? For example, if now is March 11, 2018 and older, fields price and provider_ price are disabled and doesn't edit in list view. -
Django: <ul> inside help_text of field
I would like to have a inside the help_text of a django form field. Unfortunately django renders the help_text inside a . According to the HTML spec a must not contain a . At least that is what my validation tool says. Here is the source of django: https://github.com/django/django/blob/master/django/forms/forms.py#L283 def as_table(self): "Return this form rendered as HTML <tr>s -- excluding the <table></table>." return self._html_output( normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', error_row='<tr><td colspan="2">%s</td></tr>', row_ender='</td></tr>', help_text_html='<br><span class="helptext">%s</span>', errors_on_separate_row=False) What can I do to get in the help_text and valid html. -
Getting tracks from a playlist using Spotipy is slow
I'm interacting with the Spotify Web API for a django project that allows users to upload their playlists for them to be ranked according to certain parameters, namely audio features spotify assigns to all tracks. I'm using the Spotipy library to query the spotify API with python. It's lightning fast for user and playlist data, but following the Spotipy tutorials on how to get tracks from a playlist, I'm finding the response is extremely slow. The wait time for tracks is about proportional to the length of the playlist in tracks.. I'm thinking it has something to do with an inefficiency in how the spotipy library packages up and sends requests. Has anyone ever come across a similar bottle neck with regards to getting tracks and speed? I'd be very grateful.. our project kind of hinges on it at this point.