Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Microservice architecture via Django
now I make an app which uses microservice architecture. So most of microservices should be made with Django. So is it real to make one separate service, which only will get requests and send verification emails, another separate service (django app in a fact), which will store sessions in Redis and another services could send requests to find out, does user have a session or not? And one more question, I haven't used Django for much time, but can I freely use requests lib in Django Views? So it looks like: I send POST request with some data to one endpoint. The view, which belongs to this endpoint, sends request to one microservice, gets some data, than sends request to the next microservice and gets another extra data and finally returns something to user. -
How can I use F() expressions to subtract on a query expression?
I want to show when a user is under or over budget based on user entries. Currently my views will add the values for totalProjSum and totalActSum but when I attempt to output the total through budget.html it just outputs the actual code. Is there a better way to do these calculations? Or what am I missing? inside my views.py `table_data = BudgetEntry.objects.filter(user=request.user) context = { "table_data": table_data } table_data.totalProjSum = BudgetEntry.objects.all().aggregate(Sum('projected')) table_data.totalActSum = BudgetEntry.objects.all().aggregate(Sum('actual')) table_data.total = F('table_data.totalProjSum') - F('table_data.totalActSum') return render(request, 'budget/budget.html', context)` inside models: `Class BudgetEntry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=128) category = models.CharField(max_length=128, choices=CHOICES, default='green') projected = models.IntegerField(default=0) actual = models.IntegerField(default=0) totalProjSum = models.IntegerField(default=0) totalActSum = models.IntegerField(default=0) total = models.IntegerField(default=0) temp = models.IntegerField(default=0)` in budget.html (main template) {% if not table_data%} <p> No budget info </p> {%else%} {{table_data.total}} {%endif%} -
How edit more than 2 object in one template?
I'm trying to create a student journal for teachers, where the teacher can enter scores for all students in this discipline. How can I update student scores? Do I need to create many forms or what? Thx for you answers! -
grouped bar dataset in djanog template loop
i would like to draw a grouped bar from chart js using django which currently works fine. Actually i do manually. but i need to draw a grouped bar through for loop(data,label,background-color). Actual label_list=[2019,2020] color_list=['#e75e72','#3396ff'] data_list=[[282,314,106,502,107,111],[86,350,411,340,635,809]] datasets: [ { label: {{label_list.0|safe}}, backgroundColor: '{{color_list.0|safe}}', data:{{data_list.0|safe}} , }, { label: {{label_list.1|safe}}, backgroundColor: '{{color_list.1|safe}}', data: {{data_list.1|safe}} , }, ] i really do not have any idea to make it dynamically. i need something like {% for x in label_list %} {{ label:label_list.forloop.counter[x], background-color:color_list.forloop.counter[x], data:data_list.forloop.counter[x] }}//forloop.counter0,forloop.counter1 {% endfor %} thanx in advance. -
how to show different Django views on a same html page section wise, instead of different html
how to show all these views on the same HTML i.e. home_2.html and how to write URL def Home(request): posts = Yogmodel.objects.filter return render(request, 'frontend/home_2.html', {'posts': posts }) def Viewfulltest(request): tests = Testimonial.objects.all() context = {'tests':tests} return render(request, 'frontend/testfullview.html', context) def ViewAward2(request,id): #award = request.GET.get('award') awardphotos = AwardPhoto.objects.filter(award__id=id) awards = AwardTitle.objects.all() context = {'id':id,'awards': awards, 'awardphotos': awardphotos} return render(request, 'frontend/viewaward2.html', context) -
Fetch order data based on order item with particular seller in django
I want order data with order item of particular seller in django. Here is my code: def list_order_by_status_entrepreneur_view(request): order = Order.objects.distinct().filter(orderitem__entrepreneur_id=request.data['entrepreneur_id'], orderitem__status=request.data['status']) serializer = ListOrderSerializer(order, many=True) return Response(serializer.data) -
What is the best Third party package for Auth in Django rest framework
and hope you all doing well. Recently i m working on a project, and i m still new to Django, I need to make an Authentication API, but I kinda got confused on the number or the 3rd party package that Django REST framework provide, https://www.django-rest-framework.org/api-guide/authentication/#installation-configuration_1, in my project used Simplejwt, but now i m not sure of my choice, and i also want to be able to log out with facebook, google ... So my question here what the best package to work with in the terms of security and maintainable code, and also with the option of login with social media. thanks for reading this . -
Boolean Field for django_filter search bar
I am trying to show an option on a search bar where the user can choose a True or False value for the boolean fields lead_register(and finished_leveltest) below. class LevelTestFilter(django_filters.FilterSet): class Meta: model = LevelTest fields = { 'first_name': ['icontains'], 'username': ['icontains'], 'phone_number': ['icontains'], 'email': ['exact'], 'lead_register': ['exact'], 'finished_leveltest': ['exact'], } Right now, I typed in exact because I didn't know what to put there. I hope you guys could help. Thanks a lot! -
Direct assignment to the forward side of a many-to-many set is prohibited. Use students_that_completed.set() instead
This error happens when i try to create a new "Assignment" /Model instance. ofc this is works perfectly fine in django admin panel but when i do the same with django rest framework browsable api it doesnt work. here is my "Assignment" serializer class (AssignmentSerializer): class AssignmentSerializer(serializers.Serializer): title = serializers.CharField(max_length=50) body = serializers.CharField(max_length=1000) attachment = serializers.FileField(max_length=100) class_name = serializers.CharField(max_length=50) students_that_completed = serializers.PrimaryKeyRelatedField(queryset=Student.objects.all(), many=True) owner = serializers.PrimaryKeyRelatedField(queryset=Teacher.objects.all()) def create(self, validated_data): """ Create and return an "Assignment" instance. """ print(validated_data) return Assignment.objects.create(**validated_data) -
Django - How to SUM the related Model field with Filter in Annotate?
I've been facing this issue. I have 2 models with relationship like below, I tried to Sum all the PRICE of each author with filter: sale_type=sl01 and I was stuck all day. Can someone point the right way for it to solve it, many thanks in advance, from django.db.models import Q, Subquery, OuterRef SALE_CHOICES = ( ("sl01", "sl01"), ("sl02", "sl02") ) class Author(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=50, default='', null=True) password = models.CharField(max_length=20, default='', null=True) phone = models.CharField(max_length=15, default='', null=True) address = models.CharField(max_length=100, default='', null=True) class Sale(models.Model): created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True) sale_type = models.CharField(choices=SALE_CHOICES, default='sl01', max_length=10) data = Author.objects.annotate(total_amount=Subquery(Sale.objects.filter(author=OuterRef('author'), sale_type='sl01').aggregate(total_amount=Sum('price'))['total_amount'])) -
How to upgrade Django Celery App from Elastic Beanstalk Amazon Linux 1 to Amazon Linux 2
I am trying to upgrade a Django Application running Celery from Amazon Elastic Beanstalk Linux 1 on running Python 3.6 to Amazon Linux 2 using Python 3.8. I am having trouble with the Celery application. In Linux 1 I the following file #!/usr/bin/env bash # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryconf="[program:celeryd-worker] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery -A core worker -P solo --loglevel=INFO -n worker.%%h directory=/opt/python/current/app/src user=nobody numprocs=1 stdout_logfile=/var/log/celery/worker.log stderr_logfile=/var/log/celery/worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 environment=$celeryenv " # Create the celery supervisord conf script echo "$celeryconf" | tee /opt/python/etc/celery.conf # Add configuration script to supervisord conf (if not there already) if ! grep … -
variable.object.get is this possible in django?
it would be better if I show this to you: @classmethod def validate_recommendation_id(cls, recommendation_id): try: Recommendation.objects.get(id=recommendation_id) except Recommendation.DoesNotExist as exception: raise ValidationError( {f"{recommendation_id}": "does not exist"} ) from exception return recommendation_i @classmethod def validate_profile_id(cls, profile_id): try: Profile.objects.get(id=profile_id) except Profile.DoesNotExist as exception: raise ValidationError({f"{profile_id}": "does not exist"}) from exception return profile_id What you see here happens in django_rest_framework serializers I was looking for implementing some sort of logic in these functions, since I do not want to keep repeating the same code over and over I could not find any information about this over net yet I wonder if there a possibility to have something like: def validate_recommendation_id(cls, value, model): try: model.objects.get(id=value) except model.DoesNotExist as exception: raise ValidationError( {f"{value}": "does not exist"} ) from exception return recommendation_i Thanks! -
How can I add a choice field in django models through a form?
I have a choices field which has a set of limited number of choices like: class Choices(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name This now is a foreign key to another model which has some data like: class Item(models.Model): name = models.Charfield(max_length = 255) choice = models.ForeignKey(Choices, on_delete=models.CASCADE) I want that if a choice does not exist, one may be able to add a new Choice item while submitting the form and add it to the database, then the newly created choice can be used again. Please help me accordingly. -
Creating a class structure for data in a catalogue python Django
I am currently developing a fruits catalogue using Django and was wondering how I would structure and implement a python class to structure the data for the items in my catalogue I was initially using the SQLite database but was told by my teacher not to. The structure would follow somthing similar to this but I am having trouble formulating it and just need an example of how this could work and be implemented into my server item1 = My_Item_Class(‘widget’, ‘something’, ‘data’) item2 = My_Item_Class(‘thingy’, ‘content’, ‘info’) my_catalogue_list = [item1, item2] -
How to change the output of the models.ForeignKey in Django?
How can I change the output of the models.ForeignKey field in my below custom field? Custom field: class BetterForeignKey(models.ForeignKey): def to_python(self, value): print('to_python', value) return { 'id': value.id, 'name_fa': value.name_fa, 'name_en': value.name_en, } def get_db_prep_value(self, value, connection, prepared=False): print('get_db_prep_value') return super().get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): print('get_prep_value') return super().get_prep_value(value) And used in the below model: class A(models.Model): ... job_title = BetterForeignKey(JobTitle, on_delete=models.CASCADE) I want to change the output of the below print(a.job_title) statement: >>> a = A.objects.filter(job_title__isnull=False).last() get_db_prep_value get_prep_value >>> print(a.job_title) Developer -
Create template/model that use static-image when model is created and a real image-URL afterwards
I have a model class myModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) start_price = models.FloatField(default=0) image_url = models.URLFild(max_length=512,default="{% static 'media/wait_logo.png' %}") #Issue which should link to an initial image (wait_logo.png) when created. In views.py I have def MyView(request): user = request.user instance = myModel(user=user) if request.method == "POST": form = my_form(request.POST,instance = instance) if form.is_valid(): form.save(commit=False) . . . form.instance.image_url="some_real_image_url.com" #Update URL to real image . . . return redirect("my_site") else: form = myForm() return render(request, "my_site/my_template.html",context=context) (I know it does not matter having an initial image in the view above since the user won't see the new request before it's overwritten, but the view is just for illustration purposes) The problem I (think) I'm facing is, in the template; if I want to refer to a static image I can use <a href="{% static 'media/wait_logo.png' %} but when refering to the form-field (when it's a correct URL) it'll be <a href="{{context.image_url}}">. Simply setting default="{% static 'media/wait_logo.png' %}" does not work. How do I write my href such that it can refer to the initial-image uppon creation but also being able to show a real image URL when that is provided? I'm thinking about just uploading the wait_logo.png to our … -
How to access datatable values from a django url in my Flutter datatable?
I have a project which shows the values of volts and current etc... The actual source of the data is a Django URL, and I want to read that values in my flutter data table. How to do it... Note: I am not familiar with Django. I know only flutter & dart. Here is my Django code ss. On the left side is the code & on the right side is the output of which accessed by a URL. and here is my data table code of Flutter ```rows: [ DataRow( cells: [ DataCell( Text( 'Red', style: TextStyle( color: Colors.red, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R1'), ), DataCell( Text('$c2R1'), ), DataCell( Text('$c3R1'), ), ], ), DataRow( cells: [ DataCell( Text( 'Blue', style: TextStyle( color: Colors.blue, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R2'), ), DataCell( Text('$c2R2'), ), DataCell( Text('$c3R2'), ), ], ), DataRow( cells: [ DataCell( Text( 'Yellow', style: TextStyle( color: Colors.yellow, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R3'), ), DataCell( Text('$c2R3'), ), DataCell( Text('$c3R3'), ), ], ), ], ),``` Here is the output of the flutter code -
Bootstrap dropdown in each table row where the page refresh every five seconds not opening for a single record, but opens for multiple records Why?
I have a bootstrap dropdown, inside each table row cell. The page refresh in every five seconds. The dropdown will not open if single record appears but opens perfectly for multiple records. -
Django - Is it possible to access some content of one function from another function?
I have two functions in one of my Django-based projects, under the views.py file. Where the first function generates a view page and the second function is just returns some response based on jQuery request. Here's how they look like: First function that renders a show page: @login_required() def watchlist_details(request, iid): ... ... ... ... ... ... contracts = dict(enumerate(x.rstrip() for x in symbols)) automate = Automate() automate.init_symbol(contracts) automate.live_stream() ... ... ... ... ... ... return render(request, 'watchlist_show.html') Second function that will return some response on a jQuery call: def streaming_response(request): automate = Automate() # need to replace this with: automate = automate_of_first_function result = automate.get_stream_result() json_result = json.dumps(result) return json_result Here the problem is in the second function is, I reinitialize automate which does not have any content to generate a response. So, I need to access the method automate instance that is initialized in the watchlist_details function. As I follow function-based views in my Django apps rather than class-based views so there is no way to create a global/common variable. And I think Django does not allow the creation of more than one method in class-based views (and it is also a confusing concept for me). So my … -
'django-admin' is not recognized as an internal or external command, operable program or batch file
I have installed Django and my python path seems ok. whenever I try to create a new folder with the command line django-admin it is showing me up this message. I have tried reinstalling python but is not working. -
Django Celery - Some task messages are getting skipped
I've created a django-celery task. The task worker is hosted using supervisord. Normally whenever I call the method using celery's .delay() method a new task is received by the celery worker & immediately starts processing the same (as expected :D ) However, at frequent times this happens that we call the method using .delay() & receive no errors on main thread (where .delay was originally called). But as per the logs of the celery worker, the task never reaches it. Never seen such a behavior previously. Tried searching the docs as well as "SO" community, but can't get to why this is happening. The worker is up & free, redis-server is also up & running, after a few tries of adding new task, the worker receives the task again, without even restarting the worker. Thanks -
How would you make this interface in django? [closed]
I need to do something similar to this. What would be the best structure using classes and forms if I need to present them all together? At the time of creating a product I need: 1- add a model A. 2- Add one or more models B. 3- Add one or more models C. But I need each model to keep a key about the product. interface -
React rest-hooks authentication
I have to admit that I already asked this but it was answered correctly. But I can't still focus on how to authenticate against the backend. I have both sides: frontend (React) and backend (Django). I am reading the rest-hooks authentication documentation but I can't see how to use their resources the send the data and retrieve the token. Thanks to @LindaPaiste, "I" wrote this AuthResource.ts: import { Resource } from '@rest-hooks/rest'; import { API_URL } from '../utils/server'; export default class AuthResource extends Resource { static getFetchInit = (init: RequestInit): RequestInit => ({ ...init, credentials: 'same-origin' as const }); readonly email: string = ''; readonly password: string = ''; pk(parent?: any, key?: string | undefined): string | undefined { return; } static urlRoot = API_URL + 'auth-token/' } But, after reading the previous documentation I can't figure out which hook I should use. Is useFetcher(AuthResource.create(), { formData })? Just looking at it, you can tell is wrong..., but anyway...: import React, { useState } from 'react'; import { useFetcher } from 'rest-hooks'; import AuthResource from '../../../resources/AuthResource'; export default function LoginPage() { const create = useFetcher(AuthResource.create()); function submitForm(e: any) { e.preventDefault(); create({}, new FormData(e.target)); } return ( <div className="login-container"> <form className="login-form" … -
When I try to set the href attribute with Javascript, undesired text is added
I am developing on localhost: http://127.0.0.1:8000 When I do some search on the website, I want that if the query does not return results, the New entry button allows the creation of a new article from what has been searched in the search input. So if I search 'whatever' and there is no article called 'whatever', the button should redirect me to the creation page of the article 'whatever'. <script> $( document ).ready(function() { var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}"; document.getElementById('newEntrybtn').setAttribute('href',newEntryUrl); }); </script> {% for article in articles %} {% block wiki_search_loop2 %} {% endblock %} {% empty%} There is no page created for '{{ search_query }}', would you like to create a page nowee? <a class="btn btn-success" id="newEntrybtn" role="button"><i class="fa fa-plus" aria-hidden="true"></i> New entry ({{ search_query }})</a> {% endfor %} To calculate the url to create the new article, I use this line: var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}"; If I do an alert(newEntryUrl); it returns the desired result: 127.0.0.1:8000/wiki/_create/?slug=whatever However, if I click the newEntrybtn button, it redirects me to the following url: http://127.0.0.1:8000/wiki/_search/127.0.0.1:8000/wiki/_create/?slug=whatever Which is strange to me since at no time have I assigned the href attribute to the button, much less have I assigned it … -
How to Automatically Change English Typing from Korean Typing in Password Input in Django?
I'm working on Login Function using Django. I'd like to automatically change letters typed in Korean to English. For example, 가나다 -> rkskek How can I make it? I started yesterday, but still struggling with it.. Anyone could help me out!? FYI I've been trying Adding 'lang' attribute in password element -> Failed Using LoginView -> Failed