Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' %}"> {% … -
Dropdown menu with condition in Django
I have a problem with generating dropdown menu. In admin panel for each subpage I created field "parent" where I can define if this subpage is parent of other. But in template subpages are displayed in both places. I try to explain: We start iterations. The first page has no child so is displayed normal. The second page also has no child so is displayed. Page three has a child - page one, so page one is added to the tree as child . The problem is that it will not be removed from the first place because the iteration is already completed. I don't now how to solve this problem and if it even possible in Django. I was thinking of using JS and remove class if specified href appears twice. {% for subpage in subpage_sorted %} <li class="nav-item {% if subpage.parent %}dropdown{% endif %}"> <a class="nav-link {% if subpage.parent %}dropdown-toggle{% endif %}" href="{% url 'generated_page' subpage.slug %}" {% if subpage.parent %}data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"{% endif %}>{% trans subpage.title %}</a> {% if subpage.parent %} <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'generated_page' subpage.parent.slug %}">{% trans subpage.parent.title %}</a> {% endif %} </li> {% endfor %} -
Django relationships to inherited model from parent model
I have 4 models in django, here are 3 of them (the 4th one is the default user model): class Post(models.Model): title = CharField(max_length=200) content = TextField() def __str__(self): return self.title class NewsArticle(Post): link = URLField(default='') external_id = CharField(unique=True, max_length=50, help_text='The ID of the news article from the source') source = CharField(max_length=15, help_text='Name of source website') class Like(models.Model): LIKE_CHOICES = [('L', 'Like'), ('D', 'Dislike')] user = ForeignKey(User, on_delete=models.CASCADE) post = ForeignKey(Post, on_delete=models.CASCADE, related_name='post') state = CharField(default='L', max_length=1, choices=LIKE_CHOICES) created_at = DateTimeField(auto_now_add=True) updated_at = DateTimeField(auto_now=True) def __str__(self): return self.get_state_display() According to my understanding, this way the news articles aren't linked to likes at all. My goal is to get all news articles and select_related() the likes on them. I don't want to create a new model just for news article likes also. What can I do here? -
Django Model not saving to MySQL (Maria DB) while others do
My app (Django v 2.2.5) is using MySQL (MariaDB 10.4.6) to store data in its database and has all migrations made and committed. It creates the superuser, when I log in I can creates all related objects, but the Product (arguably most important) is not being made. I click save and it does nothing. I have tried changing the model, and even removing the BooleanField (only unique field different from the models that are storing) and applying the migration but it still does not work. I even deleted the whole database and started anew in hopes of getting around any tricky migrations but that still did nothing for me. Here is my models.py: class Partner(models.Model): name = models.CharField(max_length=150, blank=False, help_text="Enter the vendor name", verbose_name="Vendor name", unique=True) address = models.TextField(help_text="Enter the address of the vendor") formula = models.ForeignKey(Formula, on_delete = models.CASCADE) phone = PhoneNumberField(help_text="enter the vendor phone number") email = models.EmailField(max_length=254, help_text="Enter the vendor email address") photo = models.ImageField(upload_to="vendors") def __str__(self): return self.name class ProductType(models.Model): name = models.CharField(max_length=150, blank=False, help_text="Enter the kind of product this is", verbose_name="Product type") def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=150, blank=False, help_text="Enter the name of the product", verbose_name="Product name") price = models.DecimalField(max_digits=12, decimal_places=5,\ help_text="Enter … -
After import function is called 2 times
Hi I am importing a file and I want to delete all the data which is not in CSV file but present on DB so each time the CSV data is in the DB. Old data will be removed. def after_import_instance(self, instance, new, **kwargs): """ For each row in the import file, add the pk to the list """ if instance.pk: self.imported_rows_pks.append(instance.pk) def after_import(self, dataset, result, using_transactions, dry_run=False, **kwargs): """ delete all rows not in the import data set. Then call the same method in the parent to still sequence the DB """ ids = list(set(self.imported_rows_pks)) Product.objects.exclude(pk__in=ids).delete() import_export.resources.ModelResource.after_import(self, dataset, result, using_transactions, dry_run, **kwargs) My code is running 2 times can you help me on it. I think the function called one time when confirm import is triggered. -
Django upgrading unsalted MD5 password not matching
I am migrating an old system that uses unsalted MD5 passwords (the horror!). I know Django handles automatically password upgrading, as users log in, by adding additional hashers to the PASSWORD_HASHERS list in settings.py. But, I would like to upgrade the passwords without requiring users to log in, also explained in the docs. So, I've followed the example in the docs and implemented a custom hasher, legacy/hasher.py: import secrets from django.contrib.auth.hashers import PBKDF2PasswordHasher, UnsaltedMD5PasswordHasher class PBKDF2WrappedMD5PasswordHasher(PBKDF2PasswordHasher): algorithm = "pbkdf2_wrapped_md5" def encode_md5_hash(self, md5_hash): salt = secrets.token_hex(16) return super().encode(md5_hash, salt) def encode(self, password, salt, iterations=None): md5_hash = UnsaltedMD5PasswordHasher().encode(password, salt="") return self.encode_md5_hash(md5_hash) and add it to settings.py: PASSWORD_HASHERS = [ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "legacy.hashers.PBKDF2WrappedMD5PasswordHasher", ] However, testing this in the Django shell check_password is returning False for the upgraded password. >>> from django.contrib.auth.hashers import check_password, UnsaltedMD5PasswordHasher >>> from legacy.hashers import PBKDF2WrappedMD5PasswordHasher >>> hasher = PBKDF2WrappedMD5PasswordHasher() >>> test_pwd = '123456' >>> test_pwd_unsalted_md5 = UnsaltedMD5PasswordHasher().encode(test_pwd, salt='') >>> print(test_pwd_unsalted_md5) '827ccb0eea8a706c4c34a16891f84e7b' # this is an example of a password I want to upgrade >>> upgraded_test_pwd = hasher.encode_md5_hash(test_pwd) >>> print(upgraded_test_pwd) pbkdf2_wrapped_md5$150000$f3aae83b02e8727a2477644eb0aa6560$brqCWW5QuGUoSQ28YNPGUwTLEwZOuMNheN2RxVZGtHQ= >>> check_password(test_pwd, upgraded_test_pwd) False I've looked into other similar SO questions, but didn't found a proper solution there as well. -
How to prevent a url from changing when loading the same template with different data in Django
I got a simple def with something like this def policies_index(request): """Resource listing""" policies = Policy.objects.all() context = { 'policies' : policies } return render(request, "policies/index.html", context) now I want to add a way to filter that info using month and year so I made a function like this def policies_date_filter(request): """List the resources based on a month year filter""" today = datetime.date.today() year = request.POST['year'] month = request.POST['month'] policies = Policy.objects.filter(end_date__year=year).filter(end_date__month=month) status = settings.POLICY_STATUS_SELECT for policy in policies: for status_name in status: if status_name['value'] == policy.status: policy.status_name = status_name['name'] request.policies = policies return policies_index(request) that way I can reuse the function index to avoid writing the code to print the view again and works perfect, but in the url instead of something like "/policies" I got something like "/policies/date-filter" Which makes sense since Im calling another function Is there a way to prevent the url from changing? -
custom Django Management commad
The idea is to delete object by accepting command line options: object can be deleted by ID and by date range Expected behavior, new custom command call using: python manage.py delete_obj --delete id 1234 or python manage.py delete_obj --delete from 2019/10/01 to 2019/12/12 code for first part: from django.core.management.base import BaseCommand from ...models import SomeObject class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('id', type=int) parser.add_argument( '--delete', default = False, help='Delete product', ) def handle(self, *args, **options): if options['delete']: if options['id']: SomeObject.delete() I add custom option in the add_arguments() method for id, how I can define that object can be deleted by ID or by DATE RANGE