Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to add checkbox next to user events?
I'm trying to add a checkbox next to the events in my calendar. I also want it to save as whatever the user leaves it as (checked/unchecked). views.py def event(request, event_id=None): instance = Event() if event_id: instance = get_object_or_404(Event, pk=event_id) else: instance = Event() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): event = Event.objects.create(**form.cleaned_data, user=request.user) print(event.title) return HttpResponseRedirect(reverse('cal:calendar')) return render(request, 'cal/event.html', {'form': form}) class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_queryset(self): qs = Event.objects.filter(user=self.request.user.id) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) cal.user = self.request.user html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context models.py class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(max_length=350) start_time = models.DateTimeField() end_time = models.DateTimeField() @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>' def __str__(self): return '{} - {} by {}'.format(self.title, self.description, self.user) Heres what my calendar looks like with an event added -
Set Up RabbitMQ on Docker with Django
I'm trying to set up a Docker container with Django. My Docker file is: FROM python:3.7-alpine MAINTAINER Freshness Productions ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user RUN rabbitmqctl add_user test testpass1 RUN rabbitmqctl add_vhost myvhost RUN rabbitmqctl set_permissions -p myvhost test ".*" ".*" ".*" RUN rabbitmq-server And my docker-compose.yml is: version: "3" services: app: build: context: . image: &app app ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 export C_FORCE_ROOT='true' celery -A app beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler" env_file: &envfile - env.env depends_on: - db - broker db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword worker: build: . image: *app restart: "no" env_file: *envfile command: sh -c "celery -A app worker --loglevel=info" volumes: - ./app:/app depends_on: - broker broker: image: rabbitmq:3 env_file: *envfile ports: - 5672:5672 I don't see what I need to do - other than I'm using two different images in my … -
Translatable choice field in Django models
I read this question but it did not help very much. I would like to have a choice field using an Enum (more readable code and possibly faster database operations) but at the same time, I would like the choices to be translatable, i. e. surrounded by ugettext(...). My enum looks like this: class UserLevel(Enum): STUDENT = 1 TEACHER = 2 but i have no idea how the associated model field shall look like. -
Django - send email when object is created
Generally, in order to send an email when an object is created, I would override the save method: def save(self, *args, **kwargs): send_email(context) return super().save(*args, **kwargs) However, I now need the context to contain an attribute of the object that cannot be known until the object is saved, namely the url of a File object associated with the model object. I am aware that this can be done with post_save signal, but the docs give the impression that this is best used when disparate models need access to such information. I get the impression that it's not good practice to use it in a single-model setup like this. I've tried this: foo = super().save(*args, **kwargs) send_email(foo.document.url) return foo But foo seems to be None. -
Can I log in webssh with user authentication info in browser?
I am building a webssh with xterm.js and django. I found a sample webssh app but it requires user to manually input username and password. I hope the users can directly make ssh connection after they have login our website, just with te stored user auth info. How can I do with that? -
Search a model using Django Rest api returns null set
I have made a simple model which i want to query using django rest api i have made it and API seems to be online however isn't working I am a beginner at Django and cant seem to find the error Any help would be greatly appreciated ! models.py class TagsDB(models.Model): # tags database links tags with each upload tag = models.CharField(max_length=10) title = models.ManyToManyField(Uploads) def __str__(self): return self.tag serializers.py class TagsDBSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TagsDB fields = ('url', 'tag', 'upload_title') views.py class TagsList(generics.ListAPIView): serializer_class = TagsDBSerializer def get_queryset(self): tag = self.kwargs['tag'] return TagsDB.objects.filter(tag=tag) urls.py urlpatterns=[ url('^tags/(?P<tag>.+)/$', TagsList.as_view()), ] I do get the API view but when i run a search with the url http://localhost:8000/tags/tag=java which is supposed to search the db for tag with the name java, although such an object does exist, i get an empty set emptysetshown -
How to clean up django filter() results
I'm new to the django orm and I'm having difficulty cleaning up the results I get from my filter(). I'm getting the results I want but I need to clean them up. I want to only put the results into a list. I did this to get the results into an array: resultObject= dbname.objects.filter(fieldindatabase = whatiwant) The above code gives me the search results but also adds a bunch of other stuff. Below is a screenshot of the items I want in a list. I want the items labeled [0], 1, [2], as those are the query results. Thanks for the help. -
Django_mobile in django 2.0
I actually wanted to have separate template for mobile and desktop, currently using django 2.1.7 facing following error system check identified no issues (0 silenced). April 06, 2019 - 18:42:59 Django version 2.1.7, using settings 'project_x.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f64bd6c8ae8> Traceback (most recent call last): File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/home/kanishk/newhostA/testhostA/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/kanishk/Downloads/project_newstart-master/project_offer/project_x/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 136, in __init__ self.load_middleware() File "/home/kanishk/newhostA/testhostA/lib/python3.6/site-packages/django/core/handlers/base.py", line 36, in load_middleware mw_instance = middleware(handler) TypeError: … -
My Accordion menu in bootstrap4 is not displaying the data in the right order as I intend it to
I have an accordion menu with sub categories and sub sub categories. the idea is when you open a category, the sub categories display under that category, same goes for sub categories, but my code is pushing my sub sub category to the very bottom and not under the sub category. <!-- Side bar --> <div class="col-md-4 col-xs-1 " id="sidebar"> <h5 class="d-flex flex-column align-items-center pt-3 ml-5">Content</h5> <div class="list-group panel"> <!-- we start with a collpsible item --> <!-- Python Menu --> <a id="collapse-main-link" href="#pythonmenu" class="list-group-item collapsed" data-toggle="collapse" data-parent="#sidebar" aria-expanded="false" onclick="change_arrow()">Python <span class="float-right text-secondary"><i id="collapse-main-link-icon" class="fas fa-chevron-circle-down"></i></span> </a> <div class="collapse" id="pythonmenu"> <a id="collapse-main-link" href="#Bokehmenu" class="list-group-item" data-toggle="collapse" aria-expanded="false" onclick="">Bokeh <span class="float-right text-secondary"><i id="collapse-main-link-icon" class="fas fa-chevron-circle-down"></i></span> </a> <a id="collapse-main-link" href="#Pandasmenu" class="list-group-item" data-toggle="collapse" aria-expanded="false" onclick="">Pandas <span class="float-right text-secondary"><i id="collapse-main-link-icon" class="fas fa-chevron-circle-down"></i></span> </a> <a id="collapse-main-link" href="#ScikitLearnmenu" class="list-group-item" data-toggle="collapse" aria-expanded="false" onclick="">ScikitLearn <span class="float-right text-secondary"><i id="collapse-main-link-icon" class="fas fa-chevron-circle-down"></i></span> </a> <div class="collapse" id="Pandasmenu"> <a href="/tutorial/1" class="list-group-item" data-parent="#Pandasmenu">How to read a csv file?</a> </div> <div class="collapse" id="Pandasmenu"> <a href="/tutorial/6" class="list-group-item" data-parent="#Pandasmenu">how to read an Excel file</a> </div> </div> <!-- End of Python Menu --> This is what it looks like now but both of the "how to" questions belong to the category of pandas an I want to be … -
How to get and set value from field in multi dimensional ArrayField?
How to get data from specific filled from multi dimensional ArrayField in Django and how to set new value. This is code for my class i want to get and set values in pb field class User(models.Model): name = models.CharField(max_length=20,default='user') password=models.CharField(max_length=200,default='arek1234') nationality=models.CharField(max_length=2,default='Na') pb=ArrayField( ArrayField( models.IntegerField(default='66666666'), size=5, ), size=18, default=list ) token=models.CharField(max_length=200,default='tokenos') id=models.AutoField(primary_key=True) def __str__(self): return self.name -
Is the post_save signal in Django atomic?
I really can't find anything solid in the docs. Lets say I'm doing something like this: from django.db.models.signals import post_save from django.dispatch import receiver class Item(models.Model): total_score = models.IntegerField() def set_score(self): ... class Review(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) score = models.IntegerField() @receiver(post_save, sender=Review) def my_handler(sender, **kwargs): sender.item.set_score() What I'm trying to do is call set_score() for the item object, whenever a review object is saved. Is this atomic? I definitely want the whole thing to be atomic, as a situation where a review is saved, but the item's total score is not updated is a recipe for bugs. -
How to render untemplated html with django
I have been following tutorials on Django, and I've found this works fine: views.py from django.shortcuts import render from django.views.generic.base import View class Home(View): def get(self, request, *args, **kwargs): context = {'message': 'Hello Django!'} return render(request, "index.html", context=context) index.html <p>{{message}}</p> But if I change index.html to read <p>{{message}} And more!</p> It will still render as "Hello Django!". Then I change context = {'message': 'Bye Django!'} in views.py, and get "Bye Django!". I tried stuff like {{message|safe}} and{%load_widget_tweaks %}` (after installing django-widget-twaks), but nothing worked. Could it be that I can only load things that aren't html tags from strings provided by context in the view? That seems completely insane... -
How to add url links arguments in a right way in Django/Jinja?
I have a dropdown list of countries. In each country there is a list of cities. When I click a country name in dropdown list, I want to take it to the list of cities which belong to that country. But it's taking me to a page with list of the countries instead of list of the cities in that country. You can see the website alive emeupci.com I tried to give argument inside of {% url 'users:cities' country.pk %} but I get Reverse for 'cities' with arguments '('',)' not found. 1 pattern(s) tried: ['accounts\\/cabinet\\/cities\\/(?P<pk>[0-9]+)\\/$'] error. Here is my views.py def countries(request): user = User.objects.all() country = Post.objects.all().order_by('country').distinct('country') context = { 'posts': country, 'user': user } return render(request, 'users/countries.html', context) def cities(request, pk): country = Post.objects.get(id=pk).country cities = Post.objects.filter(country=country).distinct('city') author = Post.objects.get(id=pk).author access_challenge_country = Country.objects.filter(access_challenge = True) context = { 'cities':cities, 'country':country, 'author':author, 'access_challenge_country': access_challenge_country } return render(request, 'users/cities.html', context) def address(request, pk): user = User.objects.all() city = Post.objects.get(id=pk).city address = Post.objects.filter(city=city) email = Post.objects.all() context = { 'user': user, 'address': address, 'city': city, } return render(request, 'users/address.html', context) def home(request): user = User.objects.all() cname = request.POST.get('dropdown1') city = Post.objects.all().distinct('city') country = Post.objects.values_list('country__name', flat=True).order_by('country__name').distinct() print(country) context = { 'country': country, … -
How to check a form field for a specific attribute in that field's m2m key
I have a form that allows the user to pick several vans (many-to-many relationship). Each van has a boolean attribute named "available". I want to only show the vans whose "available" attribute is set to "True". How do I do this in the forms.py file? I know that this could possibly be done in the template, but I did not want to create a new form-template with each individual field written out. I wanted to know if this functionality could be done in the forms.py file or in the class based view. I believe that doing it that way would be a bit cleaner. I've look into the validators but I don't think this is the way to go. Maybe I need to run a query set in the form file that checks the attribute before passing it to the form template? views.py def post(self, request): """Take in user data, clean it, and then post it to the database.""" form = self.form_class(request.POST) # pass in the user's data to that was submitted in form if form.is_valid(): trip = form.save(commit=False) # create an object so we can clean the data before saving it # now get the clean and normalize the … -
How can I use my own template with Django auth_views?
How to use my own template with Django auth_views form ? I am creating the option for users to change their passwords, and for this I am using Django auth_views, specifically PasswordChangeView (CBV). Django auth_views by default use the Django admin design template. How can I use my own template with only the form of auth_views? What I tried: I'm trying to set a template_name. But the auth_views form won't appear... Only the template I provide will load. urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('change-password/', auth_views.PasswordChangeView.as_view(template_name='settings/alterar_passwor d.html'), name="change-password"), ] Template <a href="{% url 'change-password' %}">Mudar a minha password</a> What I expect: I'm looking forward to use the form provided from auth_views, with the my own template, so I can avoid Django admin design for users. -
Problem to create radio choice form with django and bootstrap classes
I'm trying to create a form with radio button choices with Django. The website is designed in bootstrap 4 and for some reason, the buttons dissapear when the custom-control-input class is applied. I have started with a static template that is rendering perfectly. The code for these button groups is the following: <div class="form-group row"> <div class="col-sm-2">Sexo</div> <div class="col-sm-10"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="sexo1" name="sexoRadios"> <label class="custom-control-label" for="sexo1">Mujer</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="sexo2" name="sexoRadios"> <label class="custom-control-label" for="sexo2">Hombre</label> </div> </div> </div> To create the form in Django, I have added this lines to the forms.py file: sexo_choices=[('hombre','Hombre'), ('mujer','Mujer')] sexo = forms.ChoiceField(choices=sexo_choices, widget=forms.RadioSelect( attrs={'class':'custom-control-input'} )) This makes the radio buttons to dissapear for some reason. If I analyze the HTML created by django, it seems quite similar to the static web. <div class="form-group row"> <div class="col-sm-2">Sexo</div> <div class="col-sm-10"> <div class="custom-control custom-radio"> <label for="id_sexo_0"><input type="radio" name="sexo" value="hombre" class="custom-control-input" id="id_sexo_0" required>Hombre</label> </div> <div class="custom-control custom-radio"> <label for="id_sexo_1"><input type="radio" name="sexo" value="mujer" class="custom-control-input" id="id_sexo_1" required>Mujer</label> </div> </div> </div> However, when I inspect the object with Google Chrome, I observe that the input tag has the following CSS attributes: .custom-control-input { position: absolute; z-index: -1; opacity: 0; } If I remove the … -
Separate permissions for records in a table in Django Admin
Let's suppose I have different users in my Django project and a model such that each record belongs to a certain user. The users are supposed to have an access to Admin panel. class MyModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... Is there a standard way in Django to make any user list, create and edit ONLY HIS instances of MyModel in Admin panel, hiding the ones created by other users? -
What is the optimal way to store 100k daily database inserts in Django?
My problem is that Django inserts entries waaaaaaay too slow ( i didnt even time but it was more than 5 mins) for 100k entries from Pandas csv file. What i am doing is parsing csv file and then save those objects to postgresql in Django. It is going to be a daily cronjob with csv files differ for most of the entries(some can be duplicates from the previous days or owner could be the same) I haven't tried raw queries, but i dont think that would help much. and i am really stuck at this point honestly. apart from some iteration manipulations and making a generator, rather than iterator i can not somehow improve the time of insertions. class TrendType(models.Model): """ Описывает тип отчета (посты, видео, субъекты)""" TREND_TYPE = Choices('video', 'posts', 'owners') ## << mnemonic title = models.CharField(max_length=50) mnemonic = models.CharField(choices=TREND_TYPE, max_length=30) class TrendSource(models.Model): """ Источник отчета (файла) """ trend_type = models.ForeignKey(TrendType, on_delete=models.CASCADE) load_date = models.DateTimeField() filename = models.CharField(max_length=100) class TrendOwner(models.Model): """ Владелец данных (группа, юзер, и т.п.)""" TREND_OWNERS = Choices('group', 'user', '_') title = models.CharField(max_length=50) mnemonic = models.CharField(choices=TREND_OWNERS, max_length=30) class Owner(models.Model): """ Данные о владельце """ link = models.CharField(max_length=255) name = models.CharField(max_length=255) trend_type = models.ForeignKey(TrendType, on_delete=models.CASCADE) trend_owner = … -
Docker not finding my Django Celery worker module
I am trying to set up a periodic task in a Docker container with Django and Celery. I keep getting the following error when I run docker-compose up. I am doing docker build . first then docker-compose build worker_1 | Error: worker_1 | Unable to load celery application. worker_1 | The module core.worker.app was not found. worker_1 | weather-app_worker_1 exited with code 1 My folder tree is like this: C:. │ .gitignore │ checklist.txt │ docker-compose.yml │ Dockerfile │ env.env │ LICENSE │ README.md │ requirements.txt │ ├───.idea │ misc.xml │ modules.xml │ vcs.xml │ weather-app.iml │ workspace.xml │ └───app │ db.sqlite3 │ manage.py │ __init__.py │ ├───app │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ settings.cpython-37.pyc │ urls.cpython-37.pyc │ wsgi.cpython-37.pyc │ __init__.cpython-37.pyc │ ├───core │ │ admin.py │ │ apps.py │ │ models.py │ │ __init__.py │ │ │ ├───management │ │ │ ___init___.py │ │ │ │ │ └───commands │ │ │ wait_for_db.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ wait_for_db.cpython-37.pyc │ │ __init__.cpython-37.pyc │ │ │ ├───migrations │ │ │ 0001_initial.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ … -
How do I escape single quotes in a django-widget-tweaks's render_field tag?
I'm trying to use django-widget-tweaks to render the following form field: {% render_field profile_form.bio class+="form-control" id="bio" rows="3" oninput="showBtn('updateProfile')" %} Into this: <textarea class="form-control" id="bio" rows="3" oninput="showBtn('updateProfile')"></textarea> However, I'm getting a parsing error as Django is changing the single quotes in the widget into double quotes. The showBtn js function is as follows: // Shows a button given an id showBtn: function (selector) { let btn = document.getElementById(selector); btn.classList.remove("btn-hidden"); } The reason why I use django-widget-tweaks is to keep all html classes and attributes isolated in the templates. What I already tried: representing the single quote as text entity &#39;. It renders the template (no parsing error), but does't actually replace the ascii into quotes so the js is never triggered escaping with slashes using the safe templatetag using the autoescape templatetag For reference, here is the form model: # forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ["bio"] And the original model: # models.py class Profile(models.Model): """ Non-auth related user information about an user""" user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) -
Handling a model's save method using an atomic transaction in Django
The question is honestly pretty self-explanatory. I have 2 models which are related. It goes like this: from django.db import IntegrityError, transaction class Item(models.Model): total_score = models.IntegerField() def set_score(self): ... class Review(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) score = models.IntegerField() def save(self, *args, **kwargs): try: with transaction.atomic(): super(Review, self).save(*args, **kwargs) self.item.set_score() except IntegrityError: handle_exception() Basically, whenever a review is saved, its item's score is updated using the set_score() method. I put the whole thing in an atomic transaction because obviously, I don't want a review to update and the item's score to remain unuqdated. Thats like a breeding ground for potential bugs. Anyway, is the right way to do it? I feel like I have no way of testing this in my local server as it is impossible to create an error which saves the review but not update the score. Thanks. -
How can i show progress of a loop in python script that runs on clicking a button?
I'm using ajax to run a python script on clicking a button but I want to display progress of a loop in that python script.How can I achieve that? At present what my program does is that it alerts me when python script is finished.I want to show the progress meter on the same page meanwhile the script is running. -
fussing around with PGPy Version/header in messages
My Django app has users and those users again have a public-pgp-key field where they can save there public-key onto. Now my application uses beside google 2FA also the possibility to generate a pgp message with a one-time login key if the user has the corresponding private key setup on his account. This methode is working pretty well but im having security concerns about the version header that is getting displayed because this specific wrapper around gnupg >>PGP<< implants his version header again into the message that is getting display to the user and that again is pretty damn stupid because PGPy is only available for Python and users do not have to know what software my site is written with. Now im trying to find a way to somehow change the header of the encrypted message that is getting generated, currently it look like this: -----BEGIN PGP MESSAGE----- Version: PGPy v0.4.3 and it should be: -----BEGIN PGP MESSAGE----- Version: MyCustomVersionHeader views.py if 'encrypted_token' not in request.session: encryption_key = PGPKey.from_blob(user.pgpkey.rstrip("\r\n"))[0] encrypted_token = encryption_key.encrypt(PGPMessage.new(token_message), cipher=SymmetricKeyAlgorithm.AES256, ascii_header='Test123' ) for some reason also the ascii header gets ignored or im placing it wrong, this is the only thing i found at the documentation … -
TypeError at /vxml/InputData/33/18 'element_id' is an invalid keyword argument for this function
I get the following error and I can't seem to get it working: TypeError at /vxml/InputData/33/15 'element_id' is an invalid keyword argument for this function I assume it has something to do with def Input(request, element_id, session_id) in my view because that is the only place where element_id is in this view. I can't seem to find where the element_id is assigned. view: from django.shortcuts import render, get_object_or_404, get_list_or_404, redirect from ..models import * def input_get_redirect_url(input_element, session): return input_element.redirect.get_absolute_url(session) def input_generate_context(input_element, session): language = session.language redirect_url = input_get_redirect_url(input_element, session) ask_input_label = input_element.voice.label.ask_input_label_url(language) ask_confirmation_voice_label = input_element.ask_confirmation_voice_label.get_voice_fragment_url(language) final_voice_label = input_element.final_voice_label.get_voice_fragment_url(language) context = { 'InputData': input_element, 'redirect_url': redirect_url, 'voice_label' : voice_label, 'ask_input_label' : ask_input_label, 'ask_confirmation_voice_label' : ask_confirmation_voice_label, 'final_voice_label' : final_voice_label, } return context def Input(request, element_id, session_id): input_element = get_object_or_404(Record, pk=element_id) voice_service = input_element.service session = lookup_or_create_session(voice_service, session_id) if request.method == "POST": session = get_object_or_404(CallSession, pk=session_id) value = 'DTMF input' result = UserInput() result.session = session result.category = input_element.input_category result.save() return redirect(request.POST['redirect']) session.input_step(input_element) context = input_generate_context(input_element, session) context['url'] = request.get_full_path(False) return render(request, 'input.xml', context, content_type='text/xml') Urls.py: from django.conf.urls import url, include from . import views app_name= 'service-development' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^choice/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.choice, name='choice'), url(r'^message/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.message_presentation, name='message-presentation'), url(r'^start/(?P<voice_service_id>[0-9]+)$', views.voice_service_start, name='voice-service'), url(r'^start/(?P<voice_service_id>[0-9]+)/(?P<session_id>[0-9]+)$', … -
Django: using F() expressions on JSONField?
I have the model class Product(Model): properties = JSONField() When querying Product.objects.values('properties__color') i'm getting the correct result SELECT product.properties->color FROM product However, when I'm doing what I thought to be equivalent Product.objects.values(color=F('properties__color')) the query that's executed is completely different SELECT product.properties AS color FROM product Is this a bug of django's JSONField, or have I misunderstood F() expressions?