Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can compile Django project to War file as boot spring
Can compile the Django project to War file as boot spring? I would like to deploy the Django project as a compiler library which is a similar WAR file of boot spring framework into the webserver? is there any way to hide or encrypt Django source code in order to deploy it into a web server? -
Return multiple fields from django model
As the title says, I want to return two fields (semester, subject) separately from semSubject model and access them in Sem1Attendance. Code as follows, models.py class semSubject(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=7, primary_key=True) category = models.CharField(max_length=9,default="Theory") sem = models.IntegerField(null=True) class Sem1Attendance(models.Model): reg_no = models.ForeignKey(Sem1Students, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices=STATUS) semester = models.ForeignKey(semSubject,related_name='sem_name', on_delete=models.CASCADE, default=1) subject = models.ForeignKey(semSubject, related_name='sub_name', on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) Is there a way to do this? -
Custom method inside Django admin does not throw its error - Why?
I have an admin view in Django which should call and display the result of a custom method. I would expect the following: if that custom method raises an error, I'll see the error popping up in my Django admin view. However, the admin view displays a dash instead: "my_custom_method: -". There is no error in the logs. I do not want to wrap every of my custom methods in a try/catch block. Is there any other way I can force Django to display that exception and quit showing that admin page? class MyAdmin(admin.ModelAdmin): readonly_fields=['my_custom_method'] def my_custom_method(_): raise AttributeError -
Django how to add static in images
How to add {% load static %} in images. example ( "{% static 'images/pic/1.jpg' %}" ) in the same time . if I have templates in html I have 50+ images how can I add {% static %} in images ? -
Get field value from inside the model class
I have a Folder class, which creates a folder when instanciated, with the parent_folder field being the location in which I want the folder to be created. class Folder(models.Model): folder_name = models.CharField(max_length=200, unique=True) parent_folder = models.FilePathField(path=r'media/', allow_files=False, allow_folders=True, recursive=True) def __init__(self, *args, **kwargs): super(Folder, self).__init__(*args, **kwargs) self.initial_filepath = self.filepath() def save(self, *args, **kwargs): on_creation = self.pk is None if on_creation: os.mkdir(self.filepath()) else: os.rename(self.initial_filepath, self.filepath()) super(Folder, self).save(*args, **kwargs) def filepath(self): return os.path.join(self.parent_folder, self.folder_name) When I go to the Django Admin page, there's no issue while creating a folder, however if I go and try to modify it, among the different choices for parent_folder, there's the folder itself, and if I select it, it causes an error because it tries renaming inside itself. My goal is then to remove the folder from the list of folders in which I can move it. I tried using the match attribute of the FilePathField, but I didn't manage to get the value of folder_name of my instance (to match any folder which doesn't contain the name of the folder I'm moving). So if you could help me get the value of folder_name of my instance that would be really appreciated ! -
End Session When browser is closed in python django and javascript
I have created logout def in python, in that def I am deleting session that I have created after login the user. I wish to end/del session when the user closes the browser using(X) OR using(alt+4). how do I call logout url in javascript when user close the browser. Here is def logout: @login_required def logout(request): username = request.session['username'] ip = settings.IP headers = settings.HEADERS del request.session['username'] Here is urls.py from django.urls import path from . import views urlpatterns = [ path('logout', views.logout, name="logout"), ] -
Django/Docker/Postgresql: app connected to the 'wrong' database
I have develop a project with Django/Docker/Postgresql and use docker-compose to deploy on a linux remote server. I want to deploy 2 apps based on the same code (and same settings file), preprod and demo, with two disctincts PostgreSQL databases (databases are not dockerized): ecrf_covicompare_preprod and ecrf_covicompare_demo, respectively for preprod and demo. Apps tests will be done by differents teams. I have : 2 docker-compose files, docker-compose.preprod.yml and docker-compose.demo.yml, respectively for preprod and demo .env files, .env.preprod and .env.preprod.demo, respectively for preprod and demo Databases parameters of connection are set in these .env files. But my 2 apps connect to the same database (ecrf_covicompare_preprod). docker-compose.preprod.yml version: '3.7' services: web: restart: always container_name: ecrf_covicompare_web build: context: ./app dockerfile: Dockerfile.preprod command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - app_volume:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.preprod entrypoint: [ "/usr/src/app/entrypoint.preprod.sh" ] depends_on: - redis healthcheck: test: [ "CMD", "curl", "-f", "http://localhost:8000/" ] interval: 30s timeout: 10s retries: 50 redis: container_name: ecrf_covicompare_redis image: "redis:alpine" celery: container_name: ecrf_covicompare_celery build: context: ./app dockerfile: Dockerfile.preprod command: celery -A core worker -l info volumes: - app_volume:/usr/src/app env_file: - ./.env.preprod depends_on: - web - redis celery-beat: container_name: ecrf_covicompare_celery-beat build: context: ./app dockerfile: Dockerfile.preprod command: celery -A core … -
django aggregate between 2 different querysets
So I have 2 query sets that are from the same model but different records. I already made the pythonic way of getting the result. but I want to do it with aggregate and annotate to get this done. result = [i for i in self.old_searches if round( abs(same_keys.get(keyword =i.keyword).current_position-i.current_position)) >=1] so both of self.old_searches and same_keys have the same field called current_position and for example I need first recprd of the first query be compared with first record second one. but all i need is the current_position. -
Interactive drawing
I'm an enginner working on a shipyard and i'm trying to create a django based tool that helps me track production progres. Helpfull with that would be interactive drawing, I can use contractual data given by my boss, a couple of drawings of a vessel. For sure it is easy to import it as a typical src saved as png ....no biggie. But i need it to be interactive - in example if i'll get an information that area 'A' is completed then area 'A' will change it's colour to lets say green. I'm a beginner when it comes to programming so any suggestions on how to achieve my goal will be helpfull. -
Loop through objects in template and set each elements background image to object's ImageField value using tailwind css
From the tailwind docs, to set the background image to an 'Arbitrary value': <div class="bg-[url('/img/hero-pattern.svg')]"> <!-- ... --> </div> In my template, I am trying to loop through a list of Artist objects and build cards for each one. Artist objects all have a profile_picture attribute which is an ImageField: {% for artist in artists %} <div class="bg-[url('{{artist.profile_picture.url}}')]"> <a href = "{{artist.profile_picture.url}}">Link to Image</a> <!-- put this here to make sure the url is correct and this does take me to the image --> <h1>Some text</h1> </div> {% endfor %} And this is not applying the background image. I can confirm the url is correct because I have inspected the page: <div class="bg-[url('/media/images/artists/headshot.jpeg')]"> <h1>Some text</h1> </div> and visited http://127.0.0.1:8000/media/images/artists/headshot.jpeg where I do see the image. Does anyone know what's going on here? Thanks for any help. Edit: Using Tailwind version 3.0.24 -
Throttling is also restart as our django server restart
i need help of yours. I want to limit my GET API. firstly i can hit this API only for one time(forever with the same system) then i signup then i can hit this same API for 5 times(forever with the same system) then i have to pay some amount then i can hit infinite times. At this time no throttle is used. Below is my code:- Settings.py 'DEFAULT_THROTTLE_RATES': { 'Auserlimit': '1/infinite', 'userlimit': '5/infinite', } throttling.py:- from rest_framework.throttling import AnonRateThrottle, UserRateThrottle import random class limitAUserThrottle(AnonRateThrottle): scope = 'Auserlimit' def parse_rate(self, rate): """ Given the request rate string, return a two tuple of: <allowed number of requests>, <period of time in seconds> """ if rate is None: return (None, None) num, period = rate.split('/') num_requests = int(num) duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400, 'i': 315360000000}[period[0]] return num_requests, duration class limitUserThrottle(UserRateThrottle): scope = 'userlimit' def allow_request(self, request, view): if not request.GET.get('call_type') == 'seu': self.scope = 'userlimit' self.rate = '5/infinite' return True return super().allow_request(request, view) def parse_rate(self, rate): """ Given the request rate string, return a two tuple of: <allowed number of requests>, <period of time in seconds> """ if rate is None: return (None, None) num, period = … -
I Face Following below when install Project in pycharm in Django 'A server error occurred. Please contact the administrator.'
please help me what is the main problem face fallowing error throw which I run Django server A server error occurred. Please contact the administrator. Traceback (most recent call last): File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\defaulttags.py", line 1034, in find _library return parser.libraries[name] KeyError: 'staticfiles' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inn er response = get_response(request) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_re sponse response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\Restaurant_Management_System_Project_Django\hotel\views.py", line 113, in index return render(request, 'index.html', {'food':food}) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\loader.py", line 61, in render_to_s tring template = get_template(template_name, using=using) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\loader.py", line 15, in get_templat e return engine.get_template(template_name) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\backends\django.py", line 34, in ge t_template return Template(self.engine.get_template(template_name), self) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\engine.py", line 143, in get_templa te template, origin = self.find_template(template_name) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\engine.py", line 125, in find_templ ate template = loader.get_template(name, skip=skip) File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\loaders\base.py", line 30, in get_t emplate contents, origin, origin.template_name, self.engine, File "C:\Users\Muhammad Talha Qamar\Desktop\Restaurant_Management_System_Project_Django\env\lib\site-packages\django\template\defaulttags.py", line 1038, in find _library name, "\n".join(sorted(parser.libraries)), django.template.exceptions.TemplateSyntaxError: 'staticfiles' is not a … -
How to aggregate distinct values of one key then sum the matching values of the other key?
I've made a loop that gives me data in the following format: name_quant = [{'name_id': 'S00004', 'quantity': '1'}, {'name_id': 'S00004', 'quantity': '2'}, {'name_id': 'S00003', 'quantity': '1'}, {'name_id': 'S00003', 'quantity': '2'}, {'name_id': 'S00003', 'quantity': '2'}, {'name_id': 'S00002', 'quantity': '1'}] I used the following loop to get the values above: namesequence = EventSequence.objects.filter(description="names").values("Details") name_quant = [{ 'name_id': e['element'][33:39], 'quantity': e['element'][50:51] } for e in namesequence ] So my question is how can I aggregate the name_ids and sum the quantities of matching name_ids so that i get a result like so: name_sum = [{'name_id': 'S00001', 'quantity': '160'}, {'name_id': 'S00002', 'quantity': '50'}, {'name_id': 'S00003', 'quantity': '40'}, {'name_id': 'S00004', 'quantity': '90'}] I would have used the sum function in Django but I have to subscript and loop though the value first which makes it a bit more complicated :/ Any help is appreciated! -
In Django how to get the email address of a Foreign key user
I have a User model and a Project connected where the Project connects to User model with foreign key. How can I select the email address of the permitted user with raw query? (I don't want to use ORM). models.py class Project(models.Model): def __str__(self): return str(self.project) project = models.TextField(max_length=150) company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1) permitted = models.ForeignKey(User, on_delete=models.CASCADE, default=1) I like to send emails to the permitted users but I need the email address of them. This is the raw query I tried: SELECT COUNT(auth_user.id), ??? FROM pro_projects LEFT JOIN auth_user ON auth_user.id = pro_projects.permitted.id -
Django allAuth, Social Signin After simple email signup from same email as google account
I am using allauth for social signup. First I have Signup my account using Gmail by simply filling out a form and setting up a user name and password. for example the Gmail: > hello@gmail.com, Now I am trying to log in via My google account which is created on the same email as mentioned above. But I am getting an error that the email is already registered instead of giving me this error it should authenticate the user to sign in. -
Query aggregated values with database values with gql and django
I have taken over a project using gql and django. It completely follows the structure of the following example: https://stackabuse.com/building-a-graphql-api-with-django/ Now i want to add extra functionality. Ontop of sending databasevalues to the front end, i would also like to send aggregated ones aswell, like number of elements etc. I've added this to the Node as follows: class DatabaseDataNode(DjangoObjectType): print(DatabaseAnnotationData.objects.filter(database_id__exact=5).count()) #Prints correct value total = DatabaseAnnotationData.objects.filter(database_id__exact=5).count() class Meta: print('Hello world') filterset_fields = { 'databaseid': ['exact'], 'name': ['exact', 'icontains', 'istartswith'], 'imagefile': ['exact', 'icontains', 'istartswith'], 'annotations': ['exact'], 'created_at': ['exact'], 'modified_at': ['exact'], 'slug': ['exact'], 'total': ['exact'] # <-- Doesn't work } interfaces = (relay.Node, ) I also add it to the query: const DATABASE = gql` query Database($name: String, $first: Int, $offset: Int) { database(databasename: $name) { databaseid id name total <---------- Added modifiedAt images(first: $first, offset: $offset) { edges { node { imageid imagefile width height objectdataSet{ edges{ node{ x1 y1 width height concepts{ edges{ node{ conceptId } } } objectid imageid{ imageid } } } } } } } } } ` But when i run it i get an error saying "Cannot query field "total" on type "DatabaseDataNode" How can i implement this, to send the other value aswell? -
Django sessions Ajax query returns undefined instead of int value
So basically I'm creating an e-commerce store. And I want to use Django session and ajax query to implement an add-to-cart functionality to my app and when the user selects a quantity of some product, the selected quantity to be visible in the cart section on the navigation bar. But as I select some quantity and click add to cart button the value up in the cart section changes from 0 to undefined. When I decode the session there is no regarding info for the selected product and its quantity. This is my base Cart class: class Cart(): """ A base Cart class, providing some default behaviors that can be inherited or overwited. """ def __init__(self, request): self.session = request.session cart = self.session.get('session_key') if 'session_key' not in request.session: cart = self.session['session_key'] = {} self.cart = cart def add(self, product, qty): """ Adding and updating the user's cart session data """ product_id = product.id if product_id in self.cart: self.cart[product_id]['qty'] = qty else: self.cart[product_id] = {'price': str(product.price), 'qty': qty} self.save() def save(self): self.session.modified = True This is the add_to_cart_view: def add_to_cart(request): cart = Cart(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) cart.add(product=product, qty=product_qty) cartqty = … -
Django: Multiple table Model query
I have tried it on the Q object and in the Django ORM but could not generate the query. class Status(models.Model): id = models.AutoField(primary_key=True) name = models.AutoField(null=True, max_length=100) def __str__(self): return self.name class Billing(models.Model): id = models.AutoField(primary_key=True) name = models.AutoField(null=True, max_length=1000) sr_number = models.AutoField(null=True, max_length=100) def __str__(self): return self.name class BillingInfo(models.Model): id = models.AutoField(primary_key=True) billings = models.ForeignKey(Billing, null=True, on_delete=models.SET_NULL) net_amount = models.AutoField(null=True, max_length=100) company = models.AutoField(null=True, max_length=100) def __str__(self): return self.company class BillingOutput(models.Model): id = models.AutoField(primary_key=True) billing_infos = models.ForeignKey(BillingInfo, null=True, on_delete=models.SET_NULL) lbl_name = models.AutoField(null=True, max_length=100) lbl_qty = models.AutoField(null=True, max_length=100) status = models.ForeignKey(Status, null=True, on_delete=models.SET_NULL) def __str__(self): return self.lbl_name I required an equivalent ORM Query for the below raw SQL query: select bio.* from billing bil inner join billing_infos bi on bil.id = bi.billings_id inner join billing_output bio on bi.id = bio.billing_infos_id where bo.status_id = 1 order by bio.id desc; Could someone please help me with this issue? -
Reverse for 'detail_page' with no arguments not found. 1 pattern(s) tried: ['detail\\-page/(?P<slug>[^/]+)\\Z']
urls.py urlpatterns = [ path('', home_page, name='home_page'), path('posts-page/', posts_page, name='posts_page'), path('detail-page/<slug>', detail_page, name='detail_page'), ] views.py def detail_page(request, slug): post = get_object_or_404(Post, slug=slug) context = { 'post': post, } return render(request, 'detail_page.html', context=context) base.html <div class="navbar"> <nav class="navigation hide" id="navigation"> <span class="close-icon" id="close-icon" onclick="showIconBar()"><i class="fa fa-close"></i></span> <ul class="nav-list"> <li class="nav-item"><a href="{% url 'home_page' %}">Forums</a></li> <li class="nav-item"><a href="{% url 'posts_page' %}">Posts</a></li> <li class="nav-item"><a href="{% url 'detail_page' %}">Detail</a></li> </ul> </nav> <a class="bar-icon" id="iconBar" onclick="hideIconBar()"><i class="fa fa-bars"></i></a> <div class="brand">My Forum</div> </div> detail_page.html <!--Topic Section--> <div class="topic-container"> <!--Original thread--> <div class="head"> <div class="authors">Author</div> <div class="content">Topic: {{ post.title }} (Read 1325 Times)</div> </div> <div class="body"> <div class="authors"> <div class="username"><a href="">{{ post.user.fullname }}</a></div> <div>Role</div> <img src="{{ post.user.profile_pic.url }}" alt=""> <div>Posts: <u>45</u></div> <div>Points: <u>4586</u></div> </div> <div class="content"> {{ post.content | safe }} <br> <div class="comment"> <button onclick="showComment()">Comment</button> </div> </div> </div> </div> I have objects in db and i try to get page with post and i get this error, i understand tha problem mix with slug and that something wrong with this argument, but i really idk why -
How to use the power of uvicorn and asgi in django?
I implemented a tiny Django app (v4.0.4) containing a REST API — GET method for retrieving some data. Next, I wanted to run the project using gunicorn+uvicorn since I saw a more benchmark performance than a normal deployment in an article. So I decided to get my own benchmark using wrk tool. Here's what I've got: Command Webserver Protocol Result (Req/Sec) python manage.py runserver 0.0.0.0:8000 Django Default wsgi 13.06 gunicorn bitpin.wsgi:application --bind 0.0.0.0:8000 -w 2 gunicorn wsgi 45.20 gunicorn bitpin.asgi:application --bind 0.0.0.0:8000 -w 2 -k uvicorn.workers.UvicornWorker uvicorn+gunicorn asgi 22.17 However, the above result demonstrates something else! Is the reason that when I want to use asgi I have to use async method instead for my API view? If so how can I change a Django REST API view to an async one? Or might I've missed some configurations? [NOTE]: I ran the benchmark using the following command: wrk -t4 -c11 -d20s -H "Authorization: Token xxx" http://127.0.0.1:8000/api/v1/content/ It is worth mentioning that for this test I used two workers for gunicorn and it is obvious that the higher workers, the better the performance will be. -
Pass option value from select to view
I am trying to create an interactive scatterplot with options from an selectbox as a filter in Django. The problem is that the value from the select box is not passed to the view. views.py def dashboard(request): cool_data = manage_pandas(df_raw) posnr=cool_data['something'].unique() pos = request.GET.get('posi') dff = cool_data.loc[cool_data['posnr'] == pos] dff = dff.astype({'vnum': str}) fig = px.scatter_matrix(dff, dimensions=["a", "b", "c", "d",'e'], color="g") fig.update_traces(diagonal_visible=False) sm = plot(fig, output_type="div") context = { 'posnr' : posnr, 'plot_div':sm } return render(request, "scatterplot/scatterplot.html", context) scatterplot.html <div class = "container" id = "second" style="display:true"> <br><br> <select class="position"> {% for pos in posnr %} <option value="{{ pos }}">{{ pos }}</option> {% endfor %} </select> {% autoescape off %} {{ plot_div }} {% endautoescape %} <script> $("select.position").change(function(){ var posi = $(this).children("option:selected").val(); }); </script> I don't want to use form submit because I want the scatterplot to change automatically based on user input. Thanks -
How to list files by pk
Im newbie and trying to get lists of each backup devices.Im just tried myself and wrote useless thing, help. class Backups(View): @staticmethod def get(request, pk): dvcs = [Device.objects.filter(pk=pk) for pk in glob.glob("/static/backup/*.txt")] form = BackupsForm() context = {'dvcs': dvcs, 'form': form} return render(request, 'Recentbackups.html', context) -
Definig element.sortable()-function
My html table supports changing the row-order using mouse drag and drop. The used jquery-ui version is v1.12.1. It works for old tables (i.e. those whose row count is known since load of the page), but it doesn't work for rows added after the page has been loaded. I think the reason is that the below sortable()-function is inside document.ready()-function. <script type="text/javascript"> <script src="{% static 'js/jquery-ui.js' %}"></script> $(document).ready(function(){ $('#luok_table tbody').sortable({ stop: function( event, ui ){ $(this).find('tr').each(function(i){ $(this).attr("id", $(this).attr("id").replace(/\d+/, i) ); $(this).find(':input').each(function(){ $(this).attr("id", $(this).attr("id").replace(/\d+/, i) ); $(this).attr("name", $(this).attr("name").replace(/\d+/, i) ); }); }); } }); }); </script> If that's the reason, where should I define the sortable()-function ? The table rows are added by jquery-formset-js-script (https://gist.github.com/vandorjw/f884f0d51db3e7caaecd#file-jquery-formset-js) -
How do I write setUpClass() and tearDownClass() creating and logging in a user?(Django Rest FrameWork)
I have this test case written for two models with local permission_classes, [IsAdminUser] and [IsAuthenticated] respectively. After running the test cases both the test are failed and according to the exception messages, it is clear that the user is not getting logged in. class PermissionClassesTest(APITestCase): @classmethod def setUpClass(cls): super(PermissionClassesTest, cls).setUpClass() print('running before tests') cls.user = User.objects.create_user(username='admin', password='qwefghbnm', is_staff= True) cls.client = APIClient() cls.client.login(username=cls.user.username, password='qwefghbnm') @classmethod def tearDownClass(cls): super(PermissionClassesTest,cls).tearDownClass() print('running after test') def test_SalaryDetail_local_permission(self): response = self.client.get('/salaryDetails/') self.assertEqual(json.dumps(response.data), '{"detail": "You do not have permission to perform this action."}') def test_EmployeeDetail_local_permission(self): response = self.client.get('/employeeDetails/') self.assertTrue(status.is_success(response.status_code))``` -
How to create a double range slider linked to two model fields in Django
I am trying to create a double range slider on a CreateView and UpdateView linked to two model fields in Django representing a minimum and maximum value. I found this tutorial but I am hoping there is something more simple which can be built without moving away from class based views to avoid needing to rework lots of views/forms. Any help would be greatly appreciated :)