Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
adding a "navigate Back" and "navigate Forward" buttons in django templates
I want to add a btn in my navbar.html in django-templates, and every time client clicks it, he navigates to page previous to what he in on, and also "naviaget Forward" if clicked other button. how can i do it? -
tags will not store in database in django
Tags will not store in database in Django def addque(request): if request.method == "POST": user = request.user if user.is_anonymous: return redirect('addquery') if user.is_active: question = request.POST['question'] body = request.POST['body'] tags = request.POST['tags'] aquuid = request.user.aquuid addquery = Question(question=question, user_id=aquuid, que_body=body, tags=tags) addquery.save() return redirect('addquery') else: return render(request, 'question/ask.html') After giving the input the data is stored in the tags field but, not saving in the database. I can manually insert data through the admin panel successfully but not as a non-staff user. I have installed taggit and placed it in the installed_apps in settings.py. What is the issue with the code? -
Django Huey Crontab every day at 10am
I'm using Django 4.0.4 and huey 2.4.3. What I would like to atchieve it's to run a task everyday at 10am, using a periodic task. -
Django cant find static files 404error
I'm using django to create apps in the project. I'm going to make common files into templates and static folders under the project folder of the project. However, when the server is running, the files in the templates are found well, but the files in the static folder are not imported. I tried a few attempts through a search, but it didn't work, so I ask questions. I would appreciate an answer. setting.py STATIC_URL = '/static/' STATIC_DIRS = [ os.path.join(BASE_DIR, 'static'), # BASE_DIR / 'static', ] # STATIC_ROOT = os.path.join(BASE_DIR, 'assets') my folder structure project -app1 -app2 -templates -app1 -index.html -app2 -index.html -static -style.css -app.js html code {% load static %} <link href="{% static 'style.css' %}" rel="stylesheet" /> -
SubCategory name being displayed under every category
I know I have asked this question before , but I am really struggling with this problem I am doing CRUD using serializers and foreign keys and I am trying to dynamically display categories and sub categories however the issue is that Kurta ,Dhoti and other subcategories are getting displayed under every column, but I want it displayed only under 9-6 wear. Currently this is how it looks. below are the models class Category(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=30) category_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Category, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=30) sub_categories_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) function def shoppingpage(request): cat = Category.objects.filter(isactive=True) subcat = SUBCategories.objects.filter(isactive=True) hm = {'category':cat,'subcategory':subcat} return render(request,'polls/shoppingpage.html',hm) shoppingpage.html {% for result in category %} <div class="col-md-3"> <div class="lynessa-listitem style-01"> <div class="listitem-inner"> <a href="/9-6wear" target="_self"> <h4 class="title">{{result.category_name}}</h4> </a> {% for ans in subcategory %} <ul class="listitem-list"> <li> <a href="/kurta" target="_self">{{ans.sub_categories_name}}</a> </li> </ul> {% endfor %} </div> </div> </div> {% endfor %} -
Can't import requests in Django
I'm having problem importing requests in views.py. I've already installed requests in the environment and I already checked through Django shell by importing requests and there was no error. But every time I import requests in views.py I get the error ModuleNotFoundError. Can anyone help me. from django.shortcuts import render #from django.http import HttpResponse import json import requests #from matplotlib.style import context # Create your views here. # Think of views as a place to handle your various # web pages we are going to do this with either # functions based view or class basesd view def home_view(request, *args, **kwargs): print (args, kwargs) print ("This is the request") print ("Request has been Sent") putdata = {"supplier_name": "Django", "supplier_contact": "8000", "supplier_address": "America", "supplier_email": "Django@gmail.com", "supplier_state": "New York", "supplier_country": "America"} post = requests.post("http://localhost:8085/api/supplier", json=putdata) print(post.text) return HttpResponse("<h1>Hello World</h1>") # string of HTML code return render(request, "home.html", {}) I'm new to Django so forgive the messy code, I'm just trying various things in order to see how they work. -
Store user input using forms or models in Django?
I have a Django ML web app where the user inputs some values and the ML models calculates a value and return it. What I want to do is save those values entered by the user and later use those values to retrain the ML model. Basically the user input should be saved in the database and later I should be able to fetch it for retraining. I have a couple questions regarding this: 1.) Should I use forms for saving user input or should I use models? 2.) What is the difference between using forms or models for saving user input? Any links/material/tutorial would be appreciated! Thanks! -
Is it possible to make a web application with Tkinter? [duplicate]
I wrote a simple application with Tkinter which gets data from an .xlsc file and converts it to a document file. Now, I want to distribute my application as a web application. Can I do it without using Django? -
Django or python version issue: ModuleNotFoundError: No module named 'database'
when i try to start my Django project i get this error which i am unable to solve: ModuleNotFoundError: No module named 'database' The error stack: Traceback (most recent call last): File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/management/base.py", line 455, in execute self.check() File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/checks/caches.py", line 17, in check_default_cache_is_configured if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'database' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/olw/candidatis/database-rest/manage.py", line 22, in <module> main() File "/home/olw/candidatis/database-rest/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/olw/candidatis/database-rest/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() … -
Connect Django with Azure MS SQL Server DB using managed identity
How can I connect my Azure MS SQL Server Database to Django through managed Identity. Currently my Django settings.py file looks like this : DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'HPI_SI_DB', 'HOST': 'abcengine.database.windows.net', 'USER': 'xyz', 'PASSWORD': '*******', 'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server', } }, 'DB2': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'HPI_SI_DB', 'HOST': 'abcdengine.database.windows.net', 'USER': 'xyz', 'PASSWORD': '*******', 'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server', } } } -
How can I add Bootstrap class or css in the Ckeditor at Django for responsive?
I've taken RichTextField from CKEditor. But problem is, that the field is not responsive. It shows perfectly on the big screen but not on the mobile screen or the small screen. How can I responsive this for the mobile screen or the small screen? forms.py: from ckeditor.fields import RichTextField class update_product_info(forms.ModelForm): product_desc = RichTextField() class Meta: model = Products fields = ('product_desc') labels = { 'product_desc':'Description' } widgets = { 'product_desc':forms.Textarea() } settings.py: CKEDITOR_CONFIGS = { 'default': { 'toolbar':'Custom', 'FontSize':20, 'toolbar_Custom': [ ['Undo','Redo'], ['Styles','Font','FontSize','Bold','Underline','Italic','HorizontalRule','Flash'], ['TextColor','BGColor'], ['Table'] ] } } Template: <form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} {{form.media}} {{form.as_p}} <div class="d-flex align-items-center"> <button type="submit" class="btn btn-outline-dark ms-auto" value="Update" style="font-size: 13px;">Add</button> </div> </form> -
Django Consecutive Days and Max Consecutive days Query
I have a following model. class CategoryModel(BaseModel): name = models.CharField(max_length=100) icon = models.ImageField(upload_to=upload_icon_image_to) description = models.CharField(max_length=100) user = models.ForeignKey(User,on_delete=models.CasCade) def __str__(self): return self.name The basic idea is that whenever a user added a category In one day whether being 1 or 20 records it is regarded as 1 streak and if the user again adds a new category then it is regarded as a +1 streak so current streak will be 2 and max streak is also 2 if user consecutively adds for 5 days streak is 5 days as it is max streak. I just want to display as { "current_streak":3, "max_streak":12 } here current streak is 3 but previous streak set was 12 so it regarded as max streak Any Idea how I can achieve this query? -
Change default cookies name Django
I've more than 2 website stored under same domain due to budget of buying SSL for different domains. Is their any way that I can change or add suffix in default cookies and session variable name in django to avoid the login session confusion between different django projects ? Example: https://www.lmarts.in/ (Project-1) http://trenzact.com (It will redirect to https://www.lmarts.in/trenzact/) (Project-2) This are 2 different django project server under single django domain. The webserver used is nginx *Projects are still in development Thanks in advance!! -
cloudinary won't upload image in browser and shows empty image box
I'm supposed to upload images using cloudinary in my django app, but they won't upload in the browser. I can upload them from admin perfectly fine, though. The problem is my 'choose file' button lets me choose an image, but it won't display in my browser. And when I make a post, whether its a regular post or one with a picture, an empty box shows up and I can't get rid of it. I'll attach a screenshot for reference and show my code. Sorry if my explanation is confusing, I'm still new. <input type="file" id="img-select"> <script src="static/js/file.js"></script> <script> const imgInput = document.querySelector('#img-select') const imgPreview = document.querySelector('.preview') const pickerBtn = document.querySelector('.upload') imgInput.addEventListener('change', function() { const file = this.files[0] if(!file) return const reader = new FileReader() reader.addEventListener('load', function() { imgPreview.src = this.result }) reader.readAsDataURL(file) }) </script> screenshot for further info, that image was uploaded through admin. and that empty box towards the bottom of the screen is what I'm having trouble with -
Set Common Fields in ModelSerializer
Hi i am fairly new at this so it might be a silly question Suppose i have many model serializer but for eg lets take 4 below is the code class ModelSerializer1(ModelSerializer): class Meta: model = Model1 fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'] class ModelSerializer2(ModelSerializer): class Meta: model = Model2 fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'] class ModelSerializer3(ModelSerializer): class Meta: model = Model3 fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'] class ModelSerializer4(ModelSerializer): class Meta: model = Model4 fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'] I have other fields in these model serializer but these five fields are common in all the serializer so can i create a BaseModelSerializer so that i can inherit that in these serializer and ill get these fields by default and i dont have to write it again and again. if anyone can help thanks in advance -
How to Rectify Permission Issues in Centos while Serving Django applications via Apache + mod_wsgi?
I have a Django App Configured with via Apache and mod_wsgi The app has issues when current mode is enforcing while running: sestatus [root@localhost html]# sestatus SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: enforcing Mode from config file: enforcing Policy MLS status: enabled Policy deny_unknown status: allowed Max kernel policy version: 31 The error being shown on the webpage is: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. The error in logfile is: [Tue Jul 19 06:45:33.033587 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033591 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033592 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] During handling of the above exception, another exception occurred: [Tue Jul 19 06:45:33.033594 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] [Tue Jul 19 06:45:33.033597 2022] [wsgi:error] [pid 22355] [remote 166.175.xx.x:10600] Traceback (most recent call last): [Tue Jul 19 06:45:33.033645 2022] [wsgi:error] … -
Same Dynamic Data coming in every column of webpage
I am doing CRUD using serializers, foreignkeys and I am trying to dynamically list the categories, sub_categories. For example category = 9-6 wear and its subcategories are kurta, skirtset, dress, kurtaset. I want these subcategories below only 9-6wear The issue is that other subcategories are also mentioning kurta,skirtset,dress and kurtaset which I dont want as shown below I have tried for hours but without much success below are my models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=70) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=1000) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=30) category_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=30) sub_categories_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) below are the serializer class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=30) sub_categories_description = models.CharField(max_length=30) isactive = models.BooleanField(default=True) class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = "__all__" extra_kwargs = {'category_name': {'required': False}} class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" below is my shoppingpage function def shoppingpage(request): cat = Categories.objects.filter(isactive=True) category = CategoriesSerializer(cat,many=True) subcat = … -
django rest framework nested serializer crud operations . what required is to create a api which should be called only once to perform crud operations
models.py class User(models.Model): ROLE_CHOICES = ( ("admin","ADMIN"), ("staff","STAFF") ) username = models.CharField(max_length=256) password = models.CharField(max_length=256) firstname = models.CharField(max_length=256) lastname = models.CharField(max_length=256) email = models.CharField(max_length=256) role = models.CharField(max_length=256,choices=ROLE_CHOICES) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,) phone_number = models.IntegerField() company_name = models.CharField(max_length=256) I want to use nested serializer here to do crud operations. -
Using flask, how can I return a row of data as a list
I am trying to get my route to return a row in a list format but it appears to be returning a concatenation of the row items. How can I return the row of data in list format? Here is what I want it to return: ['field1', 'field2', 'field3', 'field4', 'field5'] What it appears to return is: ['field1' 'field2' 'field3' 'field4' 'field5'] Here is my app.py file: from flask import Flask, render_template, json, redirect, request import pandas as pd # Flask constructor app = Flask(__name__) # Data setup salary_table = pd.read_csv("salaries.csv") salary_table.fillna('', inplace=True) headings = list(salary_table.columns) print(headings) data = list(salary_table.values) print(data) # Homepage URL call @app.route("/") def home(): return render_template("home.html", headings=headings, data=data) @app.route('/GetPlayerInfo/<row>') def GetPlayerInfo(row): return row # Listener if __name__ == "__main__": app.run(port=2509, debug=True) Here is my home.html file: <html> <head> </head> <body> <div class="tableContainerDiv"> <table class="table"> <tr class="header"> {% for header in headings %} <th class="cell">{{header}}</th> {% endfor %} <th>Info</th> </tr> {% for row in data %} <tr class="row"> {% for cell in row %} <td class="cell">{{cell}}</td> {% endfor %} <td><a href="GetPlayerInfo/{{row}}">Info</a></td> </tr> {% endfor %} </table> </div> </body> </html> -
Unable to write in a file after django app deployment on aws ec2 using nginx and gunicorn
I have deployed my Django online judge project on AWS EC2 using Nginx and Gunicorn I am taking user code in a string variable and writing it to a file in my project directory and it's working fine in development server but after deployment the program unable to write code in the file. for eg:- lets say a user have submitted code in c++ language so I took that code in a string variable and I open the my .cpp file via open() function in my views.py and writing the code in it. filepath = os.path.join(settings.BASE_DIR, 'language', 'forcpp.cpp') cpp_code=open(filepath,"w") cpp_code.write(user_problem_code) cpp_code.close() I have tried to modify path in every possible way but got unlucky in every try I have my files in language folder in which I want to write user submitted code and my views.py are in problempg application my project directory structure: online_judge_project/ account/ homesrc/ language/ /* directory containing files in which I want to write */ forcpp.cpp media/ oj/ settings.py problempg/ /* application containing views.py */ views.py static/ staticfiles/ template/ manage.py may be the path I am using in development is different in EC2 server. I have develop this project on a windows machine and I am … -
(django) how to flatten an array inside of a dictionary to an array only
I am currently trying to handle the nested data in django. In my case, I want to remove the key "event_log" and flatten it to a simple array of dictionary only. { "event_log": [ { "date": 12-12-2000, "point": 500 }, { "date": 12-12-2001, "point": 700 } ] } The outcome should look like this: [ { "date": 12-12-2000, "point": 500 }, { "date": 12-12-2001, "point": 700 } ] I have tried adding a to_representation method to the serializer: class EventDateSerializer(serializers.ModelSerializer): event_log = EventLogSerializer(many=True, read_only=True) class Meta: model = EventDate fields = ['event_log'] def to_representation(self, instance): data = super().to_representation(instance) flatten_data = data['event_log'] for item in flatten_data: for key, value in item.items(): data[key] = value return data However, it turns out this method can only flatten nested dictionary instead of array inside of dictionary. Has anyone got an idea on how to flatten the array inside of the dictionary? Much appreciated. -
How Check ManyRelatedManager is None
-models.py class Role: name = models.CharFiled(max_length=100) comp = models.ForeignKey(Company, models.CASCADE, related_name="comp_roles") users = models.ManyToManyField(User, related_name='user_roles', related_query_name='user_role', through='UserRole') class UserRole(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) based on certain conditions I have two queries -in api_views.py: 1-Role.objects.filter(comp_id=self.comp_id).prefetch_related('users') 2-Role.objects.filter(comp_id=self.comp_id) -RoleSerializer.py class RoleSerializer(serializers.ModelSerializer): users = serializers.SerializerMethodField() def get_users(self, obj): #users: ManyRelatedManager = obj.users logger.info(f"this is obj.users: {obj.users}") logger.info(f"this is n obj.users: {obj.users == None}") # hit the db: # if not obj.users.all(): # if obj.users.exists() == None: # no hit the db: # if obj.users.all() == None: # if obj.users == None: if obj.users.all() == None: logger.info(f"obj.users is None!") return None logger.info(f"obj.users is not None!") serializer = UserReadSerializer(obj.users.all(), many=True) return serializer.data Either obj.users == None log or obj.users.all() == None codition are always false! My question is how can I find out obj.users or obj.users.all() (in RoleSerializer/get_users) is None? so I can decide to return whether None or UserReadSerializer data. -
How create filter for queryset Python django
can someone explain to me how to create a query with 3 sums with different filters for the same column using django's queryset? I tried to create using: sum1 = Sum("price", filter=Q(coins__=1)) sum2 = Sum("price", filter=Q(coins__=2)) sum3 = Sum("price", filter=Q(coins__=3)) but regardless of the filter, it receives the same value for the three filters. My table: Coin-in-out a - 1 - 2 b - 0 - 2 c - 3 - 3 a - 2 - 3 I need a single dictionary that receives the summed value and grouped by coin. -
I don't know why javascript is not working in the below mentioned code for back to top button for the blog page
The javascript in the base footer file is not working and that's why the back-to-top button in the base file is not working as expected. the functionality and all is working in the back-to-top button but the button is not visible because through javascript, I am adding a class active but it is not adding in this page but the base file is also linked to another page and there everything is working fine. I am not able to figure it out why it is not working. Below is the main blog file where base-home-footer file is linked to. {% extends 'media/assets/base-media.html' %} {% load main %} {% load static %} <!-- title start --> {% block title %}Prishni- Our Blog{% endblock title%} <!-- title end --> <!-- header start--> {% block header %} {% include 'assets/base-home-header.html' %} {% endblock header %} <!-- header end --> <!-- Content Start --> {% block mediaContent %} {% load markdownExtras %} <div class="wrapper _bg4586 _new89" id="main-content" role="main"> <div class="_215cd2"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="course_tabs"> <nav> <div class="nav nav-tabs tab_crse justify-content-center"> <a class="nav-item nav-link active" href=" {% url 'media:ourBlog' %} ">Blog</a> </div> </nav> </div> <div class="title129 mt-35 mb-35"> <h1 align="center">Insights, ideas, … -
How to fetchData when react component is in viewport
I am working on a social media type of project, using ReactJS & django, I don't know how do pagination in react (load more post when end of the page is reached) I have implemented pagination on backend using drf api endpoint is something like: /post/api/?page=2 response is like: { "prev": true, "next": true, "data": [...] }