Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding Google allauth on Django live app deployed on Heroku
I am trying to add Google authentication to my live Django app deployed on Heroku. I have added www.example.com and example.com as Site objects and have added them to the list of Sites on the Social Application object in the admin interface on Heroku. However, now that I have both the root(example.com) and subdomain www I cannot add both Site id's in my settings. How can I set the Site id properly in the settings? Since I have now gettings an error: allauth.socialaccount.models.SocialApp.DoesNotExist: SocialApp matching query does not exist. and I get a 500 internal server error when I visit: http://www.example.com/accounts/google/login/ Is the root enough to be added as Site? -
Style is not applied with inlineformset. But works perfectly with simple form
I am able to style the form(view update_order) with widgets in forms. But in inlineformset_factory(create_order) I am facing issues. The widget in not working for inlineformset_factory. https://hastebin.com/mapuliyaxu.cs -
How to create users and groups migrations in Django?
So I've got an API built in Django with Django Rest Framework and I now want to add a role based access control to it. For this I found the django-rest-framework-roles extension. I've got it installed, but I'm not really familiar with the usual authentication system in Django. It says I need to define the groups in the settings as ROLE_GROUPS = [group.name.lower() for group in Group.objects.all()] So I need the Group model and of course also the User model. As far as I understand, these are standard models. However, I don't have any tables in my DB for them. So I need a migration for it, but I'm unsure how I can do that. I guess it should be really easy, but even on the relevant pages in the documentation I don't see any mention on how to add these models to my Django installation. Could anybody enlighten me on this? -
Django form validation for checking uniqueness of record before submitting
I have database table columns like: | FPB_Code | Transaction_Date | Ministry_Code | Created_Date | Created_By | Modified_Date | Modified_By | I have created a form using Django and before submitting the form, I want to check whether records matching from (|FPB_Code | Transaction_Date | Ministry_Code| ) exists or not? Please help. -
ModelChoiceField in Django is not rendered
I'm desperately looking for a solution to following problem: I got a very simple form with one model choice field: from django import forms from django.contrib.auth.models import User class MyForm(forms.Form): my_field = forms.ModelChoiceField(queryset=User.objects.filter(is_superuser=False),widget=forms.Select()) The form is passed to a view and HTML file: <form method = "GET"> {{ form }} <input type = "submit" value = "Submit"> </form> The rendered HTML looks exactly as expected: <form method="GET"> <label for="id_my_field">My field:</label><select name="my_field" required="" id="id_my_field"> <option value="" selected="">---------</option> <option value="2">test1</option> <option value="3">test2</option> </select> <input type="submit" value="Submit"> </form> Still the result in the browser is not as expected: I played around with the widgets attributes for a while, but I still can not figure out why my the options are not rendered. Thanks in advance! -
Python list comprehension Django objects
I am developing a dictionary Django app where Definitions have Tags. I have written this generic function to collect all Tags from a list of Definitions. This is my current working version: def get_tags(definitions): tags = [] for d in definitions: tags += d.tags.all() return tags I was trying to accomplish the same using Python's list comprehension: tags = [] return [tags.extend(d.tags.all()) for d in definitions] This code however does not work yet. What am I missing? Is there an even slicker way to do this in just one line without creating the tags variable, perhaps using yield statement? -
Import Error DJANGO PYTHON - Error Message: 'Unable to import 'rest_framework_simplejwt.tokens'
I have already seen this [link][1] which describes a similar issue but it seems that all the suggested solutions can't help me. This is the error message I get: Unable to import 'rest_framework_simplejwt.tokens' This is the command I use: from rest_framework_simplejwt.tokens import RefreshToken I have also inserted this code in my settings.py file: REST_FRAMEWORK = { 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } The documentation says that the Requirements are: Python (3.6, 3.7, 3.8) Django (2.0, 2.1, 2.2, 3.0) Django REST Framework (3.8, 3.9, 3.10) My System when I do pip freeze: argon2-cffi==20.1.0 asgiref==3.2.10 bcrypt==3.2.0 cffi==1.14.2 Django==3.0 djangorestframework==3.10.0 djangorestframework-simplejwt==4.4.0 psycopg2==2.8.6 pycparser==2.20 PyJWT==1.7.1 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 My version of python: Python 3.6.4 :: Anaconda, Inc. Do you have any idea how to fix it? -
Django filter queryset. Need to get all jobs which require at least one skill from list skills
#I have a list of skills skills = p.skill_info #Also in Jobs I have the list of all jobs now I need to get all jobs which contain at least one skill from the skills list. jobs = Job.objects.filter(job_requirements__in=skills) I am doing something like this, what am I doing wrong ? -
Django Admin Related [closed]
Anyone here Django Developer who creates a custom Admin panel from Scratch(does not use Django admin panel). Fully features like sidebar and charts and Some Tables. Please help me with the project. -
how Count() works in django
I can get the count of a foreign key relationship for each row using django.db.models.Count like below from django.db.models import Count Publisher.objects.annotate(num_books=Count('book')) but the Count() function is weird for me and I think it works like magic, can you explain how it works? I read this page but I don't found anything related to my question https://docs.djangoproject.com/en/3.1/topics/db/aggregation/ and I tried to print Count() print(Count("book")) //Count(F(book)) and I don't understand this too -
Excluding the Data of Child Class Model From The Super Class Model in Django
I have some models like this: class Super(models.Model): attr1 = ... attr2 = ... class Child(Super): child_attr1 = ... child_attr2 = ... Now I when I do Child.objects.all(), it gives child objects only. However, when I do Super.objects.all(), it gives all the super and child objects. Is there a queryset like Super.objects.exclude(...) which I can use to get the objects of Super class model only? -
Allauth signup customization
Hello everybody i was exploring a way to create a good registration and login system and i found the allauth lib that was very good in configurations and had many good sides. The question is how can i customizate the signup page because i have many fields in the registration form and i don't found a way to use my own design and add more fields i have searched in google in youtube and stackoverflow but nothing was helping and everybody was adding a boostrap design and that was all ( i will very thankfull if anybody will show me a way, sorry for my bad literature. -
django - rest framework response content negotiation not happening
I upgraded djangorestframework from version 3.2.5 to version 3.5.3. Since then response content negotiation (not sure if term is correct) is not happening. Sample code: serializer = SessionSerializer(active_sessions, many=True) print(serializer.data) response = Response(serializer.data) print(response.data) Output when using version 3.2.5 {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"count": 1, "previous": null, "results": [{"session_id": "16a635d0-0f7a-4366-b648-a907ea4f4692"}]} Output when using 3.5.3 {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} I am using below rendered 'DEFAULT_RENDERER_CLASSES': ( 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', ), I tried a lot of things, but nothing seems to work. -
How to go about creating a paint app in Django [closed]
I wanted to create a paint app in Django. Can someone guide me through the steps I need to go through to achieve this. Thanks! -
Is it possible to show only a certial fields when using django-material forms
{% form form=form %}{% endform %} this thing renders the complete form https://pypi.org/project/django-material/0.5.1/ -
Django/PostgreSQL custom TimeRangeField
I'm trying to create a TimeRangeField but am having some problems saving to the database (PostgreSQL version 9.5.23). from psycopg2.extras import DateTimeRange from django import forms from django.contrib.postgres.forms import BaseRangeField from django.contrib.postgres.fields.ranges import RangeField from django.db import models class TimeRangeFormField(BaseRangeField): default_error_messages = {'invalid': 'Enter two valid times.'} base_field = forms.TimeField range_type = DateTimeRange class TimeRangeField(RangeField): base_field = models.TimeField range_type = DateTimeRange form_field = TimeRangeFormField def db_type(self, connection): return 'tsrange' The error when saving seems pretty self explanatory - pretty sure I need to cast the time object to a string but I have no idea how to do that. function tsrange(time without time zone, time without time zone, unknown) does not exist LINE 1: ...('b9925dd3-d4a8-4914-8e85-7380d9a33de5'::uuid, 1, tsrange('1... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. -
Django admin misbehaves after adding for django.contrib.sites on server
Django Admin Site was working fine on local server. But the same thing when deployed on server. Admin CSS misbehaves See Screenshot Admin panel screenshot on server admin panel site also working fine on mobile responsive view or small screens On localhost it looks something like this. I have ran collect static several times on server but nothing happens. Tried Clearing Cache many time. Nothing worked But localhost seems to work fine -
no such table: Append_employeemodel Django
GitHub repository When I send a post request I get this. I previously try python manage.py syncdb ./manage.py migrate python manage.py migrate python manage.py createsuperuser python manage.py makemigrations python manage.py migrate but I still got an error. The Git Hub link is above please help me. -
Django Form Validation : shows enter a valid date but the date given is correct
I'm working in a project where i've to implement Nepali calender. The calender is working fine but django validation does not accept the date. The date selected is valid according to BS (Bikram Sambat) calender but it is not valid as per AD calender. If i choose the date upto 2077-04-30 it works fine but it does not accept 31 and 32 on 4th month. There are 32 days on 4th month of BS calender. How can i make django accept this date? Any suggestion is highly appreciated. Thanks. -
Multiple user types Django + React
I am currently planning out an application that I plan to build with Django (backend) and React (frontend). Where I am currently hitting a roadblock is the implementation of multiple user types. I am choosing Django as the backend for the sake of the fact that it will handle authentication, session management, etc.. I'd like to create an API to pull the information to the frontend which I will be using the django-rest-framework to do so. User types: Company - Company will fulfill orders - Company can have multiple Clients Client - Client will submit orders - Client can have multiple Company's to submit orders to There is no need for users to switch between accounts, and I would like to do away with the the default username and implement email to login/register. Thanks for your input -
How to manually render formset form select choices as radio button
I'm trying to manually render my form choices in a formset as radio buttons. I think I've got close to the right idea, but I'm somehow missing something with the values set in the input tag. This is a solution that seems to fit my needs better than using {{ form.as_p }}, because I'm zipping a formset and a list and displaying both simultaneously. I'm really hoping to have the input tag's syntax correct, but I'm not sure what I'm missing. <div class="" style="flex-wrap: wrap; display: flex;"> {{ formset.management_form }} {% for form in formset %} {% csrf_token %} <div class="col "> <table style="border-radius: 21px;"> <p style="font-weight: 500;" class="question-text"> </p> <tr class="bubbles"> <td class="bubble-text-left">Not interested&nbsp;</td> {% for choice in form.value %} <td> <label class="container"> <input type="radio" name="{{ form.value.choice.name }}" value="{{ form.value.choice.0 }}" id='{{ form.value.choice.auto_id }}' class="{{ radio_input.choice_value }}"> <span class="checkmark"></span> </label> </td> {% endfor %} <td class="bubble-text-right">Very interested</td> </tr> </table> <br> </div> {{ form.id }} {{ form.question }} {% endfor %} </div> -
Creating more than 1 html files on public directory
I want to use React with Django. For this, i thinked this structure: Project |_ back-end (django) |_ front-end (builded react) |_ index.html |_ about.html |_ contact.html |_ <other files and bundles> But i can create only index.html. I dont know how can i create other html files on react, for use with django. -
how to display registered image on django ImageField
I need to make a custom ImageField with django. with dropify.js, I could make drag & drop image field but I need to display current image when it has image already (when user need update the image file after create a post once) dropify has attribute named "data-default-file" so I am trying to modify my forms.py as below. Please kindly guide me to input the image's url when it has the image... thanks in advance! Forms.py ... from django import forms from django.forms import ModelForm from shop.models import Product from event.models import * class ProductRegisterForm(forms.ModelForm): detailVN = forms.ImageField(label='Detail(VN)', widget=forms.FileInput(attrs={ 'id':'detailVN', if it has image: 'data-default-file': image-url })) Models.py class Product(models.Model): ... detailVN = ProcessedImageField(upload_to = img_path, processors=[ResizeToFit(width=1150, upscale=False)], format='JPEG', options={'quality':90}, blank=True, null=True, ) -
libscca-python failed on jenkins build
I have django app try to build it on Jenkins, However when it reaches Install pip dependencies stage it fails because of libscca-python library. I got long error but I will paste here what I think it may help on finding the issue: Building wheels for collected packages: libscca-python Building wheel for libscca-python (setup.py): started Building wheel for libscca-python (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /home/jenkins/agent/workspace/SI_backend_develop/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-e6l9je1l/libscca-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-e6l9je1l/libscca-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-pwlznjn1 cwd: /tmp/pip-install-e6l9je1l/libscca-python/ from common/types.h:34, from pyscca/pyscca_integer.c:23: /usr/include/fortify/string.h:144:1: error: 'mempcpy' undeclared here (not in a function); did you mean 'memccpy'? 144 | _FORTIFY_FN(mempcpy) void *mempcpy(void *__d, const void *__s, size_t __n) | ^~~~~~~~~~~ /usr/include/fortify/string.h:145: confused by earlier errors, bailing out error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /home/jenkins/agent/workspace/SI_backend_develop/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-e6l9je1l/libscca-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-e6l9je1l/libscca-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-e7hsbwat/install-record.txt --single-version-externally-managed --compile --install I'm totally new to devOps, your help is appreciated! -
How to use @property in models choices?
My model: **class SomeModel(models.Model): ... models.CharField(max_length=255, choices=BookPage.choices)** My choices: from enum import Enum class BookPage(Enum): MAIN = "Main" SIDEBAR = "Sidebar" @property def choices(self): return [(key.value, key.name) for key in self] I got this error Where I'm wrong? choices' must be an iterable (e.g., a list or tuple).