Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting DB index on Redis Django
I am using Redis as my caching server on Heroku, Django. However, when I page loads I get and error: redis.exceptions.ResponseError: invalid DB index My Redis setting is: CACHES = { 'default': { 'BACKEND': "redis_cache.RedisCache", 'LOCATION': os.environ.get('REDISTOGO_URL', 'redis://127.0.0.1:6379'), "OPTIONS": { "CLIENT_CLASS": "redis_cache.client.DefaultClient", } } } Shouldn't the DB index be 0 by default? How can I set the DB index correctly? I have the same settings locally and I do not get this error. Thanks for all the help in advance! -
JavaScript function doesn't work in form loop
JavaScript work only in first iteration, doesn't affect on the field from second iteration. forloop Code Sample {% for i in userlist %} <input id="a{{i.email}}" type="email" value="{{i.email}}"> <input id="b{{i.email}}" type="text" value="{{i.date_of_birth}}"> <input id="c{{i.email}}" type="text" value="{{i.mobile}}"> {% endfor %} Button for disable editing <button onclick="disableProfileEditing()" type="button"> Disable </button> Button for enable editing <button onclick="enableProfileEditing()"> Edit</button> JavaScript function function disableProfileEditing() { var a=document.getElementById("a{{i.email}}"); var b=document.getElementById("b{{i.email}}"); var c=document.getElementById("c{{i.email}}"); document.getElementById(a).disabled = true; document.getElementById(b).disabled = true; document.getElementById(c).disabled = true; } function disableProfileEditing() { var a=document.getElementById("a{{i.email}}"); var b=document.getElementById("b{{i.email}}"); var c=document.getElementById("c{{i.email}}"); document.getElementById(a).disabled = false; document.getElementById(b).disabled = false; document.getElementById(c).disabled = false; } -
Where to place Telegram bot code in my Django app? And how to run it with separate container or a part of Django?
I have Django app and my Telegram bot which interacts with ORM models. Bot can work in two ways: longpooling and webhook. Where to place the code of this bot: In separate Djnago app or in separate folder in the same level as Django place. And how to Run it? As new Docker container with all same dependencies and requirements.txt with Djnago (to have microservices arhitecture but dependencies duplicates) or as a part of django app? How to do this. Please help with best practicies! Thanks -
Discuss Implementation For Marketplace Website In Django
I am building a marketplace website for old mobile phones. I will be building it using django stack. I have figured out the other modules, but am stuck with payment integration for the website.(since I am quite Noob in payments field) I read about PayPal & Stripe integrations in django, but am little doubtful on how to implement these services for my website scenario. Here's the scenario:- Website will have Buyers & Sellers. Buyers - who will buy mobile phones. Sellers - who want to sell mobile phones. Each seller - will have payment details to receive payments (these can be either a paypal ID/ stripe ID) Buyers will need to checkout throut debit cards, credit cards, paypal, stripe etc. (To buy the phones) After a transaction is done, Being a marketplace, we will keep a little service fee in (℅) and handover the rest of amount to seller. Please suggest an approach to implement this scenario. -
explain me this django views
i dont understand the download() part can someone explain me this This is views file in django project def index(request): send_to_index = { 'file' : FieldAdmin.objects.all() } return render(request , 'installer/index2.html' , send_to_index ) def download(request , path): file_path = os.path.join(settings.MEDIA_ROOT , path) if os.path.exists(file_path): with open(file_path , 'rb') as file: response = hr(file.read(),content_type="application/admin_upload") response['Content-Disposition'] = 'inline;filename='+os.path.basename(file_path) return response raise Http404 -
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