Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery - No result backend is configured
Im currently unable to make celery using redis as a results backend as i want some of my tasks wait to finish before accepting the next one. The Problem now seems that celery does not recognize the results backend for some reason. celery.py import... os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'App.settings') app = Celery(str(settings.SITE_NAME), broker=str("redis://") + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT')) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": [ str("redis://") + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT') + str("/") + env.str('REDIS_CACHE_DB') ], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "SOCKET_CONNECT_TIMEOUT": 30, # in seconds "SOCKET_TIMEOUT": 30, # in seconds "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", "CONNECTION_POOL_KWARGS": {"max_connections": env.int('REDIS_MAX_CONN'), "retry_on_timeout": True} } } } # Celery Settings: BROKER_URL = str("redis://") + env.str('REDIS_HOST') + str(":") + env.str('REDIS_PORT') CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'default' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'GMT' CELERYD_TASK_SOFT_TIME_LIMIT = 300 with this settings in place I get the following error: No result backend is … -
Implementing Vue RESTful API calls in Django within Django Templates with Session Authentication
I have a Django project that requires page refreshes any time I want to update the content. Currently it uses the built in Django Class Based Views, which in turn use Templates. I want to start implementing some javascript calls to refresh tables/forms/modal windows with new data, mostly in response to button clicks. I'm trying to use Vue to accomplish this, and I have created a Django REST Framework backend to facilitate this. I got a simple 'Hello world' vue class working where the data is hard coded into the data field of the Vue class. I can't seem to make the jump to getting data from the API though. I am getting an Unauthorized response. I have unit tests where I call the API from the DRF APITestCase using the self.client.get('api/path') and they work as expected (unauthorized when there is no authenticated user attached to request, authorized when there is). I have debugged into the DRF Permission class to see why the request is being refused and it is because there is no authenticated User attached to the request. I have added SessionAuthentication to the DEFAULT_AUTHENTICATION_CLASSES in settings. My question is, how do I add an authenticated user to … -
Route to different databases depending on the group of users in Django Rest Framework
I have a project with Django rest framework as backend and Vue as frontend and everything works well. Now, I have to extend my project. I want to bring the same product, but to a new group of users, who will have 0 interaction with the first group of users. No data will be shared among the two groups of users. Like if I created a copy of my backend with a new database and directed the new group of users to this new backend. So, I am looking for a solution not to have to build another backend for each new independent group of users (which is obviously less than ideal). I could create permissions where users could only access data about their own group and change every querysets. But I think it is not optimal to keep everyone on the same table as the number of groups of users will grow. I guess the ideal would be to have 1 database per group of users, 1 backend in total, and to route users to their own group specified by the api call they make with a /groupID/rest-of-endpoint Is that possible in Django ? Do you see any solution … -
Facing a probelm to find source code of generic views
I am searching source code of generic views - listView - UpdateView - TemplateView - DeleteView but i am not able to find in documentation. Kindly someone share the link where i can see the source code of these views. Thank you! -
How to render aut generated listed to django template
maybe my question is silly but this is giving me a headache. let's say that: list_1 =[1,2,3,4,...] new_dic ={} for i in list_1: new_dic[i] = [] How to render new_list[1] , new_list[2] .... automatically on Django? -
duplicated lines are fetched by filter
I have a little bit complex combination of | & filter like this. objs = objs.annotate(num_line=Count("lns")).filter(Q(lns__id__in=lnIds) | (Q(sts__id__in=oIds) & (Q(lns__id__in=lnIds) | Q(num_ln__lte=0)))) It looks like work, but results are sometimes deplicated (has same id). id 1 2 3 3 4 5 I thought filter is assured to return unique id though ,am I wrong?? Or is it possible to omit duplicated rows?? class Obj(models.Model): created_at = models.DateTimeField(null=True) lns = models.ManyToManyField(Ln) sts = models.ManyToManyField(St) is = models.ManyToManyField(Is) pub_date = models.DateTimeField('date published') -
django serialize json in geojson
i have a model like: latitudine = models.FloatField(max_length=50,default=None) longitudine = models.FloatField(max_length=50,default=None) and I need to serialize it and send it in geojson format I'm using usual django json serializer in view: def meterpoints(request): points = serialize('json', Contatore.objects.all(),fields='latitudine, longitudine') return HttpResponse(points, content_type='json') what I receive is: { "model": "conlet.contatore", "pk": "1012-081-7217", "fields": { "latitudine": "45.0717383", "longitudine": "7.6810848" } } so, is there any way to serialize my model in geojson creating a pointfiled from my lat long model, so leaflet can understand it? -
How to connect websocket after set up with NGINX and Supervisor?
I created a Django Channel beside my wsgi application. Everything works fine if I run: daphne -b 0.0.0.0 -p 8001 myapp.asgi:application I can connect to the websocekt but after I created supervisor with nginx I can not connect and I don't see any useful log that could solve the problem. When I check the supervisor status it has no error: asgi:asgi0 RUNNING pid 23981, uptime 0:10:22 asgi:asgi1 RUNNING pid 23980, uptime 0:10:22 asgi:asgi2 RUNNING pid 23983, uptime 0:10:22 asgi:asgi3 RUNNING pid 23982, uptime 0:10:22 The socket was originally localhost:8001 and I also allowed UFW to use that port but it didn't work so I changed to my server IP. Supervisor [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://139.162.172.87:8001 # Directory where your site's project files are located directory=/home/markkiraly/crumb_backend # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/home/markkiraly/crumb_backend/venv/bin/daphne --fd 0 --access-log - --proxy-headers crumb_backend.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=4 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose … -
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