Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to increment a django value_list
I'm trying to find a way to add one more element to the list, but with my first attempt using append it didn't work, as it's a queryset. Any tips on how to add an element to generos after the value_list query? generos = Specie.objects.values_list('Genus', flat=True) generos.append('NA') -
How to dinamically access to a field in django form to change instance
Using a generic CreateView in Django I'm trying to save only the fields that have been changed by user. I'm trying to do this in my view: def form_valid(self, form): if form.has_changed(): for field in form: if field.name in form.changed_data: continue else: form.instance.field=None In the last line I got this error: object has no attribute 'field' Is there a way to dynamically access to each field in the form? so I could change it? -
How to get the latest (distinct) records filtered by a non unique field in Django
I'll demonstrate by using an example. This is the model (the primary key is implicit): class Item(models.Model): sku = models.CharField(null=False) description = models.CharField(null=True) I have a list of skus, I need to get the latest descriptions that are written in the table for the model Item. Latest item == greatest id. I need a way to annotate the latest description: Item.objects.values("sku").filter(sku__in=list_of_skus).annotate(latest_descr=Latest('description').order_by("-id") but this won't work for various reasons (excluding the missing aggregate function). -
Can I tell PyCharm that a function argument is a Django template path to enable autocomplete?
In Pycharm, values from built-in Django functionality which will eventually be used as the argument to resolve_template (such as the template_name property on TemplateView) are subject to autocomplete using the Django template lookup syntax. I have a custom function whose signature includes a template name. Is there a way to annotate this function such that PyCharm will provide the same template directory autocomplete for uses of this custom function as it provides for built-in functionality? -
Subclassing TemplateView with Mixins - a bad idea?
I have several "Listing" views which are very similar and I feel like I'm unecessarily repeating myself. Subclassing seems like the answer, but I've run into problems down the line before when subclassing things in Django so I'd like to ask before doing so. If I have 2 views, like this, which use the same template, a variable message and different querysets: class MyGiverView(LoginRequiredMixin, TemplateView): template_name = "generic_listings.html" message = "" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["list_of_stuff"] = MyModel.objects.filter( giver=self.request.user, status=1, ) context["message"] = self.message return context class MyTakerView(LoginRequiredMixin, TemplateView): template_name = "generic_listings.html" # this hasn't changed message = "" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["list_of_stuff"] = MyModel.objects.filter( taker=self.request.user, # this has changed status__in=(1,2,3), # this has changed ) context["message"] = self.message # this hasn't changed return context Am I going to screw it up by creating a base class like: class MyBaseView(LoginRequiredMixin, TemplateView): template_name = "generic_listings.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["list_of_stuff"] = self.qs context["message"] = self.message return context And using it in my views as such: class MyGiverView(MyBaseView): qs = MyModel.objects.filter( giver=self.request.user, status=1, ) message = "" class MyTakerView(MyBaseView): qs = MyModel.objects.filter( taker=self.request.user, status__in=(1,2,3), ) message = "" It's DRYer, but I'm unsure of the … -
How do we pick objects from a model to create copies in another model adding extra parameters in django?
I have the following models: class Questionnaire(models.Model): questionnaire_name = models.CharField(max_length=120, default="") ... class Question(models.Model): question_body = models.TextField() ... class QuestionnaireContent(models.Model): questionnaire = models.ForeignKey(Questionnaire) question = models.ForeignKey(Question) ... The QuestionnaireContent model acts as a list of questionnaire templates. Those are assigned to users eventually, using: class QuestionnaireAssignment(models.Model): user = models.ForeignKey(User) questionnaire = models.ForeignKey(Questionnaire) Now, ideally, I would like this assignment to generate a new questionnaire 'instance' in another model which would have the following fields: class QuestionnaireInstance(models.Model): user = models.ForeignKey(User) questionnaire = models.ForeignKey(Questionnaire) question = models.ForeignKey(Question) visibility = models.BooleanField() But I would like that QuestionnaireInstance to be created automatically once a QuestionnaireAssignment instance is created. I guess I could rewrite the save function of QuestionnaireAssignmentbut I am wondering if there is a simpler/cleaner way to do this? The idea is I want from the template questionnaires to create instance for users that can be customized for that user (adding attribute visibility and eventually changing the questions). Thanks for your help!! -
Sum aggregation over list items in Django JSONField
I'd like to calculate the sum of all elements in a list inside a JSONField via Django's ORM. The objects basically look like this: [ {"score": 10}, {"score": 0}, {"score": 40}, ... ] There are several problems that made me use a Raw Query in the end (see SQL query below) but I'd like to know if it is possible with Django's ORM. SELECT id, SUM(elements.score) AS total_score FROM my_table, LATERAL (SELECT (jsonb_array_elements('results')->'score')::integer AS score ) AS elements GROUP BY id ORDER BY total_score DESC The main problems I faced is that the list in the JSONField needs to be turned into a set via jsonb_array_elements. Afterwards it is impossible to run an aggregate function over the results. Postgres complains: aggregate function calls cannot contain set-returning function calls Using a LATERAL FROM -- as widely suggested -- is not possible with the ORM. Not even with Django's .extra() queryset method because it is not possible to specify an additional table that is not quoted in the final query: Model.objects.annotate(...).extra( tables="LATERAL (SELECT (jsonb_array_elements('results')->'score')::integer AS score) AS elements" ) # ERROR: no relation "LATERAL (SELECT ..." -
Python\Django deployment with Jelastic cloud
i try to deploy an app on Jelastic cloud without success. I have a generic error message "RuntimeError: populate() isn't reentrant" and i'm not allowed to modify "django/apps/registry.py" for more details. This project run with manage.py Structure of my project: ROOT |_wsgi.py |_requirements.txt |_monprojet |_monapplication |_ ... |_manage.py |_monprojet |_settings.py |_ ... WSGI.PY virtenv = os.path.expanduser('~') + '/virtenv/' virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: if sys.version.split(' ')[0].split('.')[0] == '3': exec(compile(open(virtualenv, "rb").read(), virtualenv, 'exec'), dict(__file__=virtualenv)) else: execfile(virtualenv, dict(__file__=virtualenv)) except IOError: pass sys.path.append(os.path.expanduser('~')) sys.path.append(os.path.expanduser('~') + '/ROOT/') os.environ['DJANGO_SETTINGS_MODULE'] = 'ROOT.monprojet.monprojet.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() settings.py extract : ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'monapplication', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'monprojet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'monprojet.wsgi.application' Thanks -
When i should use put or patch method?
in Put method, you have to send all the properties of the object to be updated, but patch one or two or all. But well, I send one or two properties in the put method, they are updated, and the rest of the properties are there as before. Can someone guide me where exactly they should be used? -
Django: How to display current date in html using javscript (jquery)
I am prepending a html document, so when user post a comment, it shows up in real time. Now the problem is the way the date is looking, i want the date to show in a format like this 3s ago and not 09/08/2022 2:41 p.m., what is the best to achieve this let _html = ' <div class="details_Comment"> <h4><b>{{c.user.username|title}}</b> <span>{% now "SHORT_DATETIME_FORMAT" %} ago</span></h4> <p>' + _comment + '</p> </div>\ ' $(".comment-wrapper").prepend(_html) -
How to (optimally) serialize joined tables in django rest framework, with many-to-one relation on non-integer primary key
I have a PostgreSQl database with three main tables: houses, searches for those houses and users making the searches. The houses have characteristics, e.g. an address and price, a user can search multiple times for the same house and in the search give the house a rating. A House: [ { "house_id": "0363200000499764", "address": "Bos en Lommerplein 104, Amsterdam", "street": "Bos en Lommerplein" "city": "Amsterdam", "price": 700000 }, ] Multiple Searches for the same house by different users: [ { "search_id" : 1, "house_id": "0363200000499764", "user_id": 1, "date_searched": "2022-09-07 12:14:14", "rating": 1 }, { "search_id" : 2, "house_id": "0363200000499764", "user_id": 1, "date_searched": "2022-10-08 14:00:00", "rating": 2 }, { "search_id" : 3, "house_id": "0363200000499764", "user_id": 3, "date_searched": "2022-04-01 09:36:32", "rating": 4 }, { "search_id" : 4, "house_id": "0363200000499764", "user_id": 2, "date_searched": "2021-09-08 18:59:10", "rating": 5 }, ] Users: [ { "user_id": 1, "first_name": "John", "last_name": "Doe" }, { "user_id": 2, "first_name": "Jane", "last_name": "Doe" }, { "user_id": 3, "first_name": "Patrick", "last_name": "West" }, ] I am using Django and created models for these tables in the database. Snippet from my models.py file: from django.db import models from django.contrib.auth.models import User class House(models.Model): house_id = models.CharField(max_length=16, blank=True, unique=True, primary_key=True) address = models.CharField(max_length=200, … -
Django python score card keeper
I am trying to develop a scoring sheet app for my football club. I have models for Player, Scoresheet, Season ,etc. What I would like to achieve is basically when a game takes place, the scoresheet model will have a form where the person can capture the total score of the team and also the goals of each player, freekicks. My issue is how do I link the players stats to the scoresheet in a form, for example if I have 11 players, I want the scoresheet to be able to take in the 11 players and how many goals they scores, freekicks if any, red cards if any etc. my Models are as follows class Player(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,related_name="playeruser") Player_name = models.CharField(max_length=40) Player_surname = models.CharField(max_length=40) Player_ID = models.CharField(max_length=40) Player_Email = models.CharField(max_length=40) Player_Contact = models.CharField(max_length=40) category = models.ForeignKey(Category,on_delete=models.CASCADE,related_name="pcategory") Player_preferred = models.CharField(choices=Roles,default="default",max_length=16) def __str__(self): return self.Player_name + " " + self.Player_surname class Score_sheet(models.Model): season = models.ForeignKey(Season,on_delete=models.CASCADE,related_name="season") category = models.ForeignKey(Category,on_delete=models.CASCADE,related_name="sscategory") players = models.ManyToManyField(Player,related_name="players") captain = models.ForeignKey(Player,on_delete=models.CASCADE,related_name="captain") Date = models.DateField() Venue= models.CharField(max_length=40,null=True,blank=True) description = models.TextField(null=True,blank=True) goals= models.IntegerField(null=True,blank=True) freekicks = models.IntegerField(null=True,blank=True) redcards = models.IntegerField(null=True,blank=True) yellowcards = models.IntegerField(null=True,blank=True) def __str__(self): return str(self.season) + " " + self.Venue Please let me know if anything is unclear. -
Django database structure issue
I am making a python django project and I am having some trouble wrapping my head around how I should structure the database in order to execute the wanted outcome. I should say that I am using the default sqlite database. The idea is to have the user create different IRL tasks for them to do and for the tasks to be in a sort of pool of tasks. The different tasks will eventually come one after another in a sort of template that the different users can create (Every user can access the other users' templates and tasks). Every task will have an estimated time of when it should be completed and a user can choose to initiate a template and then complete tasks in the website as they complete the tasks in real life. The problem is that different users should be able to use the same tasks (thus, you can't make a Boolean model attribute for complete because different users use the same tasks). Another problem is fact that the users should be able to order the different tasks in a template as they deem fit. I have tried to think of a solution to this problem … -
Django ajax search button more than one data
I have a django project. In this project, I made a search box with ajax, but the same data is coming more than once. Is the problem in ajax? or is the problem in django? I am not sure. Please help me. Hey guys.I have a django project. In this project, I made a search box with ajax, but the same data is coming more than once. Is the problem in ajax? or is the problem in django? I am not sure. Please help me. Hey guys.I have a django project. In this project, I made a search box with ajax, but the same data is coming more than once. Is the problem in ajax? or is the problem in django? I am not sure. Please help me. my html code enter code here <form class="search-content" method="POST"> {% csrf_token %} <input type="text" name="text" placeholder="Ne Aramıştınız?" id="searchInputChange"> <button>Ara <i class="fas fa-search"></i></button> </form> <div class="all-dietitans-content"> <div id="null-search-dietitians"> Aradığınız sonuç bulunamadı. Lütfen aradığınız kelimeyi gözden geçiriniz. </div> {% for posts in posts%} <div class="dietitans" data-firs-load="true"> <div class="left-image"> <img src="{{posts.photo}}" alt=""> <a onclick="openVideoModal(event)" data-iframe-link="{{posts.video}}"> <i class="far fa-play-circle"></i> <br> İzle </a> </div> <div class="right-content"> <div class="dietitans-infos"> <div class="left"> <div class="name"> {{posts.isim}} {{posts.soyisim}} </div> <div class="degree"> … -
Which Frontend framework comes best with Django?
I'm currently building a full stacks web application with Django as a backend framework. I did some research and found out that there are some famous tech stacks used such as the MERN, MEVN, MEAN stack, just wondering if there are any frontend framework that best fit with the Django as a working tech stacks Thanks -
Django is giving me NoReverseMatch at /post/5/ error when I deploy while everything works fine locally
Django is giving me NoReverseMatch error for no reason. Everything works fine in my local environment but as soon as I deploy, I get this error. I got this error yesterday also, when I implemented a button for adding posts. At that time, I tried to find the error but couldn't and gave up but today when I opened the page, the error was gone. Now I feel that whenever I implement a new feature, django likes to throw that error at me for no reason and later it gets fixed on its own?? This is driving me crazy please I would really appreciate if someone can help. Also, this is my first post here so try to forgive me if I make a mistake in posting. Error: NoReverseMatch at /post/5/ Reverse for 'post_delete' not found. 'post_delete' is not a valid view function or pattern name. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.postList, name='post_list'), path('post/new/', views.postNew, name='post_new'), path('post/<int:pk>/', views.postDetail, name='post_detail'), path('post/edit/<int:pk>/', views.postEdit, name='post_edit'), path('post/delete/<int:pk>/', views.postDelete, name='post_delete'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from blog.models import Post from blog.forms import PostForm from django.utils import timezone import datetime # Create your views here. … -
how can i test this function from firebase verify_id_token in backend without frontend?
how can i verify the token id from firebase? def login(request): authorization_header = request.META.get('HTTP_AUTHORIZATION') token = authorization_header.replace("Bearer ", "") try: decoded_token = auth.verify_id_token(token) cars = Person.objects.all() response_object = {'data': serialize("json", cars)} except: return JsonResponse({"data": "user token id invalid"}) return JsonResponse(response_object) i am getting this error: AttributeError: 'NoneType' object has no attribute 'replace' it suppose what i have to send firebase.auth().currentUser.getIdToken() from frontend to backend, but how can i test this function just in backend without frontend? what else i have to do in the backend side? -
Upload Images to Django starcross gallery from External Script
first time question. I have been playing with Django and needed a photo gallery, and made a basic one, then found starcross gallery (https://github.com/Starcross/django-starcross-gallery). It works really nice and easy to put into my app, but from what I can tell its made for dragging and dropping images in, or by adding them from the django-admin page. I need to be able to add photos from an external script. I haven't dealt with ImageField before. I was able to import the gallery.models in my api views file, and make it so I can POST and add those ok. But I have been pulling my hair out trying to get actual images to upload. From looking around, I found I think how to do it with curl (I make my requests with curl then port it to python), and it gave me CSRF issues with a 403 Forbidden. How can I upload an image and bind it to an album, externally with curl or Python? Thanks -
Django Import Export: NOT NULL constraint failed
I'm Building a fairly simple Django app to import and export Excel files (.xlsx, .xls) and whenever i click on 'SUBMIT' after importing the excel file, i keep getting this error I've installed the import-export library, also included it in my settings.py and i also made use of the ImportExportModelAdmin in my admin.py. I don't know what else to do. .enter image description here -
Display data from mongodb to html page in realtime
I'm working on a python project, and I want to fetch and display data from mongodb in real-time, for example, display the new data in an html table page as soon as it's pushed to the DB, and the other data will be displayed while refreshing the page. Any help is highly appreciated. this is my view.py : def datatable_view(request): if request.method =='POST': form = Scraping(request.POST) if form.is_valid(): subject=form.cleaned_data['subject'] #run python code of scraping scrap(subject) #add the products scraped to the database client = pymongo.MongoClient("mongodb://localhost:27017/") # use variable names for db and collection reference db= client["db2"] col = db[subject] products = col.find() context = {'products' : products} #open datatable html and display all the data from database return render(request,'datatable.html', context) return this is my html table page : <table id="scrap" class="table table-striped table-bordered" style="width:100%"> <tbody> {% for product in products %} <tr> <td> {{ product.Title }} </td> <td> {{ product.Price }} </td> <td> {{ product.Currency }} </td> <td> {{ product.Stars }} </td> <td> {{ product.Orders}} </td> <td> {{ product.Shipcost }} </td> <td> {{ product.Supplier }} </td> <td><a href="{{product.Productlinks }}"> Click here</a></td> </tr> {% endfor %} </tbody> </table> -
How to access rectangular array values of data model fields in Django
Consider this model: from django.contrib.postgres.fields import ArrayField class Board(models.Model): pieces = ArrayField(ArrayField(models.IntegerField())) As a example, suppose that this is one of the values: [[1,2], [3,4]] I tried to access the values of this nd array, but I got list index out of range error. Board= Board.objects.all() final_list = [ { "pieces_one": row.pieces[0][0], "pieces_four": row.pieces[1][1] } for row in Board ] Any suggestion on accessing nd array filed's inner values? Of course, I am using Postgres as my database. -
What's the most pythonic way to test if obj has any permission from a list
In both Django and Django Guardian it's simple to test if a user has a permission: user.has_perm('app.can_eat_pizzas') It's also easy to test if it has all permissions: user.has_perms(('app.add_student', 'app.can_deliver_pizzas')) What's the most pythonic way to test if the user has any permission? I know I can just chain an if/or statement, but this feels cumbersome: if user.has_perm('app.add_student') or user.has_perm('app.can_deliver_pizzas') -
'RuntimeError: cannot schedule new futures after interpreter shutdown', while sending message on channel layer, in Django
I am trying to send the message over channel layer, where I am using Thread to start the function continuously, channel_layer = get_channel_layer() async def send_data(): try: await (channel_layer.group_send)('Live_Message_Layer', { 'type': 'send_live_message', 'value': {'live_message':json.dumps(message)}}) except: print("Error while sending message ...\n", traceback.format_exc()) # RuntimeError: cannot schedule new futures after interpreter # shutdown class MyWorker(Thread): def __init__(self): Thread.__init__(self) def run(self): print('Worker is running .....') while True: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(send_data()) loop.close() time.sleep(0.5) MyWorker().start() In the above code, messages are changing every second, and sending it on channel layer. and this is deployed on the ubuntu, using daphne and gunicorn. what is exactly happening when server gets restarted everything works fine, but after some time, somehow this error occurs and after that the last message when the error start occurring, has sent over the channel layer repeatedly until I restart the server. Thank you !!! -
Django object has no attribute in a _set.filter
when I make .all then everything works fine when I try to filter for a single value I get AtributeError what am I missing ? @property def mathe2(self): return self.lehrertabelle_set.filter(Stundenanteil_bei_WE = self.Stundenanteil_bei_WE) + self.SON_Gesamt_Gesamt -
How to filter those Students( equal section with Staffs) to Staffs in Django form
I have no fully experience on Django, mean I am fully a beginner on it. Here is my question ... my Staff model is: class Staffs(models.Model): """ Staff models. """ teacher_of_section = models.ForeignKey(Sections, on_delete=models.CASCADE) And that of Student model is: class Students(models.Model): """ Student models. """ section_name = models.ForeignKey(Sections, on_delete=models.CASCADE) Lastly the form is: class AddResultForm(forms.Form): """ Forms that adds the students Result.""" student_list = [] students = Students.objects.filter(section_name=2) try: for student in students: small_student = (student.id, str(student.admin.first_name)) student_list.append(small_student) except: student_list = [] From those models, I want to filter all students that fulfills Staffs.teacher_of_section == Students.section_name I tried to compare the value of the two and set the staff value to filter the students, but it can't work. I know it can work with JQuery, but I want to work with Django only. The form should filter all students that is similar section with Staff and drop the other students - it is many to many relationship of students and staffs. Kindly, I want help for this, it stucks me on the code for the days...