Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selecting serializer field in the DRF browsable API
For example my model and its serializer: class Person(models.Model): name = models.CharField(max_length=150) age = models.IntegerField() city = models.CharField(max_length=150) class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' # to select these fields on the browsable API So my aim is to select serializer fields dynamically in order to post on the browsable API. I thought about adding a filterset class with a MultipleChoiceFilter field for serializer field names. class PersonFilter(filters.FilterSet): FIELD_CHOICES = ( (0, 'name'), (1, 'age'), (2, 'city'), ) field = filters.MultipleChoiceFilter(label='fields', choices=FIELD_CHOICES) class Meta: model = Person fields = ['field'] What I try to do is: Selecting the fields from the json query: { "name": "Jack", "age": 30, "city": "London", }, by using the filter on the browsable API : obtaining the subset of fields: { "name": "Jack", "city": "London", } At this point I couldn't find out how to manipulate the serializer fields variable from the filterset class. Also I don't know if it's a good practice to do it or there's a simpler way. -
how to create a rest api in python only? or how to run the py file on server?
I am trying to create a rest api in python without django or flask, is there any way to create a rest api only in normon python? and, is there any way to run the py file on server? -
adding a auto increment field to JSONfield in django
I have been able to insert data into my field which is JSONField through modelName.family_member.append({"name":'Brian King', "relationship":'Father', "occupation":'Engineer'}) But I wish to add an id field which would auto increase like it does in mysql so data call would be like {'id':1, "name":'Brian King', "relationship":'Father', "occupation":'Engineer'}, {'id':2, "name":'Demi King', "relationship":'Mother', "occupation":'Teacher'}, I am using Django and mysql as my database. My model declaration is like this. family_member = models.JSONField(default=jsonfield_default_value) Please how can I get this done -
How can I convert my Tkinter application to a web application?
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? There’s a similar question but I couldn’t understand the answer. -
python manage.py test not founding test files and changed folder name
I am running python manage.py test but my project file changes code intesad backend. enter image description here -
Auto increment rank field in my response in Django Rest Framework
I've a StudentAnswer model which stores the answer id given by the student(User) in a quiz. If the answer is correct then 1 marks else 0. The model looks like this: class StudentAnswer(models.Model): user = models.ForeignKey(User, related_name='user_question_answer', on_delete=models.SET_NULL,null=True, blank=True) answer = models.ForeignKey(QuizQuestionAnswer, related_name='user_answer', on_delete=models.CASCADE) quiz = models.ForeingKey(Quiz, on_delete=models.CASCADE) marks = models.IntegerField() Now I need my response to look something like this: { "rank": 1, "user": "John Doe", "marks": 10 }, { "rank": 2, "user": "Stanley", "marks": 8 } I don't have a rank field in my model. I want rank in my response and that too according to the marks of students(highest to lowest). How can I do it? Thanks in advance! -
Video streaming with django API and react-native
I'm working on a react-native app witch contains some videos, and when I put in source the uri: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4', from google samples, it actually works, but if I try to put a uri for a video contained in my django media folder, the following error occur: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". How can I solve? Thank you -
Why I am not getting images from django model in correct ways?
I have created a model in which there are many fields, one of which is the picture field. When I am storing the data from the admin panel the images are stored with the correct address in the database but when I am storing the images from an HTML form they are stored with another address so I am missing the images in my template. Here is my model in Django: class User(AbstractUser): picture = models.ImageField(upload_to='profile_pictures', null=True, blank=True) full_name = models.CharField(max_length=100, help_text='Help people discover your account by using the name you\'re known by: either your full name, nickname, or business name.') email = models.EmailField(blank=True) # Optional fields bio = models.TextField(null=True, blank=True, help_text='Provide your personal information, even if the account is used for a business, a pet or something else. This won\'t be a part of your public profile.') website = models.URLField(null=True, blank=True) phone_number = models.CharField(max_length=20, null=True, blank=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True, blank=True) is_private_account = models.BooleanField(null=True, blank=True) first_name = None last_name = None USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['full_name'] objects = CustomUserManager() def __str__(self): return self.email Here is the HTML form that I am using to store the data from the user: <form action="posts" method="POST"> {% csrf_token %} <input type="text" … -
How can I add a changeable "subfield" to a ModelField in django?
I'm trying to create a kind of "subfield" for a CharField in django, but I'm not sure (a) if it is possible at all and (b) how to succeed if it is indeed possible. Let's say I want a model for Tools. They would have a, e.g., a field for long_name, short_name, maybe a ForeignKey for realizing different departments. One of these tools I'd like to be a Link, the said "subfield" being a URLField with the href to the webpage. Now, I can create multiple link entries with the associated URL, but I'd rather have only one tool called "Link" with the changing URL attached. Is this a case for ForeignKey as well? Does it make sense to have a model with only one field (well, two if you count the pkid) in it? Or am I on a completely lost path here? Any guidance is appreciated. -
How to add multiple permission to user in django?
I want to add multiple permission for a user in single api request. I have a array of permission code name, how to pass it in the view? Is for loop is the only way? or any other ting will work? u = User.objects.get(username="admin_user_1") permission = Permission.objects.get(name="Can add user") u.user_permissions.add(permission) This code can be used for single permission -
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