Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Serializer Dataset Context
Is there a way to access the entire dataset that will be processed by the serializer before it does so. The Reason for this is because there is a bulk process I would like to do before I serialize the data. This is so that I can improve the performance of the serializing process to improve the delivery speed to the client(this is not required when creating only on retrieving) class MySerializer(serializers.ModelSerializer): def before_process(self, *args, **kwargs): # TODO: Some bulk work here with the self.full_unprocessed_dataset self.bulk_results = from_the_above_result def some_function_field(self): return self.bulk_results['some_key'] Is this possible? -
Django Site Can't Find Admin Styling or Media Files when Debug = False
I'm having trouble getting my django site running with debug = False. Info: Currently, Debug = False I am running on my local host I'm using Wagtail. But from what I've read, the problems I'm dealing with are more Django-related. Problem: When I go to the site on my local host, it can find static files, but it can't get any 'media' files.Example: GET http://127.0.0.1:8000/media/images/block-alphabet-abc.width-400.png Internal Server Error When I log into the admin panel, the look and feel is off in some places (like css components may be missing). When I go to edit a page, the look and feel is still off and the web developer tool has a bunch of 500 errors saying things like the http://127.0.0.1:8000/static/wagtailadmin/js/date-time-chooser.js?v=3a1ab45f is missing. What I have tried: I have ran python manage.py collectstatic. Doing that does not create the media directory though. It adds the wagtail admin files, but none of them have the little hash at the end. I tried running python manage.py compress, but I keep getting the error that none of the templates have the compression tag (which is true). I added logging, but I'm not sure how to resolve the errors. Question: How do I create the … -
JWT authentication using CBV
I have implemented a jwt in my project, some of my views are using apiview others are using cbv. currentely I moved the authentication system to jwt token authentication. my problem is, when I log in, the api views work as expected, but my cbv views are redirecting to the authentication page. In my settings I use sessionauthentication. 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ], but it still not working. can someone tell me if have a way to use boths views(apiview and cbv) knowing that authentication _classes is used only in drf? -
Django management commands reuse arguments
I want to write several management commands in a Django 2.2 and Python 3.8 project. All of these should have a --dry-run options. I would like to have some degree of code reuse in implementing these. What is the recommended approach? Here is how I'm doing it right now. Make MyBaseCommand extended from BaseCommand: class MyBaseCommand(BaseCommand): def add_arguments(self, parser): parser.add_argument('--dry-run', ....) class Command(MyBaseCommmand): def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_arguent('--other-arg', ...) Another option I've thought of is to create one or more decorators for each reusable arg, e.g. @dry-run, @yaml-output, @json-output etc. Then decorate the add_arguments method in each child class. This way I have more control over which management command gets which reusable arg. -
Django- Display columns depending on chosen filter in ModelAdmin (list_display)
I'm trying to show different columns(in list_display) depending on chosen filter. Here is my code: # Filter: class FilterNameFilter(admin.SimpleListFilter): title = ('FilterName') parameter_name = 'FilterName' def lookups(self, request, model_admin): return ( ('xxx', _('xxx 1')), ('yyy', _('yyy 2')), ) def queryset(self, request, queryset): if self.value() == 'xxx': return queryset.filter(c__isnull=False) if self.value() == 'yyy': return queryset.filter(d__isnull=False) # Model: class pricelist_admin(ModelAdmin): ... list_display = ('EAN_id', 'Vendor', 'Description', 'DynamicColumn', 'a', 'b', 'c', 'd', 'e') list_filter = ('Vandor_id__Name', FilterNameFilter) search_fields = ('EAN_id__Description', 'EAN_id__EAN') #Dynamic column: def DynamicColumn(self, obj): if # ... Here is my code for showing different columns, # it works fine for other loop's examples, but I don't know # how to integrate it with "FilterNameFilter" to return desired columns: return obj.e else: return obj.EAN.Description Any ideas? Help would be really appreciated! -
How to filter children by parent field
Example, models.py: class Guy(models.Model): name = models.CharField(max_length=30) class Mom(models.Model): name = models.CharField(max_length=150, choices=MOTHER_NAMES, default=MOTHER_NAMES[0][0]) guy = models.OneToOneField(Guy, on_delete=models.SET_NULL) How to get queryset of Guys whose Mom's name is 'Sophia' -
What is the best and up to date Django authentication library as of 2020?
Our project is entirely on Django Rest Framework, so the ftont-end user interface features of Django are not used. The front-end is on ReactJS. When you mention the method that you suggest, please say why, and whether you used it recently in a project or a company. Many thanks for the help. -
How to display average per grading period in html? using django
I have this filter that compute the final average per Grading Categories gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True))\ .filter(grading_Period__in=period.values_list('id', flat=True)).values('Grading_Categories').annotate(average_grade=Avg('Grade')) when i print it, the result is like this: <QuerySet [{'Grading_Categories': 1, 'average_grade': 88.3333333333333}, {'Grading_Categories': 2, 'average_grade': 90.0}]> I just want to display in my html the actual average per grading period in html but the result i got in html is like this <QuerySet [{'Grading_Categories': 1, 'average_grade': 88.3333333333333}, {'Grading_Categories': 2, 'average_grade': 90.0}]> -
Is there a way to serve a file in django that is generated in a Thread?
I'll explain myself. In my Django web I have a button that calls a view. #The view that's being called def pil_image(request, pdv_id): fp=FileProcesor(request,pdv_id) th = threading.Thread(target=fp.process) th.start() messages.success(request,"The file is being generated, when it's ready you'll be able to download it") return redirect('punto-de-venta',pdv_id) The FileProcesor class has a method process that generates a zip file. The problem is that sometimes this file takes too much time to process. Thats why I create the file in a Thread. But once the file is ready I cant redirect the user to the file. I want that when the file is ready automatically the "standar downloading pop up" shows to the user. if I use this code instead the download message shows but the web is "frozen" untill the file is created. def pil_image(request, pdv_id): fp=FileProcesor(request,pdv_id) return fp.process() -
How to fix TypeError: initial_value must be str or None, not bytes using StringIO
I've got the error message initial_value must be str or None, not bytes and i do not know how to fix it. I face with that after changing to python 3. Moreover I change the import to from io import StringIO Here is my code : def render_to_pdf(template_src, context_dict): template = get_template(template_src) context = context_dict html = template.render(context) result = StringIO() pdf = pisa.pisaDocument(StringIO(html.encode("utf-8")), dest=result, encoding="utf-8") Here is the Traceback: Environment: Request Method: GET Request URL: http:///pdf/11479/ Django Version: 2.2.6 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'bootstrap_themes', 'intranet', 'crispy_forms', 'fm', 'dal', 'dal_select2', 'django_crontab', 'django_tables2', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/var/www/vhosts/intranet.health-nutrition.gr/health_nutrition/intranet/views.py" in pdf_view 598. 'fpa_total':fpa_total(), File "/var/www/vhosts/intranet.health-nutrition.gr/health_nutrition/intranet/views.py" in render_to_pdf 542. pdf = pisa.pisaDocument(StringIO(html.encode("utf-8")), dest=result, encoding="utf-8") Exception Type: TypeError at /pdf/11479/ Exception Value: initial_value must be str or None, not bytes Any idea how to fix it? -
react rest social auth React auth flow
I'm new to asking on stackoverflow, so please be kind :) My issue is as follows: Im developing a react app(I'm new at this), in whch I intend to authenticate users via social account. What I haven't been able to do is to fullfill the oauth flow between backendapiserver->react app->social provider. BackendAPI server: 1. Django 2. DRF 3. rest-auth 4. django-allauth with github configured with client_id a secret_key as the docs says This is what 've been able to understand about how the flow should be processed: 1. User clicks on button to authenticate to social account(e.g. GitHub) 2. react app makes a post request to Backend and returns a url for the provider.ç 3. react apps, in any manner(haven't found out how) launch another window instance(popup, another tab, etc.) where is going to be asked by the social account provider to authorize authentication from my OAuth app(guess is like that) 4. A preconfigured callback url in social account addapter from the OAuth app is then sent (to front-end? to back-end?) 5. if is to front-end, then resend(or redirect) the code, provided from the social account provider, to backend api, where is in charge to verify(guess with the provider) the … -
Git clone causing issues with Windows permissions over SSH with django project
I've got a Django project which works great. Previously we just cloned down and used password authentication. I changed the remote to git@bitbucket.org:myteam/our_repo.git Recently we started requiring 2FA, so now we can only clone down over SSH. For this project, I created an access key (read-only, which is all I need for cloning down on a staging server) and I was able to clone down the repo (git clone git@bitbucket.org:myteam/our_repo.git) without issue and get it all set up. This appeared to have worked. The other server admin remoted in and tried to run git pull origin master, he got a permission issue. His windows user is part of the Administrators group - but for some reason that didn't matter. His local user had to be added to the directory with full access before he could run git pull origin master It appears that this permission issue is causing other issues, too. File uploads (from the Django admin) are no longer actually uploading the files into the directory on the server - my guess is that this is related to the permissions issue, too. Nothing was changed to impact this - the project was just cloned down over SSH. Does cloning … -
Can not connect to postgresql on localhost using ssl client certificate with django
I am trying to connect to postgresql on localhost using ssl client certificates via django. However I get the following error django.db.utils.OperationalError: FATAL: connection requires a valid client certificate I have tried the following I can connect to a remote postgresql database via the django application (using a set of different certificates) I can connect to the local database (using the same ssl certificates that does not work in django) using psql. I can connect to the database on localhost via the django shell and psycopg2 connection using the following code psycopg2.connect("host=127.0.0.1 dbname=analyticslayer user=al-app password=... sslmode=verify-ca sslcert=/home/al-app/.postgresql/ps-analyticslayer-1-postgresql-al-app-ca.crt sslkey=/home/al-app/.postgresql/ps-analyticslayer-1-postgresql-al-app-key.pem sslrootcert=/home/al-app/.postgresql/vintercapital.com-ca.crt") I have also verified that the certificates are okay using openssl verify would really appreciate some help with this problem / Hakan -
ValueError: Attempted relative import in non-package Python 3.6 (UBUNTU 12.4)
I have the following directory structure: -project_name --folder1 --folder11 -urls.py -views.py -wsgi.py -manage.py --folder2 --folder22 -file1.py -file2.py -file3.py -file4.py -main.py Django version is 1.11.22 Python 3.6 In views.py def abc(request): .... .... .... subprocess.Popen(['python', 'path/to/main.py']) return JsonResponse({ 'status': True, 'code': 200, 'message': "Success!" }) In main.py from .file1 import FILE1 from .file2 import FILE2 from .file3 import FILE3 from .file4 import FILE4 def main(): .... .... if __name__ == '__main__': exit_status = main() I am getting this error: Traceback (most recent call last): File "/path/to/main.py", line 1, in <module> from .file import FILE1 ValueError: Attempted relative import in non-package What can be the issue? I have tried all given solutions on SO. -
Django - how to redirect while sending mail
Question: is it possible to redirect the page while sending the email. It takes 5 to 10 seconds for the mail to be sent. During this time, the page is not doing anything. Users might resubmit the form to prompt a reaction. So I was thinking maybe there's a way to redirect the page right after the object is saved instead of redirecting after the mail is sent. Code below: @login_required def handle_order(request, **kwargs): .... order = form.save(commit=False) order.active = True order.save() # send email to the user, 5-10 seconds waiting time kwargs = {...} mail_order_detail(**kwargs) return redirect('shopping:show-order', order.ref_number) I've tried to use post_save signal, not working, still have to wait before being redirected -
Will Django process inclusion tag if I hide it in html template using css
I am using inclusion tag in sidebar of html page. If I hide the sidebar using css for mobile view. Will Django process the inclusion tag in backend when visited from mobile -
Save chat conversation in json field
I have created a chat bot. I want to save the conversation in JSONField ('question': 'answer') when channel disconnect, or user ends the chat or after 5 min of inactivity. I am using django channels. Everything is working but I don't know how can I save conversation after chat ends. My model to save conversation: class ChatHistory(models.Model): question = models.TextField(null=True) # not required. added just to test answer = models.TextField(null=True) # not required. added just to test conversation = JSONField() customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, related_name='customer_chat') date_time = models.DateTimeField(auto_now_add=True) talker = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='user_chat', null=True) consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['secret_key'] self.user_email = self.scope['url_route']['kwargs']['user_email'] self.room_group_name = 'chat_%s' % self.room_name + self.user_email # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] dir_name = text_data_json['dir_name'] reply = bot_reply(message, dir_name) secret_key = text_data_json['secret_key'] u_id = text_data_json['user_id'] customer = Customer.objects.get(u_field=u_id) company = Company.objects.get(secret_key=secret_key) conversation = {} # I tried to save every question/answer when talker asked and bot responded. Please igore fields. # ChatHistory.objects.create( # company=company, # # question=message, # answer=reply, # # talker=company.company_name # ) # Send message to room group … -
How to store a user's cart information without using models or authentication in Django?
I am making an ecommerce website, I use this view to allow user to add items in cart: def add_to_cart(request, slug): if request.method == 'POST': item = get_object_or_404(Item, slug=slug) order_item = OrderedItems.objects.create(item=item, user=request.user, ordered=False) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] order_item.quantity = request.POST.get('number') order_item.save() order.items.add(order_item) return redirect('core:home') order = Order.objects.create(user=request.user, ordered=False) order.items.add(order_item) order_item.quantity = request.POST.get('number') order_item.save() return redirect('core:product_detail', slug=slug) The models and everything else in this website depends heavily on user authentication. I keep track of which user ordered which items through Order model: class OrderedItems(models.Model): item = models.ForeignKey( Item, on_delete=models.CASCADE, related_name='ordereditems') quantity = models.IntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) So, how do I store a user's cart information without using models or authentication using cookies or sessions? Please kindly explain it with code. Github link to current project. Thank You -
Serialization of related pivot models with Django Rest Framework
I am learning Django, and are using Django Rest Framework. In my application, I have three different models Bar (holds information about a bar, has multiple beers through the BarBeer model) Beer (holds information about a beer) BarBeer (connection between a bar and a beer, has pivot fields such as alcohol, type, price and volume) This is how the different models are defined: class Bar(models.Model): name = models.CharField(max_length=60) location = models.PointField() address = models.CharField(max_length=60) description = models.TextField(default='') beers = models.ManyToManyField('api.Beer', through='api.BarBeer') class Beer(models.Model): name = models.CharField(max_length=60) alcohol = models.FloatField(default=0) class BarBeer(models.Model): bar = models.ForeignKey(Bar, on_delete=models.CASCADE) beer = models.ForeignKey(Beer, on_delete=models.CASCADE) price = models.FloatField(default=0) type = EnumField(Type, default=Type.Cask) volume = models.IntegerField(default=0) Now I want to serialize a given bar with all the beers for that particular bar including the extra fields in the pivot model BarBeer. For example, below is what I'd like the output to be (note the extra three fields on the beer, that comes from the BarBeer model): { "id": 1, "name": "A bar", "beers": [ { "id": 1, "name": "Ship Full of IPA", "alcohol": 6.5, "type": "bottle", "price": "35", "volume": "33" } ] } I can't figure out how to get the extra fields from the pivot model … -
Django group by multiple fields and apply aggregation
I'm trying to generate a report from Postgres using Django ORM which will be similar to the following SQL query: SELECT region, manager, report_group, SUM( CASE WHEN invoice_date BETWEEN '2020-01-01' AND '2020-01-31' THEN item_amount ELSE 0 END ) as p1_spends FROM A_TABLE_WITH_SOME_JOINS GROUP BY region, manager, report_group I've written this snippet queryset = queryset.values("region", "manager", "report_group").order_by().annotate( p1_spends=Case( When(invoice__invoice_date__range=('2020-01-01', '2020-01-31'), then=Sum('item_amount')), default=Value(0), output_field=FloatField() ) ) ) I was hoping to achieve a resultset where rows are grouped by region, manager and report_group and the aggregation function applied on item_amount field but the resultset gets grouped by region, manager, report group and invoice date. How can I acheive the expected resultset? -
Django filter only if value is given
I want to get the number of sites per country. Now if the country is not given, the amount of sites for all countries should be the result. My query looks like: Devices = GatewayDevice.objects.prefetch_related("model").filter( model__site__country=country, end_date=None ) Before I do the query I can check if parameter country is null and give it and other value, like example ALL (doesn't work). How can I handle this? -
Django redux knox authentication- request.user is always anonymous
My setup is Django, redux, react with knox authentication. I've managed to login to my application, redux is showing the user and token. when i'm calling a function in views.api, the user is always annoynmous. My function in views.api: def navApi(request): user = request.user data = { 'name': 'Vitor', 'location': 'Finland', 'is_active': True, 'count': time.time() } return JsonResponse(data) note- in the request i can see the token in the header. Am I missing something? -
USE_THOUSAND_SEPARATOR only to selected fields of a model Django
I have a model which has two fields ID and price- both are numbers, I only want my price to be comma separated using USE_THOUSAND_SEPARATOR in django. When I use USE_THOUSAND_SEPARATOR= True in my settings.py file it changes both ID and price to be comma-separated. Also, I have used NUMBER_GROUPING=2, but it still groups it with 3 numbers. Thanks -
Django server shuts down
As soon as I try to switch from http://127.0.0.1:8000/ to http://127.0.0.1:8000/admin/, the django server automatically shuts down, without any error. What could be the problem? I just can’t find a solution. Thanks in advance. -
The url does not change at form submit?
I have some categories, like restaurants, sport and fitness, fast food etc.. I want to create dropdown menu with all categories and show different category items each time when different category is selected: HTML: <form action="{% url 'show-all-objects' category=category page_num=1 %}" method="POST" id="sort_form"> <select data-placeholder="Categories:" class="utf_chosen_select_single" id="select_sort_category" name="select_sort_category" onchange="this.form.submit()"> <option>Категориии</option> <option value="restaurants">Ресторанти</option> <option value="sportfitness">Спортни и фитнес</option> <option value="carservice">Автосервизи</option> <option value="beautysalon">Салони за красота</option> <option value="fastfood">Бързо хранене</option> <option value="carwash">Автомивки</option> <option value="fun">Забавлание</option> <option value="other">Други</option> </select> </form> Okay, this is the first link: http://localhost:8000/objects/all/restaurants/1/ Then from <select> select second option with value sportfitness It refresh page and show items from category sportfitness but url is still http://localhost:8000/objects/all/restaurants/1/ After that select third option with value carservice page is refresh again, this time url is changed to http://localhost:8000/objects/all/sportfitness/1/ instead of carservices so it has delay 1 time. urls.py: from django.urls import path, re_path from . import views urlpatterns = [ path('user/<int:pk>/', views.UserObjectsView.as_view(), name='user-objects'), path('add/<str:category>/', views.add_object, name='add-object'), path('<str:category>/<int:pk>/<int:page_num>/', views.show_object, name='show-object'), #path('all/<str:category>/<int:page_num>/', views.show_all_objects, name="show-all-objects"), re_path(r'all/(?P<category>\w+)/(?P<page_num>\d+)/?/(?P<city>\d+)?', views.show_all_objects, name="show-all-objects"), ] views.py: def show_all_objects(request, category, page_num, city=None): params_map = { 'restaurants': Restaurant, 'sportfitness': SportFitness, 'carservice': CarService, 'beautysalon': BeautySalon, 'fastfood': FastFood, 'carwash': CarWash, 'fun': Fun, 'other': Other, } if request.method == 'POST': category = request.POST.get('select_sort_category') objects = Object.objects.instance_of(params_map.get(category)).order_by('rating') if city is not …