Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save nested objects in Django from a dictionary
I have a small problem with repeating myself by creating nested related objects. I get a JSON from an API call which I convert it to a nested dictionary. This nested dict has a lot of related objects which I have to check if their fields have a related_model in order to create the related object before creating the actual object... I have 3 functions that are the same, but with different name: get_or_create_object get_or_create_related_object get_or_create_subrelated_object Here is the code: def get_or_create_object(object_dict:dict, Klass): # Main object just_fields_dict = object_dict just_related_objects_dict = {} for key in object_dict.copy().keys(): key = _validate_field_name(key) related_model = getattr(Klass, key).field.related_model if related_model: if isinstance(object_dict[key], list): print(object_dict[key]) else: value = _clean_object_dict(object_dict[key]) obj = get_or_create_related_object(object_dict=value, Klass=related_model) just_related_objects_dict[key] = obj just_fields_dict.pop(key, None) composed_object_dict = {**just_fields_dict, **just_related_objects_dict} obj, _ = Klass.objects.get_or_create(**composed_object_dict) return obj def get_or_create_related_object(Klass, object_dict): # Related object to main object just_fields_dict = object_dict just_related_objects_dict = {} for key in object_dict.copy().keys(): related_model = getattr(Klass, key).field.related_model if related_model: object_dict = _clean_object_dict(object_dict[key]) obj = get_or_create_subrelated_object( Klass=related_model, object_dict=object_dict ) just_related_objects_dict[key] = obj just_fields_dict.pop(key, None) composed_object_dict = {**just_fields_dict, **just_related_objects_dict} obj, _ = Klass.objects.get_or_create(**composed_object_dict) return obj def get_or_create_subrelated_object(Klass, object_dict): # Related object to "Related object to main object" # In other words: subrelated object just_fields_dict … -
Make form input searchable for items from a different model
I have a form that will be used to add a drinks recipe to my database. The form allows for up to 10 ingredients plus their amount to be added as well as information, name and a picture of said drink. I now want to make the text input blocks to be linked to a model that contains all possible ingredients in my database. I would like these text blocks to work as a searchbar for the ingredients. Is there a way to make this work? see my setup below: Template view so far: {% extends 'base.html' %} {% block content %} <div class='container'> <div class='row'> <form method="POST" enctype='multipart/form-data'> {% csrf_token %} <div class='row'> <div class='col'> <div class='mb-5'> {{form.drink_name.label_tag}} <br> {{form.drink_name}} </div> {% for ingredients in form %} {% if forloop.counter < 21 %} {{ingredients.label_tag}} <br> {{ingredients}} <br> {% endif %} {% endfor %} </div> <div class='col'> {% for ingredients in form %} {% if forloop.counter > 21 %} {{ingredients.label_tag}} <br> {{ingredients}} <br> {% endif %} {% endfor %} </div> <div class='row my-4'> <input type='submit' value='submit' class='my-2'> </div> </form> </div> {% endblock content %} Models: ingredient model: class Bottle(models.Model): category_name = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True) brand = models.ForeignKey('Brand', on_delete=models.CASCADE) bottle_name = models.CharField(max_length=255) … -
Python: Delete a rows in db if it is not in the API
In my database, I have a Trader and Position table. For each position retrieved via the API url, I look if it exists in my table. If the position does not exist, I create it. I would like to delete the Position in my database if it does not exist in the API. I can't modify the data coming from the url because it comes from an external API. Only the data (encryptedUid, symbol) are fixed, the others are data related to the price of a cryptocurrency Here is what the JSON data from the url looks like: { 'symbol': 'BTCUSDT', 'encryptedUid': '08F22AF1161739C74509F9F38F188A8D', '......': ......, } My code (Django Command) def handle(self, *args, **kwargs): traders = Trader.objects.all() for t in traders: uid = t.encrypted_uid payload = {'encryptedUid': uid, 'tradeType': 'PERPETUAL'} positions = requests.post(self.URL_POSITION, json=payload).json()['data']['otherPositionRetList'] if positions is not None: for p in positions: p['uid'] = uid find_positions = Position.objects.filter(trader=t).filter(symbol=p['symbol']) if not find_positions: trader = Trader.objects.get(encrypted_uid=p['uid']) self.save(trader, p) Data from my db <QuerySet [{'id': 117, 'trader_id': 1, 'symbol': 'BNBUSDT', 'entry_price': 342.966434, 'amount': 350.0, 'direction': '', 'leverage': 25.0, 'closed': False}]> I tried to make a loop on all the Positions. To loop over the API to find the matches with (encryptedUid & … -
Django querysets being cached when using custom manager and properties
I have a Django model that uses properties to derive "fields" whenever called. I did this rather than creating these as database values as these "fields" are all calculable from model fields and should be calculated on the fly when required. As these do not exist at the database-level and can't be accessed via queryset I created a custom manager with methods that look-up all the ids of a queryset with the condition of a property or properties required and then re-lookup a queryset for those ids. What is happening is that the resulting querysets are completely cached and any updates to the underlying database is not reflected when refreshing the views. I am using djange-tables2 and filters so the views are mostly based of generic form views calling the custom manager methods as input into the queryset variable. Does anyone have any ideas as to what I am doing wrong? Any pointers will be greatly appreciated. The models.py is as follows: from django.db import models from datetime import date import datetime from business.calendar import Calendar from django.urls import reverse from simple_history.models import HistoricalRecords from taggit.managers import TaggableManager from contacts.models import Contact # ToDo: Move calendars to global yml and … -
Django Pylint failed to parse the output
I am running a django server on Linux environment. When running pylint from commandline there is no error. Versions pylint 2.15.5 astroid 2.12.12 Python 3.10.6 (main, Nov 2 2022, 18:53:38) [GCC 11.3.0] pylint_django 2.5.3 VSCode: Version: 1.73.1 (system setup) Commit: 6261075646f055b99068d3688932416f2346dd3b Date: 2022-11-09T04:27:29.066Z Electron: 19.0.17 Chromium: 102.0.5005.167 Node.js: 16.14.2 V8: 10.2.154.15-electron.0 OS: Windows_NT x64 10.0.22000 Sandboxed: No pylint --load-plugins=pylint_django --django-settings-module=server.settings /root/server/app/test.py But when .pylintrc file is editted and I add these values to the config. I get the following error. ##########Linting Output - pylint########## [ERROR 2022-10-30 19:15:36.361]: Linter 'pylint' failed to parse the output '. SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at s.parseMessages (/root/.vscode-server/extensions/ms-python.python-2022.18.2/src/client/linters/pylint.ts:48:39) at s.run (/root/.vscode-server/extensions/ms-python.python-2022.18.2/src/client/linters/baseLinter.ts:99:31) at runMicrotasks (<anonymous>) at process.messages (node:internal/process/task_queues:96:5) at s.runLinter (/root/.vscode-server/extensions/ms-python.python-2022.18.2/src/client/linters/pylint.ts:21:15) Anyone who has encountered the same problem and knowns how to fix this issue. Tried running the command and that worked, but when it's run from the default python extension it gives an error. -
CSS files not loading in django
This is my first Django project. I cannot load CSS files onto my website. i've done everything possible. Project Directries firstproject/ static/ css/ <CSS files> Settings.py/ static files STATIC_URL = 'static/' STATICFILE_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') urls.py urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) HTML file <link rel="stylesheet" href="{% static 'css/bootstrap-grid.css' %}"> -
How to create a ModelViewset when model has OneToOneField?
The idea is to have a model like this: class Object(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=256) def __str__(self): return self.name and then create a serializer and a ModelViewSet related to it. The problem is that ModelViewSet must return a queryset but I want to work with single objects due to the one-to-one relation. How should I proceed? -
Django : How to create a Task with Subtask system
I am trying to develop something that allows me to create Tasks to complete in a project and then you can add subtasks so each task etc. Example : The project is to build a house, the main tasks are let's say, the plumbing, then the roof and finally the rest of the architecture. For the plumbing, you then need to do the sketches first, then to figure out what kind of pipes, etc. So for each task you have subtasks and so on. class Project(models.Model): project_name = models.CharField(max_length=100) class Task(models.Model): task_name = models.CharField(max_length=100) task_project = models.ForeignKey('Project', on_delete=models.SET_NULL, null=True) class SubTask(models.Model): subtask_name = models.CharFiedl(max_length=100) subtask_parent = models.ForeignKey('Task', on_delete=models.SET_NULL, null=True) So here in my code, each Project have like several Main Tasks and then we get the Subtasks. The goal is that I can keep on creating Subtasks that then belong to a parent Subtask if that makes sense. I can't figure out what type of connection that is or how to approach the issue. Many thanks ! -
How can I get all objects of a model and it's fields?
I have a Product Model and I want to be able to count all it's objects in a method so I can render the total number in a template, same for each category but I can only do that with the number_of_likes method. class Category(models.Model): name = models.CharField(max_length=45) ... class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) category = models.ForeignKey(Category, default=None, on_delete=models.PROTECT) product_type = models.CharField(max_length=30, choices=TYPE, default='Physical') likes = models.ManyToManyField(User, related_name='like') ... def number_of_likes(self): return self.likes.count() def number_of_products(self): return self.all.count() def number_of_products_for_category(self): return self.all.category.name.count() def __str__(self): return str(self.title) + ' from ' + str(self.author) -
How to create a function that change is_active=False to True?
How to create a function that change is_active=False to True? The case is that I want to create a function that change the value in an user case from "is_active=False" to "is_active=True". At my final point I want to create "an email verification" when someone registered. If someone registered on my website, he receive an email with the verification. I guess I have to create a function that change "is_active=false" on "is_active=true" when someone clicked the link that call the function? Mean I well? Thanks! def activateEmail(request, user, email, first_name): send_mail( #email subject f"Activate your user account, {user.first_name} !", #email content f"Hi {user.first_name}!\nPlease click on the link below to confirm your registration\n{SITE_URL}\nhttps://patronite.pl/wizard/autor/profil?step=3", #email host user EMAIL_HOST_USER, #email to [user.email], #if error True is better. fail_silently=False, ) The case is that I want to create a function that change the value in an user case from "is_active=False" to "is_active=True". At my final point I want to create "an email verification" when someone registered. If someone registered on my website, he receive an email with the verification. -
How to combine data from different functions in one function?
I have a django application. And I try to combine two dictionaries in one function? So that both dictionaries will render in the same template. So I have the views.py: def data_compare(): fruits = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 24, } condition = ["ananas"] context = {"fruits": fruits, "condition": condition} return context def data_compare2(): fruits2 = { "appel": 3962.00, "waspeen": 3304.07, "ananas": 30, } condition = ["ananas"] context = {"fruits2": fruits2, "condition": condition} return context def data_combined(request): context = data_compare(), data_compare2() return render(request, "main/data_compare.html", context) And template looks: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container center"> {% for key, value in fruits.items %} <span {% if key in condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br> {% endfor %} </div> <div class="container center"> {% for key, value in fruits2.items %} <span {% if key in condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br> {% endfor %} </div> </body> </html> {% endblock content %} But then I get this error: TypeError at /data_combined context must be a dict rather than tuple. Question: … -
saving date in a django model as the now date and adding 10 minutes on it
I'm working on a Django bids project. I want to allow each product to be bidden only for 10 minutes and want to make a countdown for only 10 minutes from submitting product data , so the idea came to my mind is to save the time at which the product added with adding 10 minutes on it but I don't know how to make this and I don't know whether this idea is right or not models.py: class bidproduct(models.Model): name = models.CharField(max_length=250) when = models.DateTimeField( auto_now_add=True) views.py: class bidDetailView(DetailView): model = bidproduct template_name = 'bidding/countdown.html' countdown.html: <div class='col-9'> <div id="event-box">{{object.when |date:'M d, Y H:m:s'}}</div> </div> javascript: const eventBox = document.querySelector('#event-box'); const countdownBox = document.querySelector('#countdown-box'); const eventDate =Date.parse(eventBox.textContent); setInterval(()=>{const now = new Date().getTime() const diff = eventDate - now; const d = Math.floor (eventDate / (1000 * 60 * 60 * 24) - (now / (1000 * 60 * 60 * 24))) const h = Math.floor ((eventDate / (1000 * 60 * 60) - (now / (1000 * 60 * 60 ))) %24) const m = Math.floor ((eventDate / (1000 * 60) - (now / (1000 * 60))) %60) const s = Math.floor ((eventDate / (1000) - (now / (1000))) … -
Django many to many not symmetrical parent implemntation. Reverse lookup is returning the childs, not parents
In models.py I have this model: class element (models.Model): element=models.Autofield(primary_key=true) parent_element=models.ManyToMayField('self',null=True,blank=True, related_name='parents',symmetrical=False) This relationship is implemented in database, by django, into a table with "from_element" (child, my element) and "to_element" (parents of my element) fields. The problems happens when I try to obtain the parents of a element with a reverse lookup,giving as result the elements that have my element as parent, the childs. Debugging the parents I see this: element.parents.source_field_name='to_element' element.parents.target_field_name='from_element' instead of element.parents.source_field_name='from_element' element.parents.target_field_name='to_element' Giving an example, if I create the element 1, and after I create the element 2 with element 1 as "parent" this is what I have: element.objects.get(element=1).parents.all() is 2 (his child, wrong) element.objects.get(parent=1) is 2 (his child, rigth) element.objects.get(element=2).parents.all() do not exist (wrong) element.objects.get(parent=2) do not exist (right) In database I have this: from_element is 2 and to_element is 1. But, as I said, parents.all() is looking from "to_element" to "from_element" Many to one and one to many are not the same, they have a direction. It is easy to define a one-to-many when you are using different models, define the foreign key into the "many" model and it's done, but not in 'self' case. Looking for information I always found "use a Foreign … -
Django check user.is_authenticated before UserCreationForm to prevent a user to signup twice
In Django, I am trying to prevent an already existing user to register (sign up) again. In my case, the user can sign up with a form. My approach is to check in views.py if the user already exists by checking is_authenticated upfront. If the user does not exist, then the form entries will be processed and the user will be created. The problem: if the user already exists, I would expect the condition request.user.is_authenticated to be True and the browser to be redirected to home. Instead, the evaluation goes on to process the form throwing (of course) the following error: Exception Value: duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=(john.doe) already exists. This is a sample of my views.py: def register_user(request): if request.method == "POST": if request.user.is_authenticated: messages.error(request, ('User already exists.')) return redirect('home') form = UserCreationForm(request.POST) if form.is_valid(): form.save() ... # do more stuff What am I missing? -
Most Efficient Way To Paginate Combined Queries From Multiple Models in Django Rest Framework
I am creating a social media website using DRF as my back-end. Recently, I noticed the "Home" feed getting too slow for comfort. I then realized that, even though I was using a a paginator, I am still serializing all "Feed Item" objects before paginating them. Take a look at the code below: # serialize reposts = RepostSerializer(reposts_query, many=True).data posts = SmallPostSerializer(feed_posts_query, many=True).data comments = FeedCommentSerializer(feed_comments_query, many=True).data #combine combined_posts_and_comments = list(chain(reposts, posts, comments)) # sort combined list by date feed_items = sorted( combined_posts_and_comments, key=lambda k: k["date"], reverse=True ) # paginate combined list paginator = Paginator(feed_items, self.page_size) How do I only fetch the necessary items for the selected page before serializing the feed items? I can not just slice the queries like [(page_size * page_num) - page_size:page_size * page_num], because after combining and paginating, it will create strange and inconsistent results when navigating to the next page. I also tried slicing like this: [:page_size * page_num]. However, as the page number increases, it gets slower and slower. I am sure somebody has ran into this problem before, how should I proceed? -
My CSS file won’t load. I try to search the internet but didn’t found a solution. can you assist me?
Hi for some reason my CSS file won’t load. I try to search the internet but didn’t found a solution. can you assist me ? My settings code I've tried every possible solution on the internet, but it's of no use. -
How to automatically start a python http server
I am using python http.server 80 to expose my downloaded files to my twilio whatsapp bot is there a way that as my django-twillio app starts it automatically runs the server on port 80 as well python -m http.server 80 -
DJANGO: Get ManyToMany objects through raw SQL query
Is it possible to get the many-to-many objects connected to a model through raw SQL? (using django.db.connection) Here are my simplified models: class Comment(models.Model): author = models.CharField(max_length=100) body = models.CharField(max_length=140) class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() comments = models.ManyToManyField(Comment) Here's the output when I query using SQL all posts: from django.db import connection cursor = connection.cursor() cursor.execute("SELECT * FROM home_post") all = cursor.fetchall() print(all) # output: [(1, 'First Post', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed.')] The comments many-to-many objects aren't returned. Any help? -
character "@" in the name of a variable in the django template
I have a dictionary in my views.py mydata = {'@model': 'wolfen', '@genre': 'fantastic', 'price: '350'} which I pass to the django view in a context like this context['mydata'] = mydata and in my view i display like this {{mydata.@model}} the problem is that the django template uses the "@" character for other tags. How to replace the "@" character to not display the following error Could not parse the remainder: '@model' from 'mydata.@model' thank you -
Dynamically generate for loops to create lists from a dictionary
variations = { 'size':{'small':'Small', 'medium':'Medium', 'large':'Large'}, 'quantity':{'20l':'20l', '10l':'10l', '5l':'5l'}, 'color':{'red':'Red', 'blue':'Blue', 'green':'Green'} } var_list = [[i,j,k] for i in variations['color'] for j in variations['size'] for k in variations['quantity']] You can also write the above code as: var_list = [] for i in variations['color']: for j in variations['size']: for k in variations['quantity']: comb = [] comb.append(i) comb.append(j) comb.append(k) Var_list.append(comb) Both the var_list will output: [['red', 'small', '20l'], ['red', 'small', '10l'], ['red', 'small', '5l'], ['red', 'medium', '20l'], ['red', 'medium', '10l'], ['red', 'medium', '5l'], ['red', 'large', '20l'], ['red', 'large', '10l'], ['red', 'large', '5l'], ['blue', 'small', '20l'], ['blue', 'small', '10l'], ['blue', 'small', '5l'], ['blue', 'medium', '20l'], ['blue', 'medium', '10l'], ['blue', 'medium', '5l'], ['blue', 'large', '20l'], ['blue', 'large', '10l'], ['blue', 'large', '5l'], ['green', 'small', '20l'], ['green', 'small', '10l'], ['green', 'small', '5l'], ['green', 'medium', '20l'], ['green', 'medium', '10l'], ['green', 'medium', '5l'], ['green', 'large', '20l'], ['green', 'large', '10l'], ['green', 'large', '5l']] var_list contains 3 for loops based on the 3 dictionaries in variations. How can we dynamically write the above code so that if more or less dictionaries are present in variations the for loops in var_list can also get adjusted? e.g if 'brand' is also present in variations, a for loop for this 'brand' should be … -
how to know which app is running in background and save all spendig time of that?
I want to know can I increase my time counter when specific app is running in background of operating system and save spending time in db? is it posiible to solve this problem with django? e.g:I want to open photoshop with an icon in my website(in user`s computer) then I track what time they spend in that app. I think I need a script on users computer to send me feedback of processes or an desktop app to track the processes. -
How to send POST request using Julia lang HTTP library to a Django RESTFUL API (DRF)
There is very limited documentation when it comes to the HTTP library in Julia Lang. Not just that, but there are no up to date Stack Overflow questions regarding the HTTP library in general. With that said, how do you send POST requests using Julia + HTTP to a Django Restful API (DRF)? -
Create and edit form with multiple Django files
could someone tell me how to save multiple files in the post method of my form, I can only save 1 file, not the ones I have tried to upload. Files = models.FileField(upload_to="alumno/archivos/%Y/%m/%d", null=True, blank=True, verbose_name='Archivos') That's what the field is called in my model Student. Then in my post method in the view I have the following code, but it doesn't save everything, as I said it only saves 1 file. def post(self, request, *args, **kwargs): data = {} files = request.FILES.getlist('Files') try: action = request.POST['action'] if action == 'edit': form = self.get_form() for f in files: Alumno.objects.update(Files=f) data = form.save() else: data['error'] = 'No ha ingresado a ninguna opción' except Exception as e: data['error'] = str(e) return JsonResponse(data) In this case as it says update in Alumno.objects because I am doing the edit, I have the same problem as with the create. Please could someone help me? Regards I want to be able to save or edit two or more files in the Pupil model. -
Django and ajax - data returning value but not populating field
I am new to Django and Ajax. I have a dropdown that is populated from a database. I want another field to populate based on the selection made in the dropdown. I am getting the return value, but it is not populating the form field. Console.log shows the value being returned. It just never shows on the form field and I am sure the field name is correct. In the browser I get 600. How do I get the 600 into the #id_Deductable field? Any help would be greatly appreciated. ` <script> $("#id_Primary_Plan").change(function () { var url = $("#BaseQuoteForm").attr("data-agent-url"); // get the url of the `load_cities` view var PlanData = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'PlanData_id': PlanData // add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function console.log(data); $("#id_Deductable").text(data); // replace the contents of the city input with the data that came from the server } }); }); </script> ` -
Django many to many not symmetrical parent implementation. Reverse lookup is returning the child, not parents
Hi, In models.py I have this model: class element (models.Model): element=models.Autofield(primary-key=true) parent_element=models.ManyToMayField('self',null=True,blank=True, related_name='parents',symmetrical=False) This relationship is implemented in database, by django, into a table with "from_element" (child, my element) and "to_element" (parents of my element) fields. The problems happens when I try to obtain the parents of a element with a reverse lookup,giving as result the elements that have my element as parent, the childs. Debugging the parents I see this: element.parents.source_field_name='to_element' element.parents.target_field_name='from_element' instead of element.parents.source_field_name='from_element' element.parents.target_field_name='to_element' Giving an example, if I create the element 1, and after I create the element 2 with element 1 as "parent" this is what I have: element.objects.get(element=1).parents.all() is 2 (his child, wrong) element.objects.get(parent=1) is 2 (his child, rigth) element.objects.get(element=2).parents.all() do not exist (wrong) element.objects.get(parent=2) do not exist (right) In database I have this: from_element is 2 and to_element is 1. But, as I said, parents.all() is looking from "to_element" to "from_element" Many to one and one to many are not the same, they have a direction. It is easy to define a one-to-many when you are using different models, define the foreign key into the "many" model and it's done, but not in 'self' case. Looking for information I always found "use a …