Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the value of a form in html to django
<form action="{% url 'search' %}" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> How can I get the value of q to views.py def search(request): return render(request, "encyclopedia/search.html") Should I make it a post request instead of a get and then take the value. Help me plz -
How can I make my form page resposive design in Django?
I have a form page with Django 1.11.10. I want to desing it responsive for all screen sizes. In phones and tabletes I want to not need to zoom in. Here is my html : {% extends 'base.html' %} {% load bootstrap3 %} {% block content %} <div class="form-body"> <div class="row"> <div class="form-holder"> <div class="form-content"> <div class="form-items"> <div class="row"> <div class="col-xs-11"> <h1>WARRANTY REGISTRATION</h1> <br><br> <form class="requires-validation" method="POST" novalidate> {% csrf_token %} {{form.as_p}} <div class="form-button"> <button id="submit" type="submit" class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> </div> </div> </div> </div> {% endblock %} -
How to validate foreign key with APIView
I'm learning django rest framework at school and now I'm on a internship project, I have some doubts using API base View. I want to do a POST in a endpoint and validate if the foreign key exists or not. My models: # TABELA DOS FORNECEDORES class Fornecedor(models.Model): nome = models.CharField(max_length=100, null=False, blank=False) endereco = models.CharField(max_length=100, null=False, blank=False) codigo_postal = models.CharField(max_length=8, null=False, blank=False) cidade = models.CharField(max_length=50, null=False, blank=False) nif = models.IntegerField( null=False, blank=False, unique=True, validators=[ RegexValidator(r"[1-9]\d*"), MinLengthValidator(9), MaxLengthValidator(9), MaxValueValidator(999999999), MinValueValidator(1), ], ) email = models.EmailField(max_length=50, null=False, blank=False) data_registo = models.DateTimeField(auto_now_add=True) data_ultimo_login = models.DateTimeField(auto_now=True) ativo = models.BooleanField(default=True, null=False, blank=False) def __str__(self): return self.nome # TABELA DAS MARCAS class Marca(models.Model): nome = models.CharField(max_length=55, null=False, blank=False) fornecedor = models.ForeignKey( Fornecedor, on_delete=models.CASCADE, null=False, blank=False ) def __str__(self): return self.nome My serializers class FornecedorSerializer(serializers.ModelSerializer): class Meta: model = Fornecedor fields = "__all__" class MarcaSerializer(serializers.ModelSerializer): class Meta: model = Marca fields = "__all__" My views class FornecedorPOST(APIView): @swagger_auto_schema( operation_summary="Criar um Fornecedor", operation_description="Criar um novo Fornecedor", request_body=FornecedorSerializer, responses={ status.HTTP_201_CREATED: response_201(FornecedorSerializer), status.HTTP_400_BAD_REQUEST: response_400(FornecedorSerializer), }, ) def post(self, request, format=None): fornecedor = FornecedorSerializer(data=request.data) if fornecedor.is_valid(): fornecedor.save() return Response(fornecedor.data, status=status.HTTP_201_CREATED) return Response(fornecedor.errors, status=status.HTTP_400_BAD_REQUEST) class MarcaPOST(APIView): @swagger_auto_schema( operation_summary="Criar uma marca", operation_description="Criar uma nova marca", request_body=MarcaSerializer, responses={ status.HTTP_201_CREATED: response_201(MarcaSerializer), status.HTTP_400_BAD_REQUEST: response_400(MarcaSerializer), }, … -
Got stuck in 'grid-template-columns' in CSS
I am currently learning Django and got stuck. I have created 3 divs inside of an home container and written this CSS code for the home container -> <style type="text/css"> .home-container{ display: grid; grid-template-columns: 1fr 3fr 1fr; } </style> I have created 'grid-template-columns: 1fr 3fr 1fr;' but I am not getting a column for the third div(i.e. 1fr). The third div's content is coming below the second div. Here is the whole source code. -> {% extends 'main.html' %} {% block content %} <style type="text/css"> .home-container{ display: grid; grid-template-columns: 1fr 3fr 1fr; } </style> <div class="home-container"> <div> <h3>Browse Topics</h3> <hr> <a href="{% url 'home' %}">All</a> {% for topic in topics %} <div> <a href="{% url 'home' %}?q={{topic.name}} ">{{topic.name}}</a> </div> {% endfor %} </div> <div> {% if room_count != 0 %} <h5>{{room_count}} rooms available.</h5> {% else %} <h5>No rooms available.</h5> {% endif %} <a href="{% url 'create-room' %}">Create Room</a> <div> {% for room in rooms %} <div> {% if request.user == room.host %} <a href="{% url 'update-room' room.id %}">Edit this room</a> <a href="{% url 'delete-room' room.id %}">Delete this room</a> {% endif %} </div> <div> <span>@{{room.host.username}}</span> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> <div> … -
Django: Update a value in html page without refreshing the page
I have a Rest API which I receive data every 10 seconds. I receive the data with time information that when the data sent. So, user should see the soonest data on the page. That code would work but that also wont update the data without a refresh: def get_datas(request): data = //find the soonest data return render(request, 'page.html', {'data': data}) What is the best solution for this? -
Problem fetching an equation from Excel Django
I have an excel file with a simple math equation In cell C1 it is A1 + B1 and I want to fetch the result of C1 in Django but it returns me nan...... is there a way to solve this problem? I use the pandas library! -
Django RQ ModuleNotFoundError xxx is not a package
I'm using django rq for some long running task, which I would like to provide some feedback about its progress. I hence created a function which is enqueued as a new task and set some model's attribute and save them. Here is a simplified view: class Status(models.Model): progress_a = models.PositiveIntegerField(default=0) class MyObject(models.Model): status = models.OneToOneField(Status) @django_rq.job('low-short') def set_status(self, progress_name, progress): setattr(self.status, progress_name, progress) self.status.save() def set_status_a(self, progress): self.set_status.delay(self=self, progress_name="progress_a", progress=progress) @django_rq.job('default') def long_running_job(): my_instance.set_status_a(100) Now, executing this give me the following output : 2022-05-16 15:50:03 app-85c8459c79-mrkhg rq.worker[1] INFO low-short: api.models.MyObject.set_status(progress=0, progress_name='progress_a', self=<MyObject: MyObject object (129)>) (c13480ca-a25b-4463-af9a-a0a0dd67de61) 2022-05-16 15:50:03 app-85c8459c79-mrkhg root[41] WARNING Import error for 'api.models.MyObject' Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/rq/utils.py", line 141, in import_attribute module = importlib.import_module(module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 981, in _find_and_load_unlocked ModuleNotFoundError: No module named 'api.models.MyObject'; 'api.models' is not a package api is a package api.models a module models.MyObject a class. I don't get why it doesn't work. What am I doing wrong ? long_running_job starts as a job flawlessly. Note: when removing self=self, it complains about missing self. -
Django cache doesn't invalidate on change
A cached page should be invalidated when something changes at the underlying resource. Django implements "site-wide" caching and I used this guide to setup my caching infrastructure (locally to test for now). CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" CACHE_TTL = 60 * 60 * 1 CACHE_MIDDLEWARE_SECONDS = CACHE_TTL When I run my tests now, it works too well, as all tests fail, which change information in the database. Do I have to manually add a flag for cache invalidation? Should this even work (or are my settings wrong)? I saw this question, but in my case I don't use any decorators, but the side wide caching. Nevertheless I tested using the vary_on_headers('Authorisation',) which didn't change the test results. -
The data/content isn't getting displayed. Can anyone please let me know any necessary changes to render the data?
Models.py class Question(models.Model): # id = models.AutoField(primary_key=True) question=models.CharField(max_length=600) option1=models.CharField(max_length=200, default=None) option2=models.CharField(max_length=200, default=None) option3=models.CharField(max_length=200, default=None) option4=models.CharField(max_length=200, default=None) views.py def Practice_all(request): practice = Question.objects.all() context={ 'question_list': practice } return render(request, 'practice.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("practice/", views.Practice_all, name="practice"), ] practice.html {% extends 'base.html' %} {% block content %} {% for data in question_list %} <li> {{ data.option1 }} </li> <li> {{ data.option2 }} </li> <li> {{ data.option3 }} </li> {% endfor %} {% endblock %} These are the Django files that I am using, the server runs perfectly but won't display anything, not even any errors, just blank. Any suggestions? -
Handling one template with multiple Django function
I have a template which contains feature to "fetch" the details and "edit" using Bootstrap Modal, from a API. I created 2 functions, one to display data and one to edit views.py def add_bom(request): ... context = {"sku_object": sku_object} return render(request, 'BOM/add-bom.html', context=context) def edit_bom_activity(request, bomNo, activity): ... context = {"filter_activity": filter_activity} return render(request, 'BOM/add-bom.html', context=context) Urls.py path('add_bom/', views.add_bom, name="add_bom"), path('edit_bom_activity/<str:bomNo>/<str:activity>/', views.edit_bom_activity, name="edit_bom_activity"), Since the template are same it is not somehow entering in edit_bom_activity function. Alternatively I tried to pass parameter in add_bom/ as path('add_bom/<str:bomNo>/<str:activity>/', views.add_bom, {'bomNo': None, 'activity': None}, name="add_bom"), But still I couldnt get the success. Is there a way on how to allow single template with multiple functions. -
How to stop Django inserting null columns for NoSql DB
I user django and mongodb for my project. I want to stop django orm from inserting null columns to DB. Here is some of my django files: # models.py from django.db import models class Ad(models.Model): user_id = models.IntegerField() title = models.CharField(max_length=100) description = models.CharField(max_length=500) fee = models.CharField(max_length=20) phone = models.CharField(max_length=10) location = models.CharField(max_length=50, default="") category = models.CharField(max_length=25) est_rooms = models.CharField(max_length=10) est_area = models.CharField(max_length=10) est_age = models.CharField(max_length=10) # views.py a = Ad.objects.create(user_id=request.user.id, title=title, description=description, fee=fee, phone=phone, location=location, category=category, est_rooms=est_rooms, est_age=None) a.save() For example, if I insert as above although I did not give anything for est_area, it inserts est_area="", but I don't want this. Instead, I want django orm not to insert est_area property. Could anyone help me? -
WordPress blog in Subdirectory of Django website on a CPanel Host
As I read articles and questions online, I believe it is possible; My main question is how to achieve this goal? I have Django Website with some urls on my domain (I use Setup Python App plugin on CPanel). I can simply achieve this using a subdomain, but I want to run my WordPress blog on a subdirectory, but every url that is not registered in urls.py will raise an error. What's the best way to reach this goal? What are the steps that I need to take to reach it? I will be more than greatful if you point me towards the right direction. Thanks in advance. -
only first row executing in the loop inside the array in python
I'm trying to loop through all the JSON inside the array, after the first row loop ends it's just iterated only the first row inside the array and then loop ends. How could I able to loop through all the rows inside the array here, what I tried views.py: @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': for ran in request.data: auditorid =ran.get('AuditorId') ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = ran.get('SID') TicketType = ran.get('TicketType') TypeSelected = ran.get('TypeSelected') agents = ran.get('Agents') supervisor = ran.get('Supervisor') Comments = ran.get('Comments') action = ran.get('Action') subfunction = ran.get('AuditSubFunction') region = ran.get('AuditRegion') Qstans = str(qid)+'|'+ answer+'&&' cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@agents=%s,@supervisor=%s,@ticketid=%s,@Qstans=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s, @Comments =%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,agents,supervisor,ticketid, Qstans,sid, TicketType, TypeSelected, Comments, action, subfunction,region)) result_st = cursor.fetchall() for row in result_st: return Response({0:row[0]}) here is the payload -
How to load data outside Django view?
If i have some Django views like 'first', 'second' and so on, and i want to load some data outside this views but use it inside views. Here is an example to understand my idea. #function execution time is long, that is why i want to laod it only once when run programm. fetched_data_from_postgres = some function which load data from postgres and return list with postgres data def first(request): #and the i want to use that previous value in all my views fetched_data_from_postgres = do something return HttpResponse("first VIEW") def second(request): #and the i want to use that previous value in all my views fetched_data_from_postgres = do something return HttpResponse("secondVIEW") def third(request): #and the i want to use that previous value in all my views fetched_data_from_postgres = do something return HttpResponse("third VIEW") this aproach working well when i run my django project like this python manage.py runserver but when i run with gunicorn or wsgi when i can specify workers count then when worker changes then this variable is lost and need to refresh page to get this previous worker to get that data. It's ridiculous. Or maybe there is some other aproach to do this job? -
how do i icrement a filed on a model name:''order count' when an another model object is created in django
I have two models Customer and Order and I want to make 3 fields that are updating when an Order object is created. the fields are Order_Count:--, First_Order:order_date, Last_Order: order_date how do I do this? Customer model: class Customer(models.Model): GENDER_CHOICES = ( ('MALE', 'male'), ('FEMALE', 'female'), ('OTHER', 'other') ) SOURCES = ( ('android', 'Android'), ('ios', 'IOS') ) customer = models.ForeignKey(User, related_name='customer', on_delete=models.CASCADE) image = models.ImageField(upload_to='customer_images/', null=True, blank=True) social_image_url = models.TextField(null=True, blank=True) dob = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True, blank=True) lati = models.CharField(max_length=100, null=True, blank=True) long = models.CharField(max_length=100, null=True, blank=True) fb_id = models.CharField(max_length=50, null=True, blank=True) google_id = models.CharField(max_length=50, null=True, blank=True) gapple_sub = models.CharField(max_length=50, null=True, blank=True) notifications = models.BooleanField(default=True) payment_token = models.CharField(max_length=200, null=True, blank=True) source = models.CharField(max_length=10, choices=SOURCES, null=True, blank=True) a_v = models.CharField(max_length=20, null=True, blank=True) def __str__(self): # return "%s" % self.customer.get_full_name() return f'{self.id} - {self.customer.get_full_name()}' and Order model: class Customer(models.Model): GENDER_CHOICES = ( ('MALE', 'male'), ('FEMALE', 'female'), ('OTHER', 'other') ) SOURCES = ( ('android', 'Android'), ('ios', 'IOS') ) customer = models.ForeignKey(User, related_name='customer', on_delete=models.CASCADE) image = models.ImageField(upload_to='customer_images/', null=True, blank=True) social_image_url = models.TextField(null=True, blank=True) dob = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True, blank=True) lati = models.CharField(max_length=100, null=True, blank=True) long = models.CharField(max_length=100, null=True, blank=True) fb_id = models.CharField(max_length=50, null=True, blank=True) google_id = … -
Django: ajax not returning or sending any data in django
i am creating a simple like button with ajax, i have followed the tutorial but it seems, that i am missing something, i am not getting any error either in the console in my django terminal but when i click the button no data get sent, evrything just remains the same way, and this is not what i am expecting, i know i am missing something somewhere and i cannot really tell where this error is coming from. views.py @login_required def like(request): if request.POST.get("action") == 'post': result = "" id = int(request.POST.get('courseid')) course = get_object_or_404(Course, id=id) if course.like.filter(id=request.user.id).exists(): course.like.remove(request.user) course.like_count -= 1 result = course.like_count course.save() else: course.like.add(request.user) course.like_count += 1 result = course.like_count course.save() return JsonResponse({'result': result}) urls.py NOTE:I don't know if i need a slug in this url path path('like/', views.like, name="like"), base.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> course-detail.html <li><button id="like-button" value="{{course.id}}">like</button><span id="like-count">{{course.llke_count}}</span></li> <script type="text/javascript"> $(document).on("click", '#like-button', function(e){ e.preventDefault() $.ajax({ type: 'POST', url: '{% url 'course:like' course.slug %}', data: { courseid: $('#like-button').val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(), action: 'post' }, success: function(json){ document.getElementById("like-count").innerHTML = json['result'] console.log(json) }, error: function (xhr, errmsg, err) console.log(xhr) console.log(errmsg) console.log(err) }) }) </script> this is all the code i have written for the functionality, if there is any other … -
Socket connection don't work properly on Heroku
I'm trying to get some messages from a server using socket in my Django web app. This works correctly in local but don't works when i deploy it on Heroku. The problem seems to be that I cannot receive all responses from the server in an adequate time. Procfile: web: gunicorn app.wsgi --log-file - The client connection I built has this structure. def connection(self, hostname: str, port: int, messages: list) -> str: s: socket.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock: ssl.SSLSocket = ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1_2) sock.connect((hostname, port)) sock.settimeout(1) for message in messages: sock.sendall(message.encode()) data: str = '' while True: try: # get response from server resp = sock.recv(1024) data += resp.decode("UTF-8") if resp == b'': data = None break except socket.timeout: # expired time to receive data break # close connection sock.close() return data -
Django uploaded file validation leads to "InMemoryUploadedFile is not supported"
I have a template where the user can choose and upload a file from their computer. The file is eventually uploaded to S3, but is first validated using custom validation to check some contents of the file. For checking the contents, the script reads the lines of the file in forms.py: from io import TextIOWrapper class UploadForm(forms.ModelForm): class Meta: model = MyModel fields = ('myfilefield',) def clean_myfilefield(self): file = self.cleaned_data['myfilefield'] read_file = TextIOWrapper(self.cleaned_data.get('myfilefield'), encoding='ASCII') headerCounter = 0 for line in read_file: if ">" in line: headerCounter += 1 if headerCounter > 1: error = "Custom error message 1" raise ValidationError(error) if headerCounter == 0: error = "Custom error message 2" raise ValidationError(error) return file The validation messages are correctly displayed, but if the file passes validation I get this error message (assuming myfile.txt is the uploaded file): Input myfile.txt of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported. The validation and uploading works fine if I leave out the TextIOWrapper part and the error checks. So I guess there's something about reading the file that converts it to a InMemoryUploadedFile, which is not compatible with uploading the file? I tried finding solutions for "converting" the InMemoryUploadedFile back to a "regular" (?) file, … -
How to use order_by when using Django group_by, take out all fields
I used Django-orm,postgresql, Is it possible to query by group_by and order_by? this table | id | b_id | others | | 1 | 2 | hh | | 2 | 2 | hhh | | 3 | 6 | h | | 4 | 7 | hi | | 5 | 7 | i | I want the query result to be like this | id | b_id | others | | 1 | 2 | hh | | 3 | 6 | h | | 4 | 7 | hi | or | id | b_id | others | | 4 | 7 | hi | | 3 | 6 | h | | 1 | 2 | hh | I tried Table.objects.annotate(count=Count('b_id')).values('b_id', 'id', 'others') Table.objects.values('b_id', 'id', 'others').annotate(count=Count('b_id')) Table.objects.extra(order_by=['id']).values('b_id','id', 'others') -
how to connect to the django testing databse correctrly?
I have a problem with django testing database. I use setUp method like this: def setUp(self): super().setUp() self.obj1 = MyModel.objects.create(name="name1") self.obj2 = MyModel.objects.create(name="name2") self.obj3 = MyModel.objects.create(name="name3") But when I try to connect to testing database: import psycopg2 from psycopg2 import sql db_uri = settings.DB_URI.replace("/db_name", "/test_db_name") con = psycopg2.connect(db_uri) cur = con.cursor() and execute: query = sql.SQL( "select * from {table};" ).format( table=sql.Identifier("mymodel_table_name"), ) cur.execute(query) print('result', cur.fetchall()) In result I see the empty list. BUT! If I insert something in testing database: query = sql.SQL( "insert into {table} (id, name) values ({id}, {name});" ).format( table=sql.Identifier("mymodel_table_name"), id=sql.Literal(some_id), name=sql.Literal(some_name), ) cur.execute(query) I see it in ORM, when I execute: MyModel.objects.all() My purpose is get in test_db_name all objects, which I insert in setUp method. Thank you for any help! -
How to show different menu on sidebar for each page in django?
I have 2 navigation bar, one is in the top and the second is in the side. In my top navbar, I have 3 different menu, namely "Dashboard", "Manage" and "Report". I want it to display different items in my sidebar when clicking one the menu in my top navbar. Something like this: In my "Dashboard" (the Dashboard in the top navbar will get highlighted) and will display the following on my sidebar: - dashboard-item-no1 - dashboard-item-no2 - dashboard-item-no3 In my "Manage" (the Manage in the top navbar will get highlighted) and will display the following on my sidebar: - manage-item-no1 - manage-item-no2 - manage-item-no3 In my "Report" (the Report in the top navbar will get highlighted) and will display the following on my sidebar: - report-item-no1 - report-item-no2 - report-item-no3 Can anyone please help me? I saw similar problem but it's in php and not django so I've been stuck with this problem for almost a week by now :'( -
DRF : How to sum value from nested object and order by sum value
I've created serializing nested be using serializers as document models.py class Category(models.Model): name = models.CharField("Name", "name", max_length=255) iconname = models.CharField("Icon Name", "iconname", max_length=255) budgetamount = models.DecimalField( max_digits=19, decimal_places=2, default=0) iconcolor = models.CharField( "Icon Color", "iconcolor", default='4294951175', max_length=255) def __str__(self): return self.name class DailyExpense(models.Model): payee_item_desc = models.CharField( "Payee Item Description", "payee_item_desc", max_length=255) category = models.ForeignKey( Category, related_name='dailyexpense_category', on_delete=models.CASCADE, blank=True, null=True) amount = models.DecimalField(max_digits=19, decimal_places=2) remarks = models.CharField( "Remarks", "remarks", max_length=255, blank=True, null=True) tran_date = models.DateTimeField() isnotclear = models.BooleanField(default=False) def __str__(self): return self.payee_item_desc serializers.py class DailyExpenseSerializer(serializers.ModelSerializer): class Meta: model = DailyExpense fields = "__all__" class CategoryWithDailyExpenseSerializer(serializers.ModelSerializer): dailyexpense_category = DailyExpenseSerializer( source='filtered_dailyexpense_category', many=True, read_only=True) class Meta: model = Category fields = ('id', 'name', 'iconname', 'budgetamount', 'iconcolor', 'dailyexpense_category') views.py class CategoryWithDailyExpenseViewSet(viewsets.ModelViewSet): def get_queryset(self): fromDate = parse_datetime(self.request.query_params.get( 'fromDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S') toDate = parse_datetime(self.request.query_params.get( 'toDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S') queryset = Category.objects.prefetch_related( Prefetch('dailyexpense_category', queryset=DailyExpense.objects.filter( tran_date__range=[fromDate, toDate]).order_by('tran_date'), to_attr='filtered_dailyexpense_category') ) return queryset # queryset = Category.objects.all().order_by('name') serializer_class = CategoryWithDailyExpenseSerializer filter_class = CategoryFilter And the result that I got as below [ { "id": 2, "name": "Foods:Breakfast", "iconname": "emoji_food_beverage", "budgetamount": "0.00", "iconcolor": "4294951175", "dailyexpense_category": [ { "id": 24574, "payee_item_desc": "เซเว่น", "amount": "-100.00", "remarks": "เฟิส", "tran_date": "2022-04-01T00:00:00Z", "isnotclear": false, "category": 2 }, { "id": 19933, … -
Update Graph with Select Boxes as Axis from template - Django
So I have this Django app where I want to plot some graphs and give the user the possibility to change the Axis from 2 select boxes from template. The options from the select boxes are actually Columns from a data frame. The problem that I have is that every time I change the option from one select box, the other one will set itself to None value. I am not using form because I don't want any submit button. I know in Dash there is this Dash no_update feature that doesn't update the graph until both select boxes have an option set. Now , I am new to jquery,js,ajax. The ajax call is doing his job but one selectbox at a time. Thanks Views.py def dashboard(request): cool_data = manage_pandas(df_raw) posnr=cool_data['posnr'].unique() x1 = request.GET.get('x') y1 = request.GET.get('y') dff = cool_data.loc[cool_data['posnr'] == pos] dff = dff.astype({'vnum': str}) dff = dff.drop('posnr', axis = 1) col = dff.columns if x1 is None and y1 is None: print("Nothing selected") #Dummy plot plot_div = plot([Scatter(x=[1], y=[2], mode='lines', name='test', opacity=0.8, marker_color='green')], output_type='div') else: print(x1,y1) x_axis = dff[x1] y_axis = dff[y1] plot_div = plot([Scatter(x=x_axis, y=y_axis, mode='lines', name='test', opacity=0.8, marker_color='green')], output_type='div') context = { 'posnr' : posnr, 'plot_div':plot_div, … -
How to update the django model when it does not detect changes?
I encounter an error on my Django application, I cannot update my models thanks to makemigrations It returns "No changes detected" My database is in postgresql My app is well saved in my settings.py file and I have the migrations folder inside the app, I don't see where the problem can come from. Do you have any idea what it could be? -
Error in django code server running on local (Cannot resolve keyword 'jan' into field)
I'm using the code below in Django. In local it works without errors. However, when I upload the same code to the server, an error occurs. def get_last_day_of_month(day): next_month = day.replace(day=28) + timedelta(days=4) return next_month - timedelta(days=next_month.day) def statistic(request): parameter = request.GET.get('team') today = datetime.today() monthly_kwargs = {} for i in range(1, 13): gte = datetime(today.year, i, 1) lte = get_last_day_of_month(date(today.year, i, 1)) mo = f'{gte:%b}'.lower() monthly_kwargs[mo] = Count('student_id', filter=Q(enroll_date__gte=f'{gte:%Y-%m-%d}', enroll_date__lte=f'{lte:%Y-%m-%d}')) monthly_kwargs['SPECIAL_' + mo] = Count('student_id', filter=Q(enroll_date__gte=f'{gte:%Y-%m-%d}', enroll_date__lte=f'{lte:%Y-%m-%d}', student__id__in=SPECIAL)) monthly_kwargs['total'] = Count('student_id', filter=Q(enroll_date__year=today.year)) monthly_kwargs['SPECIAL_total'] = Count('student_id', filter=Q(enroll_date__year=today.year, student__id__in=SPECIAL)) value_list_args = ['uploader_id', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'total', 'SPECIAL_jan', 'SPECIAL_feb', 'SPECIAL_mar', 'SPECIAL_apr', 'SPECIAL_may', 'SPECIAL_jun', 'SPECIAL_jul', 'SPECIAL_aug', 'SPECIAL_sep', 'SPECIAL_oct', 'SPECIAL_nov', 'SPECIAL_dec', 'SPECIAL_total'] if not request.GET or parameter == 'ALL': monthly_enroll = Feedback.objects \ .values('uploader_id').distinct() \ .order_by('uploader_id') \ .annotate(**monthly_kwargs) \ .values_list(*value_list_args) \ .order_by('uploader_id') else: monthly_enroll = Feedback.objects \ .values('uploader_id').distinct() \ .order_by('uploader_id') \ .annotate(**monthly_kwargs) \ .values_list(*value_list_args) \ .order_by('uploader_id') monthly_enroll_list = [list(i)[0:27] for i in monthly_enroll] return render(request, 'pages/research/statistic.html', { 'parameter': parameter, 'monthly_enroll_list': monthly_enroll_list, }) Error is: Cannot resolve keyword 'jan' into field. Choices are: SPECIAL_total, student, memo, total Looking closely at the error, it seems that the variable 'monthly_kwargs[mo]' is not set properly. I can see that …