Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CK Editor works locally but not on server
good work I have a django application running on aws ubuntu 18.04 LTS x64 architecture. The ck editor that works when I enter the local admin panel. Doesn't work on server (text box comes instead of ck editor). How can I solve this problem? -
How to minimise the django search query?
I am planning to implement a live autosearch complete function in django ! But, am belive that am over doing it, so need a suggestion: Basically this search bar is located in a page, where all at first all the available data's are displayed as a list ! And then when user types something i filter it out using jquery autocomplete. In the above, am making two queries one to get all data and another one on each user types As this takes two query, i belive its inefficient Here is my search function def search_query(request): if 'term' in request.GET: qs = University.objects.filter(name__icontains=request.GET.get('term')) names = list() for data in qs: names.append(data.name) return JsonResponse(names, safe=False) And the above is been called each time the user types in the search bar and this is my jquery autocomplete code: <script> $( function() { $( "#tags" ).autocomplete({ source: "{% url 'students:search-query' %}" // this hits the above def }); } ); </script> Apart from this, am also making this to show full list as initial data, def index(request): univesity = University.objects.filter(published=True) context = {'univesity': univesity} return render(request, 'students/search/index.html', context) is this right way or is there any effcient way ? Can both the queries … -
Django - What happens when a csrf_token is NOT re-submitted to the server?
Hello, Everybody. I was wondering about... What happens when a csrf_token is submitted by the server-side application to the browser in an HTML form, and that form was not submitted with the post by the browser? Because I was thinking... Django makes the csrf_token and relates it to the user or to the session, I am not sure, to check it when it comes back. And then I think it deletes it, right? So what if it wasn't back? Will it stay there waiting until the session ends or what? For Example, I want to make a form for Comments under the details of the object. But it is not a must to comment. You can comment if you need, and you can do not so. So I put a form like this under those details : <div class="container"> <!-- Here is the object data --> </div> <div class="container comments"> <ul> <li> <form action="{% url 'ads:newcomment' %}" method="POST"> {% csrf_token %} <input id="comment_txt" name="comment" type="text" value="Type a comment..." class="comment_txt"/> </form> </li> {% for comment in comments %} <li class="comment">{{comment}}</li> {% endfor %} </ul> </div> -
AttributeError: '_Environ' object has no attribute 'env'
I am trying to host a website in Gcloud.. i did changes in settings.py file i have environ code i created .env file also env = environ.env(DEBUG=(bool, False)) env_file = os.path.join(BASE_DIR, ".env") After adding this showing this error env = environ.env(DEBUG=(bool, False)) AttributeError: '_Environ' object has no attribute 'env' -
Django Json Response formatting in templates
is it somehow possible to keep the JSON response as it is as well as indent it as a proper format? I want to render the list_text in my list.html template, but the json response comes up different everytime. Is it possible to keep it fixed and properly indented? obj = { list_text[0], list_text[1], list_text[2], list_text[3], list_text[4], list_text[5], list_text[6], list_text[7], } return render(request, 'card/list.html', {'form':form, 'list_text': obj}) I found a similar JSON article here: Link But it is for JSON Serialization or something like that I am looking to pass it on to the templates. -
Does anyone can explain how is the flask_jwt_extended access_token works?
Does anyone can explain working of access_token, refresh_token and csrf_token in flask_restful. If you have any project repo using explicit refreshing with refresh tokens method, please help me. -
Django Logout clears session
I'm using Session object to store anonymous users data. I'm adding session_id to my DB through model. It's not clear, why all data connected with session is deleted when i logout from admin panel? So my records to DB just erase after logout from admin panel. What to do, anybody can help? class SomeOne(models.Model): added = models.DateTimeField(auto_now_add=True) client_session = models.ForeignKey(Session, on_delete=models.CASCADE) SESSION_COOKIE_AGE is big, so it not expires. -
Best approach to send an image over a GET API using Rest Framework in Django to an Android Application
I have deployed an application based on django framework. This application is completely a rest framework based project which deals with GET and POST APIs. The requirement is to have a GET API which is requested from an android application and I need to return few images from the Django application. Questions : What is the best approach to send multiple images (list of images) from django rest framework to android application. How do we return list of images in response from djnago in correspondence to the GET request being triggered. -
Does django-celery-beat deal with multiple instances of django processes created by web-servers
I have a fairly complex periodic-tasks that needs to be offloaded from django context. django-celery-beat looks promising. While I was going through celery-beat docs, I found this: You have to ensure only a single scheduler is running for a schedule at a time, otherwise you’d end up with duplicate tasks. Using a centralized approach means the schedule doesn’t have to be synchronized, and the service can operate without using locks. A typical production deployment will spawn a pool of worker-processes each running a django instance. Will that result in creation of multiple scheduler processes as well? Do I need to have some synchronisation logic? Thanks for your time! -
How to add text into a image using Django
How to add text into a image using Django? I do have it in excel data . In excel there are Column (order id , order name , etc. ) and I do have a Image Template ..these data should render into the (.CDR) file image.. -
App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
I have seen many answers that say we must add procfile and requirements.txt and manage.py in same directory, I have all these files including .git in same folder (directory) here is my procfile and requirements.txt, you can see my file structure as well on left procfile requirements.txt snap 1 requirements.txt snap 2 my branch is main so I am using git push heroku main: git status showing branch but still I receive this error enter image description here -
Iterating the values in a list of dictionary
Hi I have a queryset like (order_list.values('user_id'))and its result is <QuerySet [{'user_id': 2}, {'user_id': 2}, {'user_id': 4}]>. How can I get only the values from this. I'm expecting to iterate like 2 , 2 , 4. -
Getting Django - MySQLdb._exceptions.OperationalError: (1025, 'Error on rename of )
I am trying to connect my Django project to mariaDB but I am getting error MySQLdb._exceptions.OperationalError: (1025, 'Error on rename of \'./mydb/auth_permission\' to \'./mydb/#sql-backup-13c39-4a\' (errno: 168 "Unknown (generic) error from engine")') I tried removing the foreign keys and dropping the table but it still does not work. Tried this solution as well https://confluence.atlassian.com/confkb/mysql-error-1025-thrown-when-attempting-to-change-table-collation-and-character-set-785332187.html but had no effect at all. -
Hijack for profile model
I need to add hijack feature to my profile model I got this for now @admin.register(Profile) class ProfileAdmin(MPTTModelAdmin, HijackUserAdminMixin): change_list_template = 'admin/profile/profiles/change_list.html' admin.autodiscover() def get_hijack(self, obj): if obj.user: return f'<a class="button" href="/hijack/{obj.id}">{obj.email}</a>' get_hijack.allow_tags = True but when I try to follow the link, it gives me 404. I also overrided change_list template from admin, what else should I do? -
How do I upload files to the server using the drf-chunked-upload library?
I have tried many ways to upload a file to the server, but I always get the response {"detail": "No chunk file was submitted"}. How to use this library correctly? One of my attempts: import requests url = 'http://127.0.0.1:8000/chunked_upload/' in_file = open("testfile.txt", "rb") data = in_file.read() response = requests.put( url, headers={ "Content-Range": f"bytes {0}-{9}/{10}" }, data={"filename": "testfile"}, files={'file': data}, ) -
Testing in Django with authentication
I'm trying to test a couple of endpoints that require a user to be authorised in Django: def test_one(self) -> None: client = Client() user = client.post('/create', { 'username': 'bob.smith', 'email': 'bob@gmail.com', 'password': 'password', }) token = client.post('/gettoken', { 'identity': 'bob.smith', 'password': 'password', }) x = token.json() resp = client.get('/changepassword', headers={"Authorization": f"Bearer {x['access']}"}) self.assertEqual(resp.status_code, 200) However, it keeps returning a 403: {"detail":"Authentication credentials were not provided."} The content of x is: {'refresh': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYzMTI0MTIwNSwianRpIjoiNDdjNzM5NThkNmYyNGJiMzkxMzRlM2Y2NThhZWI1MjEiLCJ1c2VyX2lkIjoxLCJuYW1lIjoiYm9iYnkuc21pdGgiLCJlbWFpbCI6ImJvYkBzZWNkaW0uY29tIiwiZ3VpZCI6NjA2NzU1ODI4NX0.lqdU5EfSA3DRbfxqum6XyvBc28t-vam8GVDq4W-NOsz7j9VTcg-i9AYQO0V-PLF7Lo89i6Pq50u0tZop7X5PMUryc3sCWPPnEsPyTm7Fi_cVV054E8chd-BP9fzykwW7ef7ufLTjzzPJfQdniq48jlRmce8Yjv_SspwoAhU2uYO54jtn2NNMRk80NckKyzxy9TwU9tItlPMCtoeK1SCucVsv-PfTJscxEXcaC347AZ0Dytqm2DVyDzQbt8RE9MKOXbHkhijeaftNBuiOMqJXE7NWQQ37iyF8bF2iPsc0M-T7ECFwsfFgPK_TD93ETCl9k_o6_6yxOHvx83dk6vGyzONJgl0MJ_W_y_B1UibQttBMoDfMwCxkM7akQ1OhL3ccb7GW-nGgqlOVREfxxW5xCN6h7O9cPMVk74jQ4xv2N6SlkEWIqb5UhQ4ZIJvFVrw-BOHLY_AqvnMadD9gYn7MaDPGXlpCX2EqOvOmKinASuSTJ94kXZ9pwMzuo_b-j5DnQWKgShZydpMZTt77TZ8_MZUtBBf7W-E_z71auQrgopgq82hHEpDfq3FoY4NXUq1IOEaJxJVpFcboXKep4WXQmRliRyqfIbwEAg7DOOiQ6cKrvbScPUKCpfYfzrt2f9fQbgtwwZYxHgW3-sLRP8r10UQzMaa8yR8ot-oQIq4xy5U', 'access': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjMxMTU2NjA1LCJqdGkiOiJkZDliMWI3Yjc0N2E0YjcxYjJhZjg3ZGM0ZjUzODdmZiIsInVzZXJfaWQiOjEsIm5hbWUiOiJib2JieS5zbWl0aCIsImVtYWlsIjoiYm9iQHNlY2RpbS5jb20iLCJndWlkIjo2MDY3NTU4Mjg1fQ.dnlYgqfTvrQPBmAsZgJ5N39dtMANbBYE0kW3ZPCkAX8KWEsQrJwPQRbMYW_AetjowEkiSaWEQs8T4Hs553guW8lpdzg4_SiKjIXXodJJkfGNq9rDC9bpmLSJigVvpCM-AkgXsNUbZKrzP97fk5CZrVvyGszNlT1Oe66OSQrNQuaIqXSQ20XjuwzpSfEB3qJeC45LMgvHRBbEG0V2jOD5ReBxGJGoOPXVYS7vwfy7dLCq2iT-Kkpny4fALKjfM4bpux6UG5kJWrCLp2ybtCLTgJ9y4pvAhzEzmb1IeqtRV-gHQtaqTbMQl5cIhHdvmtMbBSQrzdG3yYqObKoyMW4oQLu8txKE4huptaInJcnXo4j2PFMPD-x3TtJOqOPYbfgb9Vu1-FCT0um5ZPnr9jv6j0ll92CuuHa7rBRatmzvLIJblpJ-ta6IkIZC6XkeEg3Sfg-dbnpSYaJ5fNxQm7r35oGj2j7r8fnvxlnYGPhmXJEdyas798Z001_TXrnHKsv2a1zNNJHQuK8sTmgAC4R1Fs0JQF4yBmIJ4TverKdiGOUHqYAYoEjNX69hdXeu_4AsAdUiRRzSYNbmuZFTEd-iREz0VgMs7QBIecVBzz33kFfgdYTy64qq9NDz3HIkzPbvw4xdGEFp8UTJlCfCFfdkzAT8pb_czC4xufdm9bSvK5E'} Any ideas why it's saying that authentication details were not provided? -
How do I render human-readable value in HTML of a choice list?
Using the following model to select a day of the week: class Schedule(models.Model): DAYS_OF_WEEK = [ (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday') ] day_of_week = models.IntegerField(choices=DAYS_OF_WEEK, default=0) Rendering the models in HTML via {{ schedule.day_of_week }} renders the integer value of 0-6 rather than the human-readable "Monday-Sunday" values. When I view the model in the admin panel, I see the human readable values. How do I render the human readable values in HTML? -
Add days to a given date in Django
I'd like to add 14 days to return date but I get the error below. return_date = models.DateField(issue_date + datetime.timedelta(days=14)) TypeError: unsupported operand type(s) for +: 'DateField' and 'datetime.timedelta' Here is my model class Issue(SafeDeleteModel): _safedelete_policy = SOFT_DELETE borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) return_date = models.DateField(issue_date + datetime.timedelta(days=14)) issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE) How would I get it to work?? -
django signal post_save not created return two times
when i try to update the post in signal this error happens from django.db.models.signals import post_save @receiver(post_save, sender=Post) def post_save_receiver(sender, instance, created, *args, **kwargs): if created: print(instance.author, " Created") else: print(instance.author, " was just saved") output: root was just saved root was just saved this is when i update the post, its running two times why? -
Error abot failed (13: Permission denied) while connecting to upstream with Nginx and uWSGI
enter code hereI am trying to build a django page with Nginx and uWSGI, nginx does not show any configuration error of the .nginx and the uWSGI either, that is, it has created the .socket with what I specify. But this error keeps appearing in nginx giving me 502 BAD GETWAY: [crit] 16466 # 16466: * 8 connect () to unix: /home/ubuntu/my_app/my_app.sock failed (13: Permission denied) while connecting to upstream, client: IP server: my_app, request: "GET / favicon .ico HTTP / 1.1 ", upstream:" uwsgi: // unix: /home/ubuntu/my_app/my_app.sock: ", host:" my_app ", referrer:" http: // my_app / " any help regarding the error or what may be causing it? theres my .nginx server { # the port your site will be served on listen 80; # the only path #root /home/django/my_app.com; # the domain name it will serve for server_name my_app; #substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; #adjust to taste # Django media location /media { #your Django project's media files - amend as required alias /home/ubuntu/my_app/media; } location /static { #your Django project's static files - amend as required alias /home/ubuntu/my_app/static; } location /static2 { #your Django project's static files … -
Using jQuery locally with Bootstrap for Django wont respond
I have this in my base.html file included {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} And I'm using navbar navbar-expand-lg navbar-light from Bootstrap for my navbar. This is working. When I'm using a small display (like smartphone) it shrinks the menu to dropdown element with a button to expand. But the {% bootstrap_javascript jquery='full' %} part is taking too long to fully load the jquery source from network: Around 400ms without cache. I would like to lose this waiting time as much as possible. So I downloaded latest jquery 3.6.0 from official site, saved it locally in my static files like static/main_app/scripts/jQuery.js loaded it locally with <script type="text/javascript" src="{% static 'main_app/scripts/jQuery.js' %}"></script> in my base.html. This works and jQuery is working fine. But the Bootstrap's nav-bar buttons are not responding. There is also not error message in browser's console. So I though: Maybe the jQuery version is wrong? So I tried to implement again working version to my site {% bootstrap_javascript jquery='full' %} , look for source of the file above in dev-tools of my browser, copy & pasted the source code to my jQuery.js file and loaded the site again. Nothing changed and the navbar … -
Django Serializer Passing a arguments into model function
New to Django and DRF, I have a method in the model properties which accept arguments. I have managed to call it successful though a serializer class with default paramenters and getting a JSON response. My problem is I can't pass argument to that function named balance. I have successful pass my argument from view to serializer class but from serializer to model that where I have failed. I thought will be appreciated. model.py class Item(models.Model): entered_by = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=50, blank=True) @property def balance(self, stock_type='Retail'): stock = Stock.objects.filter(item=self, type=stock_type, status='InStock').aggregate(models.Sum('quantity')).get('quantity__sum') return stock or 0 views.py def getItemInfo(request): if request.is_ajax and request.method == "GET": id = request.GET.get("item_id", None) sell_type = request.GET.get("sell_type", None) item = Item.objects.get(id=id) if item: serializer = ItemSerializer(item, context={'sell_type':sell_type}) return JsonResponse(serializer.data, status = 200, safe=False) else: return JsonResponse({"data":False}, status = 400) serializer.py from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): balance = serializers.SerializerMethodField() class Meta: model = Item fields = ('entered_by', 'name', 'balance', 'sell_mode') def get_balance(self, object): sell_type = self.context.get("sell_type") if sell_type: return object.balance(sell_type) return object.balance The error I'm getting 'int' object is not callable -
Cant create object with foreign key
I think i am making some silly mistake, but actually it took me already too much time so i will ask here I have two classes isActive.py active = models.BooleanField() human_readable = models.CharField(max_length=20) User.py type = models.CharField(max_length=127) is_active = models.ForeignKey(IsActive, on_delete=models.PROTECT) and in my migration i am using this function to populate: User = apps.get_model("project", "User") db_alias = schema_editor.connection.alias default_active = IsActive.objects.get(pk=1) # its active status A = User(name='Saaa', is_active=default_active) Adserver.objects.using(db_alias).bulk_create([ A ]) Now i get this error : ValueError: Cannot assign "<IsActive: Aktywny>": "User.is_active" must be a "IsActive" instance. And i think i am actually passing the IsActive instance, because it should link it to my user table? -
Django Error Template Tags type error at /
I want to try to create template tags in django, but there is an error when trying it code in my views : from django.shortcuts import render def index(request): context = { 'judul' : 'Home', 'nav': [ ['/','Home'], ['/blog','Blog'] ['/about','About'] ] } return render(request, 'index.html', context) code in my html: <ul> {% for link,name in nav %} <li> <a href="{{link}}">{{name}}</a> </li> {% endfor %} </ul> -
Django drf-social-oauth2 Social Signup fallback login
I am trying to create a SPA, and want enable to Google Sign In/Sign Up. Is there a way to click Sign In with Google and: First try to Sign Up If the user already exists, login and return access token else create the user and then return the access token I also use drf-social-oauth2