Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How do I update my inventory in the database of only the boxes that are checked?
I am creating a web application that will serve as a grocery store. I want it to work in a way so that when customers click on the checkbox and click submit, then the database will subtract the inventory quantity by 1. I am having trouble being able to capture the information from the checkboxes and then using that to subtract 1 from the inventory. models.py class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'Price', 'Sale', 'quantity', 'category',] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): Post = self.get_object() #editor = self.get_object() if self.request.user == Post.author: return True return False home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} {% if post.quantity > 0 %} <input type="checkbox" name="product[]" id=" {{ post.id }} "> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.category }}</a> </div> <h2><a class="article-title" … -
template doesnot exist errror in django
Hi I am beginner and I am trying to do a sign up login and logout pages but I am getting template doesnot exist error my views.py is from django.shortcuts import render,redirect from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: User.objects.get(username = request.POST['username']) return render (request,'templates/accounts/signup.html', {'error':'Username is already taken!'}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'],password=request.POST['password1']) auth.login(request,user) return redirect('home') else: return render (request,'templates/accounts/signup.html', {'error':'Password does not match!'}) else: return render(request,'templates/accounts/signup.html') def login(request): if request.method == 'POST': user = auth.authenticate(username=request.POST['username'],password = request.POST['password']) if user is not None: auth.login(request,user) return redirect('home') else: return render (request,'templates/accounts/login.html', {'error':'Username or password is incorrect!'}) else: return render(request,'templates/accounts/login.html') def logout(request): if request.method == 'POST': auth.logout(request) return redirect('home') my folder structure project name : -mysite -accounts(app name) - templates - accounts -base.html -login.html -signup.html please help me out thanks in advance error: TemplateDoesNotExist at /accounts/signup/ templates/accounts/signup.html my template configuration in setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Elastic Search 7 Python-Django Find the percentage matching the text
I have installed elastic-search 7. With Python3 and Django2. For the Django part i have used Elasticsearch DSL. What i want is to find the text is duplicate or matching over 90%. e.g : Data : ['Hi Jon Show', 'Hi Night King', 'Hi tyrion', 'Hi Josep'] Search text : Hi Jon ES Output : {'Hi Jon Show', 'Hi Josep',.... all other Hi'ss] I want to find how many percentage text matched. from elasticsearch_dsl import Search q = 'Hi Jon' fl = { 'match': { 'name': { 'query': q, "fuzziness":"AUTO", "minimum_should_match":"90%" } } } c = Search() c = c.filter(fl) x = c.execute() -
Unable to Install Pandas on Cents 7 Linux Server
I have a Centos7 linux server, on that i have deployed Django application, now i have to use pandas in the application, but post installing the pandas by using pip3.6 command and i am getting below error, please someone help ImportError at / Unable to import required dependencies: numpy: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: The Python version is: Python3.6 from "/usr/local/bin/python3" The NumPy version is: "1.19.4" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: /var/www/project/venv/lib/python3.6/site-packages/numpy/core/_multiarray_umath.cpython-36m-x86_64-linux-gnu.so: failed to map segment from shared object: Permission denied Request Method: GET Request URL: http://192.168.225.45/ Django Version: 3.1 Exception Type: ImportError Exception Value: Unable to import required dependencies: numpy: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how … -
Django how to GET data from two tables and combine data in GET request in views
These are the django models that I currently have: class Desgn_Mast(models.Model): desgn_mast_id = models.AutoField(primary_key=True) desgn_name_short = models.CharField(max_length=10) class Desgn_Trans(models.Model): desgn_trans_id = models.AutoField(primary_key=True) emp_mast_id = models.ForeignKey("app.Emp_Mast",on_delete=models.CASCADE) desgn_mast = models.ForeignKey("app.Desgn_Mast",on_delete=models.CASCADE) created = models.DateField() class Emp_Mast(models.Model): emp_mast_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) The Desgn_Trans table mantains the history of all the designations an employee has ever had. Now in the view of Emp_Mast, in the GET request I want to also obtain the desgn of the employee The example of the view is: class Desgn_Mast_ListView(APIView): permission_classes = [DjangoCustomModelPermissions] queryset = Task_Mast.objects.none() # TO define a dummy queryset for the purpose of the above permission class def get(self, request, format=None): db_data = Emp_Mast.objects.all() serializer = Emp_Mast_Serializer(db_data, many=True) return Response(serializer.data) I want the following output for the GET request, how to do it? { { emp_mast_id: 1, first_name: "Test", last_name: "User", desgn_mast: 1 (primary key of the respective desgn), }, {...}, {...}, } -
Django Images in row view
I have created a model in Django where I can upload the picture in the admin site and later it will be displayed in the homepage. *.html file <!-- templates/home.html --> <h1>Django Image Uploading</h1> <ul> {% for post in object_list %} <h2>{{ post.title }}</h2> <img src="{{ post.cover.url}}" alt="{{ post.title }}"> {% endfor %} </ul> How can I display all pictures in a row view ? instead of column ? (image-gallery kind of page I wanted to built) Thanks in Advance -
How to change what Django model returns as a value?
I'm trying to get my Product kind as what I declared It's name, instead I get number. Let me be more clear: This below is my Product Kinds; PRODUCT_KINDS = ( ("1","Electronic"), ("2","Furniture"), ("3", "Bedroom"), ("4","Dining") ) And this image below is my django-admin panel which everything seems perfect because I can get every single of my kinds. However, when I try to get this data from api/products url I get this data [ { "image": null, "name": "Headphones", "kind": "1", "price": 250.99, "description": "No description for this item.", "is_featured": true }, { "image": null, "name": "Watch", "kind": "3", "price": 12.5, "description": "No description for this item.", "is_featured": true }, { "image": null, "name": "T-shirt", "kind": "2", "price": 12.99, "description": "No description for this item.", "is_featured": true }, { "image": null, "name": "Ali Ziya ÇEVİK", "kind": "1", "price": 1212.0, "description": "No description for this item.", "is_featured": false } ] as you can see In my django-admin panel I get the name of kind but In the API I get It's index. This below is my serializer: from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): #kind = serializers.CharField(source = 'kind') #print(kind) class Meta: model = Product fields = ['image', … -
Is there a way to solve OS Error in Django Project
I started learning Django recently. I first ran the virtual enviroment, then installed Django and then python manage.py runserverbut im recieving this error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' Traceback (most recent call last): File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\123\Downloads\django-react-boilerplate-master\django-react-boilerplate-master\env\lib\site-packages\django\core\management\base.py", line 371, in execute … -
Trying to do a calculation on django models
i have two integer fields that i want to divide to get the value of 3rd field. @property def Pallets_Count(self): return self.CASES/self.CasesPerPallet but the result in the database always shows null . -
Change value in views before rendering it at html page
I have a listview in my Django's project like: class KaoiroView(ListView): template_name = 'main/show-kaoiro.html' queryset = Kaoiro.objects.all() context_object_name = 'kaoiro' paginate_by = 10 where Kaoiro has one column called checkTime = models.BigIntegerField() in models.py. this checkTime is a unixtime like one big number. I would like to convert this time when user get above page from my views.py, but because I'm using a listview I don't know how to access this data -
TypeError: join() argument must be str or bytes, not 'Request'
Hi I am new to django rest framework can any one help me to download file from server as file path is store in db .How can I get file using api in django rest framework ..please help -
How to continuously keep displaying a timer on django?
I am developing a website using django framework and i am kinda new to it. I want to display an item from the database for a specific time on the webpage. I have a custom filter to implement the timer logic , however I am trying to understand that how can I display the actual timer on the page. Below is the logic for timer :- @register.filter(name="time_left") def time_left(value): t = value - timezone.now() days, seconds = t.days, t.seconds hours = days * 24 + seconds // 3600 minutes = (seconds % 3600) // 60 seconds = seconds % 60 st = str(minutes) + "m " + str(seconds) + "s" return st -
Do some function in repeated interval in django
I am working on django website through which a user can send notifications to registered user on app. Here I have a class Notification in models.py with following fieldfield sender = models.ForeignKey(User, on_delete=models.PROTECT, related_name="notifications_sent") class_group = models.ForeignKey(Classes, on_delete=models.PROTECT, related_name="class_notification") topic = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) seen = models.ManyToManyField(User, related_name="recieved_notif") reciepent = models.ManyToManyField(User, related_name="notif_reciepent") Now until acknowledged by all its reciepent I want to send this notification again to the remaining reciepent. I am using pyfcm for sending notification. How to achieve this task -
django.db.utils.ProgrammingError: relation "client_apps_externalkeys" does not exist
I was trying to save stripe keys to database for convenience of customers to edit it, have created models and saved to db. But when I try to print the keys getting this error. This is the code class ExternalKeys(models.Model): public = models.CharField(max_length=80, blank=True, null=True) secret = models.CharField(max_length=80, blank=True, null=True) webhook_secret = models.CharField(max_length=80, blank=True, null=True) public_key = ExternalKeys.objects.first().public secret_key = ExternalKeys.objects.first().secret webhook_secret_key = ExternalKeys.objects.first().webhook_secret print(public_key) print(secret_key) print(webhook_secret_key) -
user profile with django
what would be the steps to create a user profile other than the administrator user please, I am a newbie. I leave the model class of which I want to be a user profile enter image description here -
django.core.cache.lock doesn't work in a Celery task
I have the following (tasks.py): from celery import shared_task from django.core.cache import cache @shared_task def test(param1: str) -> None: with cache.lock("lock-1"): print("hello") When I do a test.delay(), nothing is printed, which makes me believe that there is something wrong with cache.lock("lock-1"). I'm using Redis as my cache and Celery backend, and this is configured in settings.py. What is wrong here? If django.core.cache cannot be used as a locking mechanism (to ensure that only one test runs at a time, what could be used instead?) Thank you! -
Cracking django/python interviews
I've been working in TCS as an embedded system developer (2.5+ years). For the past 3 months I'm learning django/python. is it going to be hard for me to crack interviews since I'm trying to switch to a completely different domain? What are the concepts in django/python I should be strong in? My current package is 4.2 LPA. But if I'm starting new as a django developer, is it fair to demand 6.5. Or 7 LPA? Does MNCs like wipro or Infosys recruit django developers? If yes, how to apply? (I'm an average coder) Please do respond. Thanks in advance! -
Handling Django Rest Framework 404 page directed to react app's home/index
I have DRF project and the react project is also within the Django project as an application. The name of the react application is frontend. INSTALLED_APPS = [ .... 'frontend' ] The structure of the frontend is as follows, The only code in the project is in views, def index(request): return render(request, "build/index.html") And the URL is, from frontend.views import index urlpatterns += [path("", index, name="index")] Now what I was trying to do is, if the browser's URL response is 404, then instead of showing django's 404 page I would like to go the home/index of the frontend react app. I tried to add handler404 = 'frontend.views.index' in urls.py, but it shows 500 internal error instead of 404 or the index of react app. Any help would be really appreciated. Thanks in Advance. -
Django raw sql statement with params and likes search
I have a problem when performing a raw sql in Django. res = [] start = '2017-12-08T01:56:56.701Z' end = '2020-12-08T01:56:56.701Z' with connection.cursor() as cursor: raw_sql = ''' select case when content like '%products%' then 'Products' else 'Others' end as name, count(id) as times from mytable where somefield LIKE "%somefieldcontent%" and created between '%s' and '%s' ''' cursor.execute(raw_sql, [start, end]) res = cursor.fetchall() It raise this error: unsupported format character ''' (0x27) I tried to perform this sql directly in mysql, it works. But it does not work in the Django environment. I think must be something wrong I do about the string. Basically I want to use params instead concat to build the SQL statement. Any ideas? Thanks! -
Django Filtering Many-to-Many relationship without ManyToManyField "through" relationship
Given these models: class Event(models.Model): name = models.CharField() class Project(models.Model): name = models.CharField() class EventProject(models.Model): event= models.ForeignKey(Event) project= models.ForeignKey(Project) Is there a way to get all the Events for each Project like this: with the property project.events = [<array of Event>]? I found a similar question, however one of the tables has the members = models.ManyToManyField(Person, through='Membership') relationship so it's easier to do. I can't do as in the related question and add a relationship as I'm not allowed to change the model. -
Serializer Including Reverse Relationship
I have been searching for the answer on SO for hours at this point and still haven't found the answer. What I am trying to achieve is this: In my chat function, I would like to show the list of chat channels with the owner, member, and the last message written. So far, I have been able to show the owner and member list. However, the last message does not show whatever I do with the serializer... Below is the models.py for the models in question. models.py class ChatUser(models.Model): id = models.IntegerField(primary_key=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField( auto_now=True) status = models.IntegerField(default=1) is_logged_in = models.BooleanField(default=True) username = models.CharField(max_length=100, default='') password = models.CharField(max_length=255) login_token = models.CharField(max_length=255, blank=True, null=True) session_token = models.CharField(max_length=500, blank=True, null=True) channel = models.ManyToManyField("ChatChannel", related_name="users", null=True, through="ChatChannelMembership" ) class ChatChannel(models.Model): channel_types = ( ('private', '비공개'), ('public', '공개') ) id = models.CharField(primary_key=True, max_length=255) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100, blank=True, null=True) owner = models.ForeignKey(ChatUser, on_delete=models.DO_NOTHING) type = models.CharField(choices=channel_types, max_length=10) is_frozen = models.BooleanField(default=False) member = models.ManyToManyField(ChatUser, related_name="channels", null=True, through="ChatChannelMembership" ) class ChatMessage(models.Model): message_types = ( ("text", "글자"), ("custom", "사용자 임의") ) id = models.AutoField(primary_key=True) talkplus_message_id = models.CharField(max_length=255, blank=True) created_date = models.DateTimeField(auto_now_add=True) channel = models.ForeignKey(ChatChannel, on_delete=models.CASCADE, related_name="messages") sender = … -
Environment Isolation in django-server on user side
I have been working on an Online Competing and Development Environment project on django, and one of the requirements is environment isolation, i.e. the server needs to be unaffected ,even if the user runs some malicious code ,such as equivalent of "rm -rf /" from python. I know the implementation is related to the use of docker, but i am unable to figure out the environment isolation on the user side, after reading several web articles too. Any references or help will be highly appreciated. Thanks for reading -
Reverse Queryset Order in Django for pagination
I have some technique to share with reverse queryset and pagination import your_model from django.core.paginator import Paginator array = your_model.objects.order_by('id').values().reverse() or array = your_model.objects.order_by('create_at').values().reverse() p = Paginator(array, 15) => 15 is number of data in pagination p.num_pages => check number of page p.get_page(page).object_list => get data each page -
Fail to pass dict data to jquery. Error display as: Uncaught SyntaxError: missing ) after argument list)
I have issue on reading data that pass from a Django template in jquery .js file. The data in my Django view: print({0}, {1}\n'.format(init_data[1], type(init_data[1])))) // this will print: 'Counter({'pass': 15, 'fail': 2}), <class 'collections.Counter'> context = {"data":init_data[1].items()} return HttpResponse(template.render(context, request)) In my index.html template I'm able to read the data out as such {% block content %} <h3> {{data}} </h3> // this printed dict_items([('pass', 15), ('fail', 2)]) <div class="tab"> <button class="tablinks" onclick="openResult(event, 'TabForm')" id="defaultOpen">Form</button> <button class="tablinks" onclick="openResult(event, 'TabChart', {{data}}')">Statistic</button> </div> <div id="TabChart" class="tabcontent"> {% include 'result/tab_statistic.html' %} </div> {% endblock %} In result/tab_statistic.html, I want to use the 'data' as dynamic data for a chart in jquery, but the 'data' seem not readable in jquery script as I get bug complaining: (index):18 Uncaught SyntaxError: missing ) after argument list Here is my simple jquery script just to show the data is not readable when called from function openResult() above function openSummary(evt, tabName, a ) { if (typeof(a)==="undefined") a = "None"; console.log('CHECK a=' + a); return It seems to be it don't allow 'data' to be passed directly as the way I do because if I replaced the {{data}} with any argument 'abc' , it just working. Pls gives me … -
Python - Access a model, with a name that is dependant on a variable value
I'm trying to access a model, with a name that is dependant on a variable value. If have a series of models based on a country identifier. e.g. Student_??? where ??? is the country identifier. If I want to print out details of each student for each country, is there a way of looping through the code to access each model dynamically. I could perform the task through an if statement, but that would require hardcoding each country code into the program, which I want to avoid. As an example. My views.py looks like: mystudentcountry = {'AU', 'US', 'UK', 'EU'} for country in mystudentcountry: mystudent = Student_AU.objects.all() for student in mystudent: print(f'{student.name} is {student.age} years old and studies in {country}') On the third line of code "mystudent = Student_AU.objects.all()" is it possible to replace the "AU" with each country as identified in the loop. Thank You for your support.