Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the code of adding two number in jinja template in Django?
I don't know it. Please answer it. Blockquote -
Django await on a function with @database_sync_to_async decorator for fetching multiple object throws error
I am integrating django channels for async capabilites. I am trying to fetch multiple objects of a user model using await on the function. consumers.py class TeamConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type":"websocket.accept" }) async def websocket_receive(self, event): o_user = await self.users() print(o_user) @database_sync_to_async def users(self): return UserModel.objects.all() Trying to fetch users from the above code causes the error "You cannot call this from an async context - use a thread or sync_to_async." However if i fetch a single object using "UserModel.objects.all().first()", everything works fine. -
How to create unique link that will work with function
I have project with rooms, where one user can create rooms and others can join, but i want to create private rooms which you can join only by unique link that will receive and send you a creator of this room.How i can implement that? -
Django ImageField object not updating with input field
I tried updating a user's profile picture using a function view (ajax) but I keep getting the error below: raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'emp_photo' The same technique I am using is being used on CharField and TextField without issues. Please see below for my codes. views.py @login_required(login_url='/login/') @user_passes_test(user_type_combo) def change_employee_photo(request, pk): data = dict() profile = get_object_or_404(Profile, pk=pk) if request.method == 'POST': form = EmployeePhotoForm(request.POST or None, request.FILES or None, instance=profile) if form.is_valid(): newPic = profile(emp_photo=request.FILES['emp_photo']) newPic.save() data['is_valid'] = True else: form = EmployeePhotoForm(instance=profile) data['form_is_valid'] = False context = { 'form': form, } data['html_form'] = render_to_string('employees/partial_employee_photo.html', context, request=request ) return JsonResponse(data) forms.py class EmployeePhotoForm(forms.ModelForm): class Meta: model = Profile fields = ['emp_photo',] {% load crispy_forms_tags %} <form action="{% url 'change_employee_photo' form.instance.pk %}" class="js-change-employee-photo-form" enctype="multipart/form-data" id="ProfileUpdateForm" method="post" runat="server"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Change Employee Photo</h5> <button aria-label="Close" class="close" data-dismiss="modal" type="button"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-group col"> <div id="emp_photo_holder"> <img alt="{{profile.first_name}}_{{profile.last_name}}" height="200px" id="emp_img" src="/media/default.jpg/" width="200px"/> <input id="emp_photo" name="emp_photo" type="file" value="{{profile.emp_photo}}"/> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#emp_img').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#emp_photo").change(function() { readURL(this); }); </script> </div> <div class="modal-footer"> <button class="btn … -
Django: jquery ajax file uploading doesn't work
Hi, in my code i want upload a file when it is selected on Input File.I am not able to get my file in my django view, and my request.POST and request.FILES are emptyso i think the problem is on the jquery code. This input file has "file_windows" id. Form has "form_upload" id. here is my jquery code: $("#file_windows").change(function(){ var myform = document.getElementById("form_upload"); var fd = new FormData(); var file = document.getElementById('file_windows').files[0]; fd.append('file_win', "file"); token_value=$("input[name=csrfmiddlewaretoken]").val(); $.ajaxSetup ({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", token_value); } }); $.ajax ({ url:"./ajax", method: 'POST', type:"POST", cache: false, enctype: 'multipart/form-data', processData: false, contentType: false, cache: false, data: { "file_win":fd }, success: function(result) { alert(result); } }); }); this is my Django view function: def ajax_file_request(request): if request.is_ajax(): #response=request.FILES["file_win"] multivaluedictkeyerror print(request.FILES) print(request.POST) return HttpResponse("ajax request") else: respose = "Not Ajax" return HttpResponse(respose) obviously in my jquery access function my alert is"ajax request" https://i.stack.imgur.com/E67xZ.png How can i solve this problem? -
Make celery wait for task to finish
I want celery to wait for a specific task to finish, therefor I installed the celery-results-backend beside celery itself. But I don't understand how I have to write my task call in order to wait as I currently get the following error: example_task() missing 1 required positional argument: 'user_pk' views.py def example(request): user = request.user if request.method == 'GET': result = example_taks.apply_async(user_pk=user.pk) result_output = result.wait(timeout=None, interval=0.5) return redirect('something') else: args = {'user': user} return redirect(reverse('something'), args) at my tasks.py: def example_task(user_pk): user = User.objects.get(pk=user_pk) try: ... previously I called the talks like that: def example(request): user = request.user if request.method == 'GET': example_task.delay(request.user.pk) ... This was working fine but did not wait for task to finish. If i Just do: result = allocate_new_bch_address.apply_async(request.user.pk) I also get a error: example_task() argument after * must be an iterable, not UUID thanksful for any advice here. -
'ManyToManyDescriptor' object has no attribute 'all'
I have a django model that looks like this: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE) title = models.CharField(max_length=120) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name='post_likes') With this toggle, a user can like a post. class PostLikeApiToggle(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, slug=None, format=None): obj = get_object_or_404(Post, slug=slug) like_count = 0 user = self.request.user liked = False if user in obj.likes.all(): liked = False like_count = 0 obj.likes.remove(user) else: liked = True like_count = like_count + 1 obj.likes.add(user) messages.add_message(self.request, messages.INFO, 'You liked the post!') data = { "liked":liked, "like_count":like_count } return Response(data) This is the view I am working on: @login_required def m_userprofieview(request): own_posts = Post.objects.filter(user=request.user) allposts = Post.objects.all() if request.user in allposts.likes.all(): liked_posts = liked_posts else: liked_posts = None if request.method == 'POST': u_form = UserUpdateForm(request.POST,instance=request.user) i_form = ProfilePictureUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid(): u_form.save() messages.success(request,'Your information has been updated !') return redirect('/') if i_form.is_valid(): i_form.save() messages.success(request,'Your information has been updated !') return redirect('/') else: u_form = UserUpdateForm(instance=request.user) i_form = ProfilePictureUpdateForm(instance=request.user.profile) context = { 'u_form':u_form, 'i_form':i_form, 'own_posts_list':own_posts, 'liked_posts_list':liked_posts } return render(request,'m_userprofile.html',context) I want that every user has a userprofile with a list of posts he liked. This is what I tried: if request.user in Post.likes.all(): liked_posts = liked_posts else: liked_posts = … -
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused django to heroku
I'm using django with mongodb atlas and trying to deploy using heroku. Somehow I keep facing pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused this error. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'name', 'HOST': 'mongodb+srv://user:pass@cluster0-xb9zh.mongodb.net/test?retryWrites=true&w=majority', 'USER': 'user', 'PASSWORD': 'pass', } } For django setting.py I simply changed it from sqlite to mongodb. It works perfectly in my local. There is one change I am suspicious is I had to change a mongo_client.py file from localhost to the connection string in order to make my mongodb connect to atlas instead of my local database. Not sure if that has anything to do with this. class MongoClient(common.BaseObject): """ A client-side representation of a MongoDB cluster. Instances can represent either a standalone MongoDB server, a replica set, or a sharded cluster. Instances of this class are responsible for maintaining up-to-date state of the cluster, and possibly cache resources related to this, including background threads for monitoring, and connection pools. """ HOST = "mongodb+srv://user:pass@cluster0-xb9zh.mongodb.net/test?retryWrites=true&w=majority" PORT = 27017 # Define order to retrieve options from ClientOptions for __repr__. -
Nested Category In django
how do I use nested categories in django as Im nwe to django and doing this and find some solutions but didnt work anything class MainCategory(models.Model): name = models.CharField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class SubCategory(models.Model): perentcategory = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Items(models.Model): # maincategory = models.ForeignKey(MainCategory, on_delete=models.CASCADE) category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='SubCategory') name = models.CharField(max_length=255) Please share your thoughts -
ListField In Django - Python
I want to store multiple CharField values in a list of a model. Is there any way to do it? I was expecting something like class Author(models.Model): name = models.CharField(max_length=255) birth = models.CharField(max_length=255) image = models.CharField(max_length=2083) cover_image = models.CharField(max_length=2083) quote = models.CharField(max_length=2083) bio = models.CharField(max_length=2083) books = models.ListField( book_name = CharField(max_length=255) ) Apparently Django does not provide anything similiar. -
How to make skinny views?
I have dashboard.py view, which helds 5 validation form code blocks around 25 lines of code each , and 3 different dynamic paths. How can I make this slimmer ? Is there a way to make the form validation blocks somewhere else in the project ? Is there a way to put each dynamic request in a different view file ? -
Is there a way to fix this?
I'm trying a develop a website for an online store where users can add products to their carts. When a user add the product or removes it, I don't know why(I'm a beginner in Django) the total price is not correct. Please can anyone help me? My views.py: from django.shortcuts import render, redirect, HttpResponseRedirect, Http404 from products.models import Product from .models import Cart from django.contrib import messages from django.urls import reverse from django.utils.safestring import mark_safe def cart(request): cart = Cart.objects.all()[0] context = {"cart":cart} template = 'shopping_cart/cart.html' return render(request, template, context) def add_to_cart(request, slug): cart = Cart.objects.all()[0] try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: raise Http404 except: pass if not product in cart.products.all(): cart.products.add(product) messages.success(request, mark_safe("Product added to cart. Go to <a href='cart/'>cart</a>")) return redirect('myshop-home') else: cart.products.remove(product) messages.success(request, mark_safe("Product removed from cart")) new_total = 0.00 for item in cart.products.all(): new_total += float(item.price) cart.total = new_total cart.save() return HttpResponseRedirect(reverse('cart')) My models.py: from django.db import models from products.models import Product class Cart(models.Model): products = models.ManyToManyField(Product, null=True, blank=True) total = models.DecimalField(max_digits=100, decimal_places=2, default = 0.00) def __unicode__(self): return "Cart" -
Postres DB idle connections not gracefully closed for django application
I've SaaS Django application running with AWS RDS postgres instance. When the traffic increases there are lot of idle connections in my Postgres DB. At that point my application gets slow reponse, and when i clear the idle connections manully the site gets back to normal. But this situation is getting worse as the traffic increases regularly. I tried setting up timeouts in the db settings but my application has some background process running, these process are getting affected some times. When i checked online for a solution, most of them suggested using Pgbouncer and to setup connection pooling to handle this issue. Is this best option to handle the issue, how efficient is Pgbouncer for achieving connection pooling for a SaaS Django application with Postgres DB? or is there any better solutuion to avoid idle connections in postgres DB? -
Multhreading with updates to MySQL
I need to evaluate around 80k rows of data every day at 11am, and I hope to accomplish it within a few minutes. I used multithreading that uses select_for_update() of Django that gets one row at a time, updates it, and then gets a new row. The problem is, there is an issue where the counter increases too fast having the assumption that there are times where the row gets evaluated twice. Here is my current code block: while True: with transaction.atomic(): user_history = UserHistory.objects.select_for_update().filter(is_finished=False).first() if user_history: user = UserProfile.objects.filter(id=user_history.user_profile_id).first() ... doSomething() # output of rewarded_value user.coins += float(user.coins) + rewarded_value # the value increases too high here user.save() user_history.save() else break Is there a better way of accomplishing this? The framework I'm using is Django, and I have a cron job running from the library django-cron. -
Select option question didn't be saved in sqlite3
I don't want to use form because there are special codes. So I use request.POST. I have a problem. I want to use select option to make 'question' field. But 'question' didn't save in sqlite3. When I print 'user.question', it's maybe saved safely. But when I enter Django admin page, it doesn't be saved. So how can I solve this problem? view.py @csrf_exempt def signup(request): if request.method == "POST": question = request.POST.get('question', '') answer = request.POST.get('answer', '') user = User.objects.create_user(question = question, answer=answer) return render(request, 'home.html') else: return render(request, 'signup.html') signup.html <div class="sign-page"> <div class="form"> <form class="sign-form" method="post" action="{% url 'website:signup' %}"> <select name="question"> <option value="" selected="selected">비밀번호 확인 질문을 선택해주세요</option> <option value="ONE">기억에 남는 추억의 장소는?</option> <option value="TWO">자신의 인생 좌우명은?</option> <option value="THREE">자신의 보물 제1호는?</option> <option value="FOUR">가장 기억에 남는 선생님 성함은?</option> <option value="FIVE">추억하고 싶은 날짜가 있다면?</option> <option value="SIX">유년시절 가장 생각나는 친구 이름은?</option> <option value="SEVEN">인상 깊게 읽은 책 이름은?</option> <option value="EIGHT">읽은 책 중에서 좋아하는 구절이 있다면?</option> <option value="NINE">자신이 두번째로 존경하는 인물은?</option> <option value="TEN">초등학교 때 기억에 남는 짝궁 이름은?</option> <option value="ELEVEN">다시 태어나면 되고 싶은 것은?</option> <option value="TWELEVE">내가 좋아하는 캐릭터는?</option> <option value="THIRTEEN">자신의 반려동물의 이름은?</option> </select> <input type="text" name="answer" placeholder="답변을 입력해주세요"> <div class="button"> <input type="submit" id="complete" value="complete"> <input type="button" id="cancel" value="cancel"> </div> </form> </div> </div> models.py … -
'type' object is not iterable - Django
I know this question has been asked many times before, but non of the other answers fixed my issue. I get this error as soon as I use the 'type'.objects.get(id=1), but using the filter() method the app runs with no errors, I guess this is related to the get() method returns a single record whereas the filter() returns a query set. I don't want a set, I just want to display a single record, I think that the Django rest framework UI iterates over the response, how to change the UI ? I found that I can override some sections of it here but I don't know what to override, also I prefer getting just a plan old JSON response rather than a fancy UI, how to do that ? -
NoReverseMatch error after saving form in Django
I am getting NoReverse at / def createOrder(request, pk): Here is my code: https://github.com/alauddinmondal/crm1/blob/master/accounts/views.py after saving the form and redirecting to homepage -
Random function in twig template show **Could not parse the remainder: '()' from 'random()**
I am developing a site in django web framework. I am aiming to use random function provided by twig in my template. But, I it shows an error showing Could not parse the remainder: '()' from 'random()'. My code:- <a href="javascript:void(0);" data-id="justrandom-{{ random() }} actualid-{{ comment.id }}"> I don't know what I did wrong. Obvioulsy, if I don't use random(), template is working fine. Do I have to import something to use random function in template? Here, is the twig documentation where they used random function. Twig -
Access variables without re-loading them between management commands in Django
We are building an AI enabled web application that uses huge memory models that ideally should be loaded only once in memory as global variables. These variables are to be used by different management commands which run as individual processes and make use of the Django framework. And of course, the runserver command too accesses these global variables. These models are loaded inside a single module commons but since we are spawning different processes, let us assume two for now - runserver and process_tasks, these models are essentially loaded twice in memory via the commons module. Is there a way to load these models centrally and share the variables between independently spawned processes. I'm aware of the multiprocessing module in python and the Manager API, but can't figure out a way for incorporating it with the current scenario. Is there a way to run a standalone python process that holds these variables and be able to access them from multiple other processes? -
Serialize multiple objects without ModelViewSet
I have models and serializer and views with rest framework However I want to make view not by viewsets.ModelViewSet by my original one get_by but in ModelViewSet serializer could be set easily serializer_class = MyTextSerializer serializer.py class MyTextSerializer(serializers.ModelSerializer): my_status = serializers.SerializerMethodField() class Meta: model = MyText fields = ('id','text','created_at','pub_date') def get_my_status(self,obj): res = ["mystatus"] return res normal ModelViewSet view but I don't want to use this now. class MyTextViewSet(viewsets.ModelViewSet): queryset = MyText.objects.all().order_by('created_at') serializer_class = MyTextSerializer ## serializer works here. pagination_class = StandardResultsSetPagination in views.py I wanto use this. @api_view(['POST', 'GET']) def get_by(request): ts = MyTexts.objects.all().order_by('id')[0:10] serializer = MyTextSerializer(ts[0]) ## it works, but I want to serialize multiple items `ts` return Response(serializer.data) However I have no idea how to pass the multiple queryset to Serializer as ModelViewSet dose. Does anyone help?? -
Django is not setting REMOTE_USER
I am trying to get the information about the user who is accessing the website for user authentication and for some other purpose also. After looking at official documentation of Django I got this article but still when I am trying to access request.META["REMOTE_USER"] I am getting the error because no key exists. After some tweaks when I tried again I was getting the username of my PC even if I tried to access my website from another PC on from the same network. I am using Django's lightweight server for testing, hosted on my PC and trying and access the website from another PC on the same network. Please help and try to resolve this issue. -
Periodic database backup in kubernetes?
How to setup periodic database backup in kubernetes? I have deployed a postgres database as StatefulSet in kubernetes and mounted a PersistantVolume to store data. Now to get periodic backup for the mounted volume, I found three options, Setup a CronJob in kubernetes and execute pg_dump and upload to the storage location. I have already using celery in my project. So now add a new task to backup postgres data and upload to the storage location. VolumeSnapshots. This looks more kubernetes way. But I couldn't find a way to automate this periodically. Which is the recommended way to take periodic volume backup in kubernetes? -
Within Django - in the HTML Files the {% 'commands %} arent working
im trying to follow a Python Course to build a Dashboard in Django - currently im have no more ideas left, why i cant use the {& load/include ..%} commands within my HTML files? Any ideas? Am I missing some packages or something else? Please be gentle im a newjoiner. I also added two pictrues of the problem. enter image description here Second one: enter image description here -
Error in virtual Environment while running Django Project
When I tried running my Django project in a virtual environment, it gave the following error after running python3 manage.py runserver. OS: Elementary OS Python: 3.6.9 Django: 3x Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/contrib/admin/checks.py", line 76, in check_dependencies for engine in engines.all(): File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/utils.py", line 90, in <listcomp> return [self[alias] for alias in self] File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/utils.py", line 81, in __getitem__ engine = engine_cls(params) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 27, in __init__ self.engine = Engine(self.dirs, self.app_dirs, **options) TypeError: __init__() got an unexpected keyword argument 'context_videoplaybackprocessors' As seen from above this has nothing to do with the files from my … -
ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
I was trying to run-server and I got this error. I was building an app for inventory management this is the screenshot of error python version 3.8.1 django version 3.0.4