Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error: ValueError: Field 'id' expected a number but got 'Нет'
I was adding a new model, but had the error ValueError: Field 'id' expected a number but got 'Нет'. After that I deleted a new model, but error don't disappear. I tried to change models.py, admin.py, form.py and I even deleted fully models.py, but it didn't change anything. models.py without choices class Card(models.Model): name = models.CharField("Наименование постановления" ,max_length=200) date = models.DateField("Дата вынесения:", null=True, blank=True) case_number = models.CharField("Номер дела:", max_length=40, null=True, blank=True) documents = models.URLField("Связанные документы (ссылки):", max_length=300, blank=True, null=True) trial = models.CharField("Наименование суда", max_length=37, choices=TRIALS, blank=True, null=True) instance = models.CharField("Инстанция:", max_length=12, choices=INSTANCE_CHOICES, blank=True, null=True) intial = models.CharField("Первоначальное решение первой инстанции", choices=REQUIREMENTS, blank=True, null=True, max_length=200) counter = models.CharField("Встречное решение первой инстанции", choices=REQUIREMENTS,blank=True, null=True, max_length=200) appellate = models.CharField("Решение апелляционной инстанции", choices=CHOICES, blank=True, null=True, max_length=200) cassation = models.CharField("Решение кассационной инстанции", choices=CHOICES,blank=True, null=True, max_length=200) proceeding = models.CharField("Вид судопроизводства:", max_length=16, choices=PROCEEDING_CHOICES, blank=True, null=True) first_dispute = models.CharField("Категория спора (подкатегория 1)", max_length=122, choices=FIRST_DISPUTE, blank=True, null=True) second1_dispute = models.CharField("Категория спора (подкатегория 2-1)", max_length=122, choices=SECOND1_DISPUTE, blank=True, null=True) second2_dispute = models.CharField("Категория спора (подкатегория 2-2)", max_length=122, choices=SECOND2_DISPUTE, blank=True, null=True) third_dispute = models.CharField("Категория спора (подкатегория 3)", max_length=122, choices=THIRD_DISPUTE, blank=True, null=True) review = models.CharField("История рассмотрения:", max_length=4, choices=YES_OR_NO_CHOICES, blank=True, null=True) original_claim = models.CharField("Первоначальное требование:", max_length=300, blank=True, null=True) counter_claim = models.CharField("Встречное требование:", max_length=300, blank=True, null=True) … -
How solve django-admin is not recognized...?
I'm trying: Django-admin startproject myweb This is what i see: 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable Even i added python27/Scripts to my pc environment variables but didn't work -
Is there any advantage or disadvantage to using reverse accessors vs direct queries?
I happen to be working on an existing project, that uses a lot of direct queries instead of reverse accessors. Take the following contrived example: class Student(Model): name = CharField(...) school = ForeignKey(School, ...) class School(Model): def get_daves(self): ... The 'get_daves' method on School could be implement in either of the following ways: def get_daves(self): return self.student_set.filter(name='Dave') def get_daves(self): return Student.objects.filter(school=self, name='Dave') And the project I'm working on, seems to have a lot of the latter, whereas I'd typically use the first option. Aside from being more succinct, and arguably clearer as to what you're intending, are there any other reasons to use the reverse accessor method, over querying the Students directly. I assume under the hood they result in equivalent DB queries, and the same amount of work constructing the models when the queryset is iterated. I just wanted to make sure there isn't a good reason to go ahead and start changing all of the instances of the direct queries in the project as I find them. -
I want to split name with space and tag_name with underscore. How can I split through jinja templating
Html file: {% for i in i|split:' ' %} <tr> <td> <p>{{ i }}</p> </td> <td> <p>{{ j }}</p> </td> </tr> {% endfor %} custom_tags.py from django import template register = template.Library() @register.filter(name='split') def split(obj, sub_strings): list1 = obj.name.split(" ") list2 = obj.tag_name.split("_") if "" in list1: list1.remove("") return [list1, list2] -
Why Does Djongo Gives Error While EveryThink Is OK? database is connected
i dont know why. but it works well on local pc and i putted it on CPanel its connected to database. but when i load a page. it gives dbError: this code works in localhost ( on my pc ) but when i uploaded it on cpanel it gives error ;/ ( db is on cpanel ) DBCode: The DBName and username and password is currect DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '(db names are currect)', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb://(entered username):(entered password)@localhost:27017/( iwrote db name)' } } } i got putted __in and [ ] cuz i heared that djongo needs booleans to be like this And Views.Py stores = Store.objects.filter(Premium__in=[True]) return render(request, 'base/home.html', context={'stores': stores}) Request Method: GET Request URL: https://www.storefa.xyz/home/ Django Version: 4.0.6 Python Version: 3.9.12 Installed Applications: ['captcha', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/storefax/StoreFa/base/templates/base/home.html, error at line 72 (Could not get exception message) 62 : </div> 63 : <br> 64 : <br> 65 : <br> 66 : <br> 67 : <div class="about-container"> 68 : <div class="kh kh-1"></div> 69 : <div class="kh kh-2"></div> 70 : <div class="kh kh-3"></div> 71 … -
Trying to hold Cart ID and product quantity through JQuery but its returning unidentified value
This is my HTML code <div class="col-sm-2 product_data1 border-left"> {% csrf_token %} <input type="hidden" class="product_id1" value={{ item.id }}> <select class="changeStatus" value={{ item.product_quantity }} name="quantity"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> And this is my JQuery var cart_id = $(this).closest('.product_data1').find('.product_id1').val(); var product_quantity = $(this).closest('.product_data1').find('.changeStatus').val(); var token = $('input[name=csrfmiddlewaretoken]').val(); -
Background tasks with Django on Heroku
So I'm building a Django app on Heroku. The tasks that the app performs frequently run longer than 30 seconds, and therefore I'm running into the 30s timeout by Heroku. I first tried solving it by submitting the task from my Django view to AWS lambda, but in that case, the view is waiting for the AWS Lambda function to finish, so it doesn't solve my problem. I have already read the tutorials on Heroku on handling background tasks with Django. I'm now faced with a few different options on how to proceed, and would love to get outside input on which one makes the most sense: Use Celery & Redis to manage the background tasks, and let the tasks be executed on AWS Lambda. Use Celery & Redis to manage the background tasks, but let the tasks be executed in a Python script on Heroku. Trying to solve it with asyncio in order to keep it leaner (not sure whether that specific case could be solved with asyncio, though? Maybe there's an even better solution that I don't see? Looking forward to any input/suggestions! -
Django Google Spreadsheet backup
I want to backup my data to Google Spreadsheet in Django project. I will get an access token shared by google from front-end (mobile app and web app - both). Now I need to, authenticate to google drive using that access token after that get list of the file in google drive if my required file exist then get that file if my required file doesn't exist then create an file and get that write backup data in spreadsheet close Now step by step I want to do this. I need exact solution, I studied google drive, google spreadsheet API documentation for Python. But that is not working for me. I need to implement this in Django. -
Sub Category Name not coming despite the if condition coming as True
I am aware that I have asked this question before but I am really struggling and unable to solve this question I have made product CRUD using serializers and foreign keys and I am making a dynamic page with categories and subcategories. The issue is that despite the if condition passing the sub categories are not getting printed only category_name is there as shown below models: class Products(models.Model): categories = models.ForeignKey(Category,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 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) below is the 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> {% if ans.category_name == result.category_name %} <a href="/kurta" target="_self">{{ans.sub_categories_name}}</a> {% endif %} </li> </ul> {% endfor %} </div> </div> </div> {% endfor %} Help is greatly appreciated thanks! -
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.