Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle keys of JsonField in Django?
I have a model with a JsonField called "settings". If I want to add a new "field" (key) or get the value of the "field" I have to write the following: # save instance.settings['color'] = 'red' instance.save() # get value instance.settings['color'] I don't like this because of the "hard-coded" color string. Is there a good approach to handle the keys of a JsonField? Should I use something like this or is there a better solution: # settings (settings.py file) COLOR = 'color' # save instance.settings[COLOR] = 'red' instance.save() # get value instance.settings[COLOR] -
Can the vuejs filter syntax be changed to work with Django?
I changed the delimiters from the mustache syntax but I also have a view filter which uses the | character. Django thinks this is for a Django filter. I'd like to use the vuejs filter I created but I can't use the | character with Django. What is the typical way to handle this? -
Django and Postgres: Relation Does not exist
Here is the exact error I am getting: django.db.utils.ProgrammingError: relation "blog_blogtype" does not exist LINE 1: ..."blog_blogtype"."id", "blog_blogtype"."type" FROM "blog_blog... I have created the tables in a database in Postgres but when I try to migrate Django returns this error. My models are below. I created the column referencing to the BlogType model "type" column. I do not know what else to put here. If needed please comment it, so I can add. Thank you in advance. class BlogType(models.Model): id = models.AutoField(primary_key=True) type = models.CharField(max_length=100) def __str__(self): return self.type class BlogPost(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) post_body = models.TextField() time = models.DateTimeField() category = models.ForeignKey(BlogType, related_name="type", on_delete=models.CASCADE) def __str__(self): return self.title -
Django Ajax onclick button not functioning
this seems like it should be pretty simple, but I'm not sure what's going on. My ajax function code is: <script> function toggleLike(){ $.ajax({ url: "{% url 'photo_blog-post_like_api' post.id %}", }); } </script> and my button code is: <input type="button" onclick="toggleLike()" value="Like" /> The url in the function should load the Rest API which toggles the liked boolean, but somethings not right. When I go to the url in my browser, the Rest API functions correctly. Thanks! -
Django - ReactJS - OAuth2
I'm currently working on an app with Django backend and react frontend. I need to authenticate the user with an external app using oAuth2 and find it hard to get a clean looking url after being redirected back to the app after authenticating with oAuth2. The url looks like this after the redirect: http://127.0.0.1:8000/?state=&code=thelongcoderetrievedfromoathusedtogettoken&scope=#/ I'm unable to redirect back to http://127.0.0.1:8000/ from the frontend (React). It seems that I cannot touch anything behind the # My idea is then: To create another landingpage which is passed with the oAuth2 redirect paramter then. In the backend I create a new view and retrieve the code and pass to the original view. Pass the data from the backen to the frontend. My solution to this problem is: Just add /landingpage to the url passed to oAuth2. Is quite easily handled by creating a new view where we store the token in a session: views.py: def landingpage(request): request.session['auth_token']=request.GET.get('code') return redirect('homepage') urls.py: urlpatterns = [ path(r'', views.index,name='homepage' ), path(r'landingpage/', views.landingpage,name='landing-redirect' ), ] This is also quite simple once we have the token in a session. In the orignal view we can pass the token to the index.html file or wherever we import the react … -
Distinct values from AddressChainedSelect2WidgetForm using django_select2
I am using select2 for my dropdown. I am using AddressChainedSelect2WidgetForm. I have declared the following class in myapp/forms.py class AddressChainedSelect2WidgetForm(forms.Form): city= forms.ModelChoiceField( label='machine', queryset=City.objects.all().distinct(), widget=ModelSelect2Widget( model=City, search_fields=['city__icontains'], attrs={'data-placeholder': 'Select city...'}, ) ) However I am not able to get distinct(unique) values form the dropdown widget? -
Serializing an object with OneToOneField
I am trying to send my Scenes object with the context dictionary over to a template. These are the models: class Scene1(models.Model): timestamp = models.DateTimeField(auto_now_add=True) number = models.IntegerField(default=0) name = models.CharField(max_length=20) class Scene2(models.Model): timestamp = models.DateTimeField(auto_now_add=True) number = models.IntegerField(default=0) name = models.CharField(max_length=20) class Scenes(models.Model): scene1 = models.OneToOneField(Scene1, on_delete=models.CASCADE) scene2 = models.OneToOneField(Scene2, on_delete=models.CASCADE) When I do queryset = Scenes.objects.filter(id=1).values() context = {"scenes": queryset[0]} print(queryset) I get: <QuerySet [{'id': 1, 'scene1_id': 3, 'scene2_id': 3,}]> How would I serialize the data to make all the information in Scene1 and Scene2 visible in the context dictionary? -
Ordering Django queryset using attributes of a JSONField, provided the attribute is not present everywhere
This is a very complex question, so let me explain. I have a model called Person which stores most of its data in a JSONField. class Person(models.Model): data = JSONField() Now, the data field is usually in the the following format: {"name" : <String>, "age" : <int>} Now, what I want to do is create a queryset of Person, that orders the objects using the age attribute from its data field, in descending order. This is solved using the following code: from django.db.models.expressions import RawSQL from .models import Person qs = Person.objects.annotate(age=RawSQL("(data->>'age')::int", [])).order_by('-age') This is great, and works well. However, during testing, I changed the data attribute of one Person object to something like this: {"name" : <String>, "profession" : <String>} That is, this object does not have the age attribute, within its data field. Now when I run the query above, it still works fine, but this object (the one without age attribute), is at the very top. This is because of one of two reasons: Since its age is null, its get sent to the top because of the descending order_by call. Its the object I last created, so it was always at the beginning, but because it … -
How can I create a two-sided marketplace with Django Oscar?
I have been reading and re-reading django-oscar's documentation but I cannot find much information in it about how to create a two-sided marketplace. People have asked about this before: https://github.com/django-oscar/django-oscar/issues/2403 I have also looked through their Google group, but could not find much recent about it. I saw this information in Version 0.6 of the documentation, but we are now at Version 1.6 and the information does not exist in Version 1.6: https://django-oscar.readthedocs.io/en/releases-0.6/howto/multi_dealer_setup.html -
RESTful api from function based views to class based views django rest framework
I was following along with this tutorial here: https://realpython.com/test-driven-development-of-a-django-restful-api/ I have set everything up and the API endpoints are working as expected: When I call: localhost/api/v1/puppies/ returned: { "name": "Bridgett", "age": 3, "breed": "Boxer", "color": "White", "created_at": "2018-10-03T17:28:21.333893Z", "updated_at": "2018-10-03T17:34:13.899385Z" }, { "name": "Mia", "age": 3, "breed": "Mix", "color": "Black", "created_at": "2018-10-09T16:08:59.775685Z", "updated_at": "2018-10-09T16:08:59.775685Z" } Also the main issue which is the Detail view works as well... If I call: localhost/api/v1/puppies/2 returns: { "name": "Bridgett", "age": 3, "breed": "Boxer", "color": "White", "created_at": "2018-10-03T17:28:21.333893Z", "updated_at": "2018-10-03T17:34:13.899385Z" } Which is great and all of my put post delete works as well here is the code: models.py: # models.py from django.db import models class Puppy(models.Model): """ Puppy Model Defines the attributes of a puppy """ name = models.CharField(max_length=255) age = models.IntegerField() breed = models.CharField(max_length=255) color = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_breed(self): return self.name + ' belongs to ' + self.breed + ' breed.' def __repr__(self): return self.name + ' is added.' serializers.py # serializers.py from rest_framework import serializers from .models import Puppy class PuppySerializer(serializers.ModelSerializer): class Meta: model = Puppy fields = ('name', 'age', 'breed', 'color', 'created_at', 'updated_at') views.py from django.shortcuts import render from rest_framework.decorators import … -
Django reverse lookup foreign keys with multiple conditions
I am trying to do a reverse lookup in Django with multiple conditions, hopefully, my question does not duplicate with other questions. Let me explain: I have two models: Model A: class A(models.Model): title = models.CharField(max_length=200) ... other fields Model B: class B(models.Model): a = models.ForeignKey(A) label = models.CharField(max_length=200) value = models.CharField(max_length=200) ... other fields How can I get A that: 1) has a B with label = name, value=John 2) and, has a B with label =age, value =20 I tried the following, it does not work: A.objects.filter(b__label="name", b__value="John", b__label="age", b__value=20) -
Add one object to M2M fields of many objects in a bulk transaction
I've got the following post_save signal. @receiver(post_save, sender=Questionnaire) def add_new_eligible_users_to_questionnaire(sender, instance, created, **kwargs): if created: if instance.open_to_all: users = Respondent.objects.filter(organization=instance.organization) users.update(eligible_for=instance) The idea is that once the survey is created, if it is open to everyone, it will automatically be added to their eligible_for row. Unfortunately, update() doesn't work on M2M relationships. Is there any way I can do this in one fell swoop? -
Django Channels and Autobahn
This is more of a architecture question. I have a python server that broadcasts a json packet using Autobahn. I have developed other scripts to listen and grab the data and use it for various reasons. Now I have a Django application that needs this data to populate data on its templates asynchronously. Is it possible to set up Channels to listen in on the python server's broadcast, and route the data? Or would I need a broker like Redis to grab the data and pass it to the Django Applicaiton. I have setup Channels, and most of the resources I have read usually points towards the direction of using Redis. -
How to get the created objects count in django inline formset
I'm using inlineformset_factory to create multiple objects. I've override access to form_valid method as follows. def form_valid(self, form): context_data = self.get_context_data() price_list = context_data['price_list'] # price objects with transaction.atomic(): if price_list.is_valid(): self.object = form.save() price_list.instance = self.object price_list.save() # need to get count here else: return self.render_to_response(context_data) return super(CategoryCreate, self).form_valid(form) How do I get the saved (created price objects) count after/before save() method? -
django use of templates views and ajax
Sorry I couldn't come with a more precise topic title and I must admit I'm still pretty new Django. I am trying to work with Ajax and templates with splitted views but I can't achieve what I want, one way or another. My goal is to be able to work with rendered templates and jquery hide/show instructions but I'm failing at some point. Here is my urls.py: from django.urls import path from django.conf.urls import url from . import views, inventory urlpatterns = [ path('', views.index, name='index'), url(r'^inventory', inventory.inventory, name='inventory'), url(r'^buildInventory', inventory.buildInventory, name='buildInventory'), ] My views index renders a templated "index.html" (there is a context that I removed for the illustration): def index(request): return render(request, 'myapp/index.html', context) My index.html file : {% extends "base.html" %} {% load static %} {% block delivery_form %} <div id="mainblock"> .... </div> {% endblock %} And my base.html mostly contains my statics & headers: {% load static %} <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="shortcut icon" type="image/png" href="http://web-iec/favicon.ico"/> <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/nice.css' %}"> <script type="text/javascript" src="{% static 'myapp/js/jquery.js' %}" ></script> <script type="text/javascript" src="{% static 'myapp/js/jquery-ui.js' %}" ></script> <script type="text/javascript" src="{% static 'myapp/js/inventory.js' %}" ></script> <script type="text/javascript" src="{% static … -
Django xlwt : issue with xls file
I'm trying to use xlwt library in order to export result from my Django queryset to xls file format. The process seems to work, but each time, I'm creating an xls file with 5.6 ko weight. And each time I would like to open the exported file, I'm getting this windows issue : An error occurred while sending a command to the program This is my function : def export_categories_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="categories.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Categories') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['id', 'name', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Category.objects.all().values_list('id', 'name') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response To my mind, my code is correct, butit still remains this issue and I don't overcome to open my xls file. -
Custom renderer breaking site
I'm new to the DJango world, having just started up my first Python job a few months ago (PHP dev for the last decade). I'm working with Django REST API on an endpoint where I need to return an XML string, but from looking around, seems like none of the built in renderers allow you to simply pass a string to be returned as is? I saw that `HTTPResponse` works, but `Response` doesn't, and a coworker told me that `Response` is a better choice and to create a renderer. I thought it seemed pretty simple based on source code, with basically this being the bare minimum: class PassThroughRenderer(BaseRenderer): media_type = None format = None def render(self, data, accepted_media_type=None, renderer_context=None): return data Unfortunately, when I run that (having added renderer_classes = (utils.PassThroughRenderer,) to my APIView class), I get 'Request' object has no attribute 'accepted_renderer' and a traceback that doesn't seem to hit any code I've written. I'm hoping someone may be able to help me figure out where I've gone wrong? -
Unable to install channels (django) using pipenv
When I attempt to install django channels using pipenv, it fails, purportedly because it cannot find "zope-interface" version 4.5.0 in https://pypi.python.org/simple. $ pipenv install channels Installing channels… Looking in indexes: https://pypi.python.org/simple Collecting channels Using cached https://files.pythonhosted.org/packages/e3/ea/65e947afe102b1b5798f6890479426e8f481df0ec7a4cbba21bdd2897ef9/channels-2.1.3-py2.py3-none-any.whl Requirement already satisfied, skipping upgrade: Django>=1.11 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from channels) (2.1.2) Requirement already satisfied, skipping upgrade: asgiref~=2.3 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from channels) (2.3.2) Requirement already satisfied, skipping upgrade: daphne~=2.2 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from channels) (2.2.2) Requirement already satisfied, skipping upgrade: pytz in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from Django>=1.11->channels) (2018.5) Requirement already satisfied, skipping upgrade: async-timeout<4.0,>=2.0 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from asgiref~=2.3->channels) (3.0.1) Requirement already satisfied, skipping upgrade: autobahn>=0.18 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from daphne~=2.2->channels) (18.9.2) Requirement already satisfied, skipping upgrade: twisted>=18.7 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from daphne~=2.2->channels) (18.7.0) Requirement already satisfied, skipping upgrade: txaio>=18.8.1 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from autobahn>=0.18->daphne~=2.2->channels) (18.8.1) Requirement already satisfied, skipping upgrade: six>=1.11.0 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from autobahn>=0.18->daphne~=2.2->channels) (1.11.0) Requirement already satisfied, skipping upgrade: PyHamcrest>=1.9.0 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from twisted>=18.7->daphne~=2.2->channels) (1.9.0) Requirement already satisfied, skipping upgrade: zope.interface>=4.4.2 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from twisted>=18.7->daphne~=2.2->channels) (4.5.0) Requirement already satisfied, skipping upgrade: hyperlink>=17.1.1 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from twisted>=18.7->daphne~=2.2->channels) (18.0.0) Requirement already satisfied, skipping upgrade: attrs>=17.4.0 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from twisted>=18.7->daphne~=2.2->channels) (18.2.0) Requirement already satisfied, skipping upgrade: incremental>=16.10.1 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from twisted>=18.7->daphne~=2.2->channels) (17.5.0) Requirement already satisfied, skipping upgrade: Automat>=0.3.0 in /home/dan/.local/share/virtualenvs/gmtools-QMaEj5K6/lib/python3.6/site-packages (from twisted>=18.7->daphne~=2.2->channels) … -
ImportError at / No module name ___ even though requirement satisfied
I'm runnning a django app and getting this error: ImportError at / No module named svglib.svglib my code for importing this is: from svglib.svglib import svg2rlg when I run pip list I see that I have svglib (0.8.1) installed already. Is this due to the import being in parent.file format? What is work around here? -
How to display user_list in a indented line from the server in Django?
I have a problem I have a site which displays users but it displays users not in a straight line but in an inverted pyramid. It could be because I am using django-filter app but it shouldnt create a problem as such. The profiles right at the end (especially in the mobile view) overlap and drag. It gets worse as profiles increase. Is it possible to align the profiles or user list in a straight line? Please find below my code. filters.py(for djang-filters app) import django_filters from userprofile.models import UserProfiles class UserProfilesFilter(django_filters.FilterSet): class Meta: model = UserProfiles fields = ['gender', 'age', 'Nationality','preference', 'Country', 'City'] views.py @login_required def profiles_list(request): filter = UserProfilesFilter(request.GET, queryset = UserProfiles.objects.all().order_by('-pub_date')) return render(request,"userprofile/user_list.html", {'filter': filter}) user_list.html {% extends 'base.html' %} {% block content %} {% load static %} {% load bootstrap %} <div class="container"> <form class="form-horizontal col-md-4 col-lg-4 col-sm-4" action="" method="get"> {{ filter.form|bootstrap}} {% csrf_token %} <input type="submit" value='search'/> </form> {% for profile in filter.qs %} <div class="col-md-12 col-lg-12 col-sm-12 col-xs-12"> <hr> <a href="{% url 'userprofile:profileview' profile.user %}"><h3>{{ profile.user }}</h3></a> <br> <img src="{{ profile.image.url }}" class="rounded mx-auto d-block img- responsive float-left" style= "max-height: 100px; max-width: 100px;"> <br><br> <br><br> <br> <div class="font-weight-normal text-justify"> Gender: {{ profile.gender }} <br> … -
Combining and slicing 2 querysets before hitting the database in Django
I am trying to get a queryset from mergeing two querysets. The conditions are as follows: Pull only 20 items Hit the database only once Lets say I have a model called MyModel, with a field called value which stores integers, however, the value can be null. I know querysets in Django are lazy, but Im not sure if the conditions are being met in the following line of code. qs = MyModel.objects.exclude(value__isnull=True).filter(value__gte=250).order_by('-value') | MyModel.objects.exclude(value__isnull=False) objects = qs[:20] Basically, I am filtering out first where the value is not null, ordering them according to value, and then at the end, I am adding the ones excluded at the very end. Is this meeting my conditions? That is, is the database being hit once? Moreover, is there a better way to do this without the | operator? Note: I know this can be done without merging querysets, but for the sake of this question, lets assume that having 2 querysets like this is absolutely necessary. -
How to create a validator for special characters in DJANGO?
my site is live but it has a problem. Whenever someone signs up with a special character in their username then the server gives an error (for the entire site) as the slug cannot display special characters such as @,-,| but django user model lets users sign up with special characters. Is there a way I can throw in a validator error in my signup form. below is my forms.py from django.contrib.auth.models import User from django import forms from captcha.fields import CaptchaField class SignUpForm(forms.ModelForm): captcha = CaptchaField() password = forms.CharField(max_length= 15, widget=forms.PasswordInput) def clean_username(self): data = self.cleaned_data['username'] if not data.islower(): raise forms.ValidationError("Usernames should be in lowercase") return data class Meta: model = User help_texts = { 'username': 'Required. Please only use lower-case alphabets and numbers.', } fields = ['username', 'email', 'password'] views.py class SignUpFormView(View): form_class = SignUpForm template_name = 'home/signup.html' #if there is no sign up yet def get(self,request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) #if going to sig up def post(self,request): form = self.form_class(request.POST) if form.is_valid(): #it takes information but does save it user = form.save(commit = False) #cleaned normalized data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns if it is all correct user = … -
Django Template Complex Reverse Query Count
I have this model where a supervisor is a foreign key for a team, which is a foreign key for an individual employee. model.py class Supervisor(models.Model): [fields..] class Team(models.Model): shift = ... department = ... supervisor = models.ForeignKey(Supervisor, related_name="team_supervisor") class Employee(models.Model): [fields...] team = models.ForeignKey(Team, related_name="employee_team") In using the Supervisor model in a view, and while looping through each supervisor I can list how many teams a supervisor manages with the statement: {{ supervisor.team_supervisor.count }} How can I show the total number of individual employees that work for a supervisor across every team that supervisor has? I assumed the follow would work but it does not: {{ supervisor.team_supervisor.employee_team.count }} -
Sending JavaScript Array or Object to Django View
I am trying to send via AJAX an array (or object) to my Django View. In JS File: var dataArr = []; dataArr.push({'status':'active'}); ... var json = JSON.stringify(dataArr); ... $.ajax({ type: "POST", url: "/filter/", data: { 'filter_text' : json, 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: filterSuccess, dataType: 'json', contentType: 'application/json' }); I am getting a 403 Forbidden error in Javascript. I tried several things, e.g. omitting the dataType / contentType, sending a Javascript object instead of an array, etc. -
Django formwizard overriding get_context_data
my template: {{ formset.management_form }} {% for form in formset %} <div class="form-row formset"> {{ form.as_p }} </div> {% endfor %} my view: class ResumeWizard(LoginRequiredMixin, SessionWizardView): login_url = '/login/' def get_context_data(self, form, **kwargs): data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '5', 'form-MAX_NUM_FORMS': '5', } SkillFormSet = formset_factory(SkillForm) formset = SkillFormSet(data) context = super(ResumeWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'skills': context.update({'formset': formset}) return context Hi, I'm trying to override get_context_data in my Wizard (extends SessionWizardView) so I can show a formset in a particular step. How can I insert my formset into the wizard.form.forms so the form wizard may work correctly? Or how can I get the wizard.form.management_form to recognize my formset? I am aware my solution will not work and I can't seem to find the answers anywhere. Any help would be much appreciated. Thank you