Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sync all tables from sqlite to postgres
I have a django application and deployed it on DigitalOcean. But the only problem is, new models, admin models, tables are not showing in django admin dashboard which is on running on server. Although I pushed al changes to github, pulled them from, and made migrations, again nothing changes. How can migrate all tables from db.sqlite3 to postgresql ? -
DRF - How do I whitelist a site for endpoint requests
This is my scenario: Hosted Django application running DRF External site hosted elsewhere. Could be multiple sites. My question is: How do I whitelist any Javascript POST request from an external site? For example I want to add a Javascript post request on a forms confirmation page. How do I do this so my DRF application only accepts requests from this site only? I'm trying not to use server site code. Just Javascript so it easily applied. My concern is anyone that views the source will be able to view the API endpoint and would be able to submit POST requests. -
Django: request.META.get('HTTP_REFERER') returns None after Ajax call
I am using request.META.get('HTTP_REFERER') to get the referrer page from where current request is made. This function work fine when I am using HttpResponse to render UI. But, if there is an Ajax call which returns JsonResponse to the page, then request.META.get('HTTP_REFERER') return None. Please guide me to solve this problem. Thanks -
I am using a phonenumbers module for validating phone numbers. It works well,however I just need the National number as output
import phonenumbers ph_no = "918332 88 1992" print(phonenumbers.parse(ph_no, "IN")) Output: Country Code: 91 National Number: 8332881992 Desired Output: 8332881993 I just need the phonenumber to return. Please help! -
django form.is_valid returns false
When ever I submit my form and check the form is not getting submited and is redirected. The validation is always false. I entered all the fileds and it still shows the same. Why is this keep showing like this? is there something wrong? Below are the files i use views,template, and forms. views.py def signincheck(request): if request.method == "POST": formsignin = FormSignup(request.POST,request.FILES) if formsignin.is_valid(): return HttpResponse("Password not match 3") TbluserVar=Tbluser() TbluserVar.firstname=formsignin.cleaned_data['firstname'] TbluserVar.lastname=formsignin.cleaned_data['lastname'] TbluserVar.username=formsignin.cleaned_data['username'] Password=formsignin.cleaned_data['password'] ConfirmPassword=formsignin.cleaned_data['confirm_password'] TbluserVar.mobilenumber=formsignin.cleaned_data['mobilenumber'] Tbluser.dateofbirth=formsignin.cleaned_data['dob'] Tbluser.dateofjoining=datetime.datetime.today() Tbluser.userlevel=0 if Password != ConfirmPassword: messages.error(request,'Password and Confirm Password does not match') return redirect('/') else: try: user = Tbluser.objects.get(username=formsignin.cleaned_data['username']) messages.error(request,'Username not available. Try another one.') return redirect('/') except: PasswordEnc=hashlib.md5(Password.encode()) RealPassword=PasswordEnc.hexdigest() TbluserVar.passwordenc=RealPassword TbluserVar.save() request.session['username']=TbluserVar.username request.session['getFirstandLastName']=TbluserVar.firstname + " " + TbluserVar.lastname FullName=request.session['getFirstandLastName'] return redirect('/index') else: return redirect('/') else: return HttpResponse("NOT CORRECT") forms.py class FormSignup(forms.Form): firstname=forms.CharField( max_length=30, widget=forms.TextInput(attrs={'placeholder': 'First Name...','class':'loginform'})) lastname=forms.CharField( max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Last Name...','class':'loginform'})) username=forms.CharField(max_length=30,widget=forms.TextInput(attrs={'placeholder': 'User Name...','class':'loginform'})) password=forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder': 'Password...','class':'loginform'})) confirm_password=forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password...','class':'loginform'})) mobilenumber=forms.CharField(max_length=30,widget=forms.TextInput(attrs={'placeholder': 'Mobile Number...','class':'loginform'})) dob=date = forms.DateTimeField( input_formats=['%d/%m/%Y'], widget=forms.TextInput(attrs= { 'class':'datepicker', 'placeholder': 'Date of Birth...' })) template.html <div class="modal fade" id="modalSignUpForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Sign in</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form id="idlognform" method="POST" action="{% url … -
Javascript-ajax not working in django template
I'm trying to use javascript-ajax to load pages without refreshing, it works fine on the home page. on the home page i have a sidebar containing adverts and other list items, when i click on advert, it shows me a page that has two views (forms), listview and create view. i hid view B so that when i click on the button in view B, it hides the form and shows view A. now the problems are, 1. the onclick function is not working on the home page, but if i run adverts as a page on its own it works very well 2. if i unhide view A such that both forms A and B show when i click on adverts from the home page, and i fill the form in view A it doesn't save to the database, but if i run the adverts.html on its own it saves and shows the form B here are my codes: home.html {% load staticfiles %} {% block content %} <head> <meta charset="UTF-8"> ... <title> {% block title %}News Central Scheduler App{% endblock %} </title> <link rel="stylesheet" href="{% static 'style.css' %} "/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"/> </head> <div class="clearfix"> </div> … -
Python/Django - Adding choices to a choice field through model submission
I'm building an API for communication from one application (the master database program) to a separate reporting application. Within my reporting application models, I have several fields with choices. These choices live within a separate choices.py file. However, when the master application creates a new instance within my reporting app, I want to ensure that if the value is not found in the choices list, that the choice is added to the list and then selected. What is the best practice or way to make this possible? Thanks! -
What is the use of {% load static %}?
I am doing the django tutorial on realpython https://realpython.com/get-started-with-django-1/ In one of the templates they add {% load static %} to load the static files for an app. In the same template they also load an image like this <img class="card-img-top" src="{% static project.image %}">. The static keyword here tells django to look for the filename defined in project.image in the static folder. When i remove {% load static %} the image is still displayed. So why would i need this part if the image can be perfectly rendered without it? Heres the code: {% extends "base.html" %} <!--{% load static %}--> {% block page_content %} <h1>Projects</h1> <div class="row"> {% for project in projects %} <div class="col-md-4"> <div class="card mb-2"> <img class="card-img-top" src="{% static project.image %}"> <div class="card-body"> <h5 class="card-title">{{ project.title }}</h5> <p class="card-text">{{ project.description }}</p> <a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">Read more</a> </div> </div> </div> {% endfor %} </div> {% endblock %} -
Django Rest - Different view based on role
News to Django and Django Rest. I'm trying to create 2 types of view, based on the role of the user. While creating a new demand, I have one field that I would like to not show to one role(leaving it null in DB) but to show it to the other role. The thing is that I don't see how I could do that. If anyone could guide me in the right direction Here is what I have : models.py class demand(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=60) description = models.CharField(max_length=400) assigned = models.CharField(max_length=60) serializer.py class demandSerializer(serializers.ModelSerializer): class Meta: model = models.demand fields = ('title','description','assigned') views.py class demandCreateAPIView(CreateAPIView): queryset=models.demand.objects.all() serializer_class=serializers.demandSerializer -
DRF/POST create related objects alongside with the main object
I have two models. class Order(..): ... class OrderImage(..): order = ForeignKey('Order...) And I have a form with dropzone.js. This form returns data suitable for creating an order using just ViewSet but it obviously doesn't create OrderImage objects, even there are image[0], image[1] etc. data in the POST request. What's the best way to create OrderImages alongside with the Order in DRF? modify dropzone output (didn't find the way) Modify request.data inside ViewSet (how?) Modify OrderSerializer to create OrderImage objects? How would you do that? -
'Pyre' object is not subscriptable
I'm trying to fetch all the products from the firebase database, but in the json data form. Here's the structure of my database: products{ 0{ name:... price:... } 1{ name:.. price:.. and so on. And below is the code I tried: import json from .models import Product import pyrebase def get_products(): database = firebase_key().database() product_list = Product.objects.all() r = database.child("products").get().each() jsonList = r.json() jsonData = jsonList['products'] data = [] for products in r: productData = {} productData['name'] = products['name'] productData['image'] = products['image'] productData['price'] = products['price'] productData['description'] = products['description'] data.append(productData) return data I'm new to both django and firebase, so any help would be appreciated -
DRF required search filter
I have viewset that works fine class PlayerViewSet(ModelViewSet): queryset = Player.objects.all() serializer_class = PlayerSerializer filter_backends = [SearchFilter] search_fields = ['nickname'] Url configuration: path('player', PlayerViewSet.as_view({'get': 'list', 'post': 'create'})), Everything works fine when I try search objects using endpoint like: 'player?search=randomNickname' but there is possibility to send GET request without search parms and it returns all possible objects Is there any way to set search field as required? -
How can I get the ID of a celery group?
from celery.tasks import QueuedSend import celery def send_survey(profile_ids, notification_email): tasks = celery.group(QueuedSend().s(profile_id=profile_id, email=email, group=tasks.id) \ for profile_id in profile_ids) tasks.apply_async() I want to be able to reference the group inside of each of the tasks, so I can send an email when the last task is completed. I thought I'd be able to recover the group from the tasks.id, but the tasks.id is None throughout the logic. The task creation is in an HTTP request, so I can't just let it hang forever and wait in this block of code to check when things are done. I'd like something in place of group=tasks.id so that I can determine when the last task is about to finish. Or an alternative architecture. Is a chord a better setup for something like this? -
using both username and email in user model
I am trying to create users asking for username and email, but using only the email to authenticate users with Django-rest-auth, the email is key as it will be used to log in to the user. but the username also has its importance in my app as when searching up a user, I would want to do something like this "accounts//". in trying to do this I have added a backend. please, what can I do, so when signing up I can input my username and email? backend.py class EmailAndUsernameBackend(ModelBackend): """ this model backend would help me use both username and email, remember to overide your AUTHENTICATION_BACKENDS to this one """ def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel.objects.get(Q(email=username) | Q(username=username)) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user models.py class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) fullname = fullname user = self.model( email=email, fullname=fullname, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, fullname, password, **extra_fields): return self._create_user(email, fullname, password, False, … -
How to serve static files in Django 3.0 (development environment)?
I migrated my django application from version 2.1.7 to 3.0, now I have a problem how to server static files in development server. I did not change anything in my project, before migration static files were served without any problems. How can I serve static files in django 3.0? -
"encoding with 'idna' codec failed (UnicodeError: label too long)" when I call the following django api code to upload a file to Azure Blob Storage
import os from azure.storage.blob import BlockBlobService, baseblobservice from django.http import JsonResponse from rest_framework.decorators import api_view @api_view(['GET', 'POST']) def upload_to_blob(request): try: container_name = 'xyzxyzxyz' connection_string = "DefaultEndpointsProtocol=https;AccountName=dapblobstorage;AccountKey=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefgh==;" local_file_path = "D:\Work\\uploadToBLOB API\\test\\a4.csv" upload_location = "kuldeep/api" block_blob_service = BlockBlobService(connection_string) if os.path.exists(local_file_path): block_blob_service.create_blob_from_path(container_name=container_name , blob_name=(upload_location.strip('/') + '/' + os.path.basename(local_file_path)) , file_path=local_file_path) return JsonResponse({'message': f'{os.path.basename(local_file_path)} uploaded successfully!'}, status=200, safe=False) except Exception as err: loggers.error(err, exc_info=True) return JsonResponse({'message': f'File upload failed with error - {err}'}, status=500, safe=False) Response : {"message": "File upload failed with error - encoding with 'idna' codec failed (UnicodeError: label too long)"} Please Help! -
django how export time to csv in one cell
I am using django outputing method to export data which includes time. In csv I have: Session Code, Round, Seller, Buyer, Price, Quantity, Created at {% for t in data %} {{ t.bid.player.session.code}}, {{ t.bid.player.round_number }}, {{ t.ask.player.participant.code }}, {{ t.bid.player.participant.code }}, {{ t.traded_price }}, {{ t.traded_share }}, "{{ b.created_at }}" {% endfor%} The data I download would be: ...Create at ..."Dec. 12, 2019, 2:18pm" Because of the comma, Dec. 12, 2019, 2:18pm are in three cells, but I want the time to be stored in one cell. -
Routing celery tasks
I can't send tasks to celery when trying to create two separate dedicated workers. I have gone through the docs and this question, but it did not improve my situation. My configuration is following: CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = f'redis://{env("REDIS_HOST")}:{env("REDIS_PORT")}/{env("REDIS_CELERY_DB")}' CELERY_DEFAULT_QUEUE = 'default' CELERY_DEFAULT_EXCHANGE_TYPE = 'topic' CELERY_DEFAULT_ROUTING_KEY = 'default' CELERY_QUEUES = ( Queue('default', Exchange('default'), routing_key='default'), Queue('media', Exchange('media'), routing_key='media'), ) CELERY_ROUTES = { 'books.tasks.resize_book_photo': { 'queue': 'media', 'routing_key': 'media', }, } Tasks are defined in a following way in the tasks.py file: import logging import time from celery import shared_task from books.models import Author, Book from books.commands import resize_book_photo as resize_book_photo_command logger = logging.getLogger(__name__) @shared_task def list_test_books_per_author(): time.sleep(5) queryset = Author.objects.all() for author in queryset: for book in author.testing_books: logger.info(book.title) @shared_task def resize_book_photo(book_id: int): resize_book_photo_command(Book.objects.get(id=book_id)) And they are called using apply_async: list_test_books_per_author.apply_async() resize_book_photo.apply_async((book.id,)) When I run celery flower I see that no tasks appear in queues. The workers are started using: celery -A blacksheep worker -l info --autoscale=10,1 -Q default --host=media@%h celery -A blacksheep worker -l info --autoscale=10,1 -Q default --host=default@%h What I can do is by using redis-cli and 127.0.0.1:6379> LRANGE celery 1 100 command confirm that they end up under celery key (which is the default one for celery). … -
Django getting error: "Reverse accessor for" in Models
I am trying to create a db model using django inspect db and it is generating all the models but I am getting error. I am using this command to generate db models for existing database: python manage.py inspectdb > models.py It is generating models accurately but in fileds such as this: create_uid = models.ForeignKey('self', models.DO_NOTHING,db_column='create_uid', blank=True, null=True) write_uid = models.ForeignKey('self',models.DO_NOTHING, db_column='write_uid', blank=True, null=True) I am getting error: polls.ResUsers.create_uid: (fields.E304) Reverse accessor for 'ResUsers.create_uid' clashes with reverse accessor for 'ResUsers.write_uid'. HINT: Add or change a related_name argument to the definition for 'ResUsers.create_uid' or 'ResUsers.write_uid'. polls.ResUsers.write_uid: (fields.E304) Reverse accessor for 'ResUsers.write_uid' clashes with reverse accessor for 'ResUsers.create_uid'. HINT: Add or change a related_name argument to the definition for 'ResUsers.write_uid' or 'ResUsers.create_uid'. I am adding related names like this: create_uid = models.ForeignKey('self', models.DO_NOTHING,related_name='create_uid',db_column='create_uid', blank=True, null=True) What should I do in order to use generated models. I am using postgres. -
Django Admin - Customize object creation form
Consider the following models: class MainModel(model.Models): name = models.CharField(max_length=255) other_model = models.OneToOneField(OtherModel, related_name='main_model', editable=False) class OtherModel(model.Models): identification = models.CharField(max_length=255) capacity = models.IntegerField() I need to create a form on Django Admin for the model MainModel. If it is for visualization and editing it should have "name" field as an editable field, and "other_model" as read only(as it is editable=False) But for Add form, it should have "name", "identification" and "capacity" for the user to fill. OtherModel is an abstraction that django admin user does not need to worry. Now I have the this form, which works fine for the visualization: class MainModelAdmin(admin.ModelAdmin): fields = ( 'name' ) readonly_fields = ( 'other_model' ) list_display = ( 'name' ) admin.site.register(MainModel, MainModelAdmin) How can I create separate forms for "visualization and editing" and "adding" actions? -
Using request_started signal for a particular request
Is it possible to restrict the request_started signal to run for a particular request? I have browsed around the web and only seem to find it being triggered for each request that is made. -
Django version 3.0 up to 3.2: to use or not to use Celery [closed]
I have a django project that performs intensive calculation. I will now turn to add asynchronous tasks to my website by using Celery with RabbitMQ. I read that the new django version 3.0 and especially the coming version 3.2 which will be fully async-capable. What should I do? 1) Continue to follow my first plan i.e. use Celery with RabbitmQ or is it better to switch to the new django async functionalities? 2) Is it correct to say that these new async functionalities are derived from asyncio? or due to the fact that since python 3.5, the python versions have async def and similar native support for coroutines? 3) If so, what would be the difference by using async instead of Celery? 4) Do you see any advantages or inconvenients by using async vs Celery? 5) Finally, what would be the best architecture for my project? i.e. future development Many thanks in advance for your answers. -
how to loop ajax response data in Django template language?
i am new to Django,recently meet a problem :as we know , to loop a data sent by view in html is simple , like below: {% for key in data %} <p>{{ key }}</p> {% endfor %} but ,what about loop a data sent by Ajax without refresh webpage? $.ajax({ data:{"data":data}, url:'/processData/', type: 'POST', success: function (data) { //how to re-loop above piece code? } }) You know the traditional way would be use Jquery each function to append tags, like below success: function (data) { $(data).each(function (index, obj) { //process obj ,add tags,so as to simulate the effect of {% for i in data %} }); } But , i am obsessed with way to solve it by django template language could you please tell how to solve it ? thanks if you have any ideas!! -
How to listen to already existing SQS queue with Celery and Django?
I want to listen to an existing SQS queue through Celery. I have already done publishing to Queue via celery and then consuming from that queue through workers and tasks bound to that queue. However, I am unable to figure out how to consume from an SQS queue if the publisher is a non-celery Django application. There is no such information available on the internet regarding this or at least I am unable to locate it. Can someone please guide me to some documentation for doing this? -
Management of JS static files: code seems to be downloaded but do not work
I have a Django project with 2 apps: registration and randomization - django-project - registration - randomization - static - randomization - js - script.js - templates - randomization - stock.html - templates - layouts - _nav.html - base.html - home.html I use JQuery/ajax that work but is repeated in all my templates so I want to refactor script.js seems to be download (browser debug network / status = 200) but when I run my ajax request, I got the following error: Not Found: /{% url "randomization:stock" %} I try to manage static files like this: settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), os.path.join(BASE_DIR,'randomization/static'), ) randomization/static/randomization/js/script.js $(document).ready(function() { $("#site").on("change", function(event){ console.log($(this).val()); $.ajax({ type: "POST", url: '{% url "randomization:stock" %}', data: { csrfmiddlewaretoken: '{{ csrf_token }}', 'site' : $(this).val(), }, dataType: 'html', success: function (data) { if (data.includes("Insufficient")) { $("#alerte").html(data); $("#randomize").children().remove(); } else { $("#alerte").children().remove(); $("#randomize").html(data); } } }); }); $("body") .on("click", '#informations', function(event) { $('#pharmacy').modal('show'); }) .on('click','#button_ok',function(event){ $(this).modal('close') }); }); base.html {% load static i18n %} {% load static %} {% load widget_tweaks %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> {% …