Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-plotly-dash how to integrate 3 different dash files
Earlier was using dash server with a base.py which runs dash app server to run the files which was combined using dashboard.py which renders data from files A and B which has data and responsive UI. Now trying to move it to django using django-plotly-dash. Could someone help one this. File Structure: base.py - dash app server dashboard.py - from base imports app, from a imports a_tab (which contains a dataframe) from b imports b_tab (which contains a dataframe) runs server both a.py and b.py --- from base imports app Have setup everything with django-plotly-dash but the data is not populating by clicking UI. -
Python - overlap time period business hours [closed]
I try to find the best way to solve this problem: I'am coding a scheduler for machine job. I will have a postgres table with all day of a year. Every row has different columns with start and ends of shift work. For example: day 17/01/21 - start_time_work1 00:00 - end_time_work1 20:00 - start_time_close1 20:00 - end_time_close1 00:00 day 18/01/21 - start_time_work1 00:00 - end_time_work1 04:00 - start_time_close1 04:00 - end_time_close1 06:00 - start_time_work2 06:00 - end_time_work2 12:00 - start_time_close2 12:00 - end_time_clos22 00:00 There may usually be several shifts on the same day. The purpose is to create a function that allows me, by entering a work start date and a work duration, to know, considering only the work periods, when this work will end. For my example: 17/01/21 18/01/21 Work Closed Work Closed Work Closed |----------------------------|----------|----------|---------|----------|---------------| 00:00 20:00 00:00 04:00 06:00 12:00 00:00 Input: |--------------------------------| 01:00 (22hous) 23:00 Output |-------------------------------------------| 01:00 (26hous) 03:00 Input: |---------------------------------------| 01:00 (24hous) 01:00 Output |-------------------------------------------------------------| 01:00 (30hous) 07:00 -
Python categories not updating?
I am currently making a blog but I recently added a dropdown menu for my website. From that point onwards when I add a new category it does not update. Instead it says this page does not exist when it should have. add_category.html file {% extends 'base.html' %} {% block title %}Create a New Blog Category!{% endblock %} {% block content %} {% if user.is_authenticated %} <h1>Add Category</h1> <br/><br/> <div class="form-group"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary">Add Category</button> </div> {% else %} You are not allowed here! (and you know it...) {% endif %} {% endblock %} categories.html file {% extends 'base.html' %} {% block content %} {% if category_posts %} <h1>{{ cats }}</h1> <ul> {% for post in category_posts %} <li><a href="{% url 'article-detail' post.pk %}">{{post.title}}</a> - {{post.author.first_name}} {{post.author.last_name}} - {{ post.post_date }} <small> {% if user.is_authenticated %} - <a href="{% url 'update_post' post.pk %}">(Edit)</a> <a href="{% url 'delete_post' post.pk %}">(Delete)</a> {% endif %} </small><br/> {{post.body|slice:":200"| safe }}</li> {% endfor %} </ul> {% else %} <h2>Sorry this page does not exist...</h2> {% endif %} {% endblock %} urls.py file from django.urls import path #from . import views from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, … -
How to make complex searches in django ? Use views or models?
I want to create a Job search page on my Django Application. I'm now wondering what the best practice is on how to develop this. Would it be better to do al the filtering in my views? Or should I do all the filtering in the models? -
FileNotFoundError with matplotlib and apscheduler
My goal is to download data from a website, plot a graph, save it, and display it on a webpage. I am using Django 3.2, Python 3.9.5, pandas and matplotlib. When I just had the below code in my views, everything worked and the graph displayed correctly: r = requests.get(url_lab) #url_lab defined elsewhere, not relevant z = zipfile.ZipFile(io.BytesIO(r.content)) if file_lab in z.namelist(): #file_lab defined elsewhere, not relevant df_lab = pd.read_csv(z.open(file_lab), dtype={'a': str, 'b': str, 'c': float}, usecols=col_list, parse_dates=['Period'], \ encoding = "ISO-8859-1", engine='python') df_lab.set_index('Period', inplace=True, drop=True) df_lab = df_lab.sort_index().loc['2015-03-03':] x = df_lab.index[df_lab.Series_reference == "HLFQ.S1A1S"] y = df_lab.Data_value[df_lab.Series_reference == "HLFQ.S1A1S"] fig = plt.plot(x, y) plt.savefig('static/images/lab-empl-lev.png') However, I don't want this code to run every time I run the server, and in fact it's important that the data gets updated at a specific time every day. So I need to use some kind of task scheduler, and decided on apscheduler. So, following a tutorial, I made a new folder, containing an empty __init__.py, fetch.py with the previous code in it and updater.py: fetch.py: def get_lab_data(): r = requests.get(url_lab) z = zipfile.ZipFile(io.BytesIO(r.content)) if file_lab in z.namelist(): df_lab = pd.read_csv(z.open(file_lab), dtype={'a': str, 'b': str, 'c': float}, usecols=col_list, parse_dates=['Period'], \ encoding = "ISO-8859-1", engine='python') df_lab.set_index('Period', … -
how to make a field which gets shown if another field reached a specific value in django
So lets say in django models, we have a ForeignKey model named info_type, the user In django admin can select height or weight, Now, my question is what can we do so when info_type == weight a field get shown named weight and when the info_type is equivalent to height, a field gets shown named height I found no clue for doing such thing, how can I make that possible? -
Django Ajax request seems to be calling incorrect view
I am trying to set up the inventory section of my page, I have created a new view definition that handles updating the database with the value set by the user. However I keep getting errors from the main page view. I believe I'm only call the updateInventory view def. Error: Internal Server Error: /magic/sets/update-inventory/ Traceback (most recent call last): File "...\card_crate_admin_venv_v2\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "...\card_crate_admin_venv_v2\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "...\card_crate_admin_venv_v2\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "...\website\magic\views.py", line 33, in setsIndividualPage setName = Set.objects.filter(code=setCode.upper()).values_list('name', flat=True).get() File "...\card_crate_admin_venv_v2\lib\site-packages\django\db\models\query.py", line 437, in get self.model._meta.object_name magic.models.Set.DoesNotExist: Set matching query does not exist. urls.py path('sets/<str:setCode>/', setsIndividualPage), path('sets/<str:setCode>/sets-individual-data/', SetsIndividualData.as_view(), name='sets-individual-data'), path('sets/update-inventory/', updateInventory, name='updateInventory'), view.py # ====================== # Sets Individual Page # ====================== @login_required() def setsIndividualPage(request, setCode): setName = Set.objects.filter(code=setCode.upper()).values_list('name', flat=True).get() return render(request, "magic/sets-individual.html", {'setCode': setCode, 'setName': setName}) def updateInventory(request): current_user = request.user if request.POST['card_type'] == 'standard': Inventory.objects.update_or_create( user_id = current_user.id, card_id = request.POST['id'], defaults = { 'standard': request.POST['value'] } ) elif request.POST['card_type'] == 'foil': Inventory.objects.update_or_create( user_id=current_user.id, card_id=request.POST['id'], defaults={ 'foil': request.POST['value'] } ) javascript.js function updateCard(e) { if (e.getAttribute('type') == 'number'){ if (e.value < 0) e.value = 0; if (e.value > … -
Why is my user manager not creating superuser?
So I tried to make a superuser in my terminal with createsuperuser and it created a user successfully only that it wasn't a superuser because when I tried to login it gave me this error but when I tried to create another superuser with the same email it tells me the email is already taken Account.models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models class AccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("user must have an email") cemail = self.normalize_email(email) user = self.model(email=cemail, username=username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): if not email: raise ValueError('user must have an email') user = self.create_user(email, username, password) user.is_admin = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) username = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = AccountManager() def __str__(self): return self.email @property def is_staff(self): return self.is_admin @property def is_superuser(self): return self.is_admin -
Django: unable to save a value in models
I am currently working on a CS50 Web development SQL, Models, and Migrations and following what the tutorial says to do , yet I found that I am not able to duplicate the result at some points. I have created a new class in models.py named Airport. class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" When I try to use the f = Airport(code="NY", city="New York") f.save() function to save it, the following error occurs django.db.utils.OperationalError: no such table: flights_airport I have checked some solutions from the internet, the first one is to do the migration again. Yet, when I do python manage.py makemigrations it says No changes detected when I do python manage.py migrate, it shows a long error message with django.db.utils.IntegrityError: The row in table 'flights_flight' with primary key '1' has an invalid foreign key: flights_flight.origin_id contains a value 'new york' that does not have a corresponding value in flights_airport.id I have also tried to delete all the data with Airport.objects.all().delete() It again shows the following error code django.db.utils.OperationalError: no such table: flights_airport I am stuck in a point that I cant do migration nor can I start it again. I'd like to … -
What does kwargs={'pk': self.pk} do in get_absolute_url method?
I've finished a Django tutorial a few days ago and I've started to recap the functionalities in my application. In my models.py I've stumbled upon a method and the kwargs thing it's not that clearly to me. What is the logic behind this, can you explain to me what it does? Thank you. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Creation(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='creation_posts') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail', kwargs={'pk': self.pk}) def total_likes(self): return self.likes.count() What does kwargs={'pk':self.pk}) do exactly? Thank you -
Page Not Found after adding user in Group ( While Redirecting )
I am building a Simple Group App in which users can ask admin for permission for join. First they have to send a join request to join the Group then a admin will accept it. BUT when user is clicking on join_the_accept then user is successfully adding BUT after click on join_the_accept then it is keep showing Page Not Found (404) models.py class Group(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.ForeignKey(max_length=30,default='') members = models.ManyToManyField(User,related_name='group_member',blank=True) class GroupRequest(models.Model): group = models.ForeignKey(Group,on_delete=models.CASCADE) request_sender = models.ForeignKey(User, on_delete=models.CASCADE) views.py def accept_it(request,pk): group_request = get_object_or_404(GroupRequest, pk=pk) group_request.group.members.add(group_request.request_sender) group_request.members.add(sent_request.request_sender) return redirect('DetailGroup',pk=pk) #Redirecting Here def DetailGroup(request,pk): data = Group.objects.get(pk=pk) request_message = data.groupjoinrequest_set.order_by('-date_sent').exclude(request_sender=request.user) context = {'data':data} return render(request,'Group_detail.html', context) Group_detail.html {% for requests in group_requests %} {{ requests.request_sender }}<a href="{% url 'accept_it' requests.id %}">Accept it</a> {% endfor %} What i have tried :- I have also tried by putting group_id instead of pk like this :- ('DetailGroup',pk=group_id) BUT it is showing the same error. I have also renamed the instances in url but still showing the error. User is saving fine BUT it is not redirecting in the Group. I have no idea what is wrong with it, Any help would be Appreciated. Thank You in Advance. -
django session key during session
I am looking for the session key that should be the same from the time when the user logs in until he logs out. I am communicating with another api that requires such key. I tried using csrf token but this one is different per request. Also, I have tried using session storage and again it is different one. I see that in the django_sessions there is a session_key that is created during the login, but I dont know how to assosiate it with a user, it has only session_key, session_data and the expire date. def user_login(request): if request.method == 'POST': response = None form = LoginForm() username = request.POST.get("username") password = request.POST.get("password") cookie = request.COOKIES['csrftoken'] user = authenticate(username=username, password=password) # logger.info(f"Session key [Login] --> {request.session}") # logger.info(f"Session key [Login] --> {request.session.session_key}") # request.session.create() # logger.info(f"Session key [Login] --> {request.session.session_key}") if user is not None: logger.info(f"Cookie [Login] --> {cookie}") response = loginApi( username, password, 'demo', cookie) if response["status"] == 200: login(request, user) logger.info("User logged in") return redirect('home') else: logger.info(f"Request Response [Log in] --> {response}") else: logger.error(f"User failed [Log in] --> {response.text}") else: form = LoginForm() return render(request, 'users/login.html', {'form': form}) -
How can I properly send images (and text) from React to Django API using fetch?
My django API views is setup as follows; class AddProductToStorageAPIView(APIView): parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) #I want to know what data is coming in for now return Response({"details": "all done successfully"}, status=200) When I make a POST request from postman (with formdata), the data request.data returns: <QueryDict: {'title': ['Something'], 'description': ['some description'], 'price': ['600'], 'category': ['A'], 'Images': [<InMemoryUploadedFile: img-transparent_bg.jpg (image/jpeg)>]}> However, when I try to make a POST request from the react side. Things got so messed up. First here is my code in react side: const handleSubmit = (e) =>{ e.preventDefault(); var headers = new Headers(); headers.append("Content-Type", "multipart/form-data"); headers.append("X-CSRFToken", csrftoken) var formdata = new FormData(); formdata.append("title", state.title); formdata.append("description", state.description); formdata.append("price", state.price); formdata.append("category", state.category); for (var i = fileinput.current.files.length - 1; i >= 0; i--) { formdata.append("Images", fileinput.current.files[0], fileinput.current.files[0].name); }//because the file input has 'multiple'='true' (i.e multiple files can be added) var requestOptions = { method: 'POST', headers: headers, body: formdata, redirect: 'follow' }; fetch("http://127.0.0.1:8000/api/v1/plus/product/", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); } On submit however, I get 400 bad request error saying multipart form parse error - invalid boundary in multipart:None and I don't have a clue what that means. Then, … -
INVALID_PATCH_PATH error while using patch/updating the interval unit in PayPal plan update API
I used the details in body as [ { "op": "replace", "path": "/billing_cycles/frequency/interval_unit", "value": "MONTH" } ] I get the output as follows { "name": "INVALID_REQUEST", "message": "Request is not well-formed, syntactically incorrect, or violates schema.", "debug_id": "7e77554e0bd6d", "details": [ { "field": "/0/path", "value": "/billing_cycles/frequency/interval_unit", "location": "body", "issue": "INVALID_PATCH_PATH", "description": "The specified field cannot be patched." } ], "links": [ { "href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#INVALID_REQUEST", "rel": "information_link", "method": "GET" } ] } what is the correct body data to pass to update the interval_unit of the PayPal plan data. -
Django - Adding model without default ModelAdmin permissions (add, change, delete, view)
I am facing problems with adding simply new permission to admin panel In my models.py i have: class search_hostname(models.Model): class Meta: permissions = [("search_hostname", "Can search hostname")] def __str__(self): return self.application but after makemigrations and migrate in my admin page i get "Can search hostname" and other four default: app | search_hostname | Can add search_hostname app | search_hostname | Can change search_hostname app | search_hostname | Can delete search_hostname app | search_hostname | Can view search_hostname app | search_hostname | Can search hostname i have no old migrations which would cause this is there any way to avoud adding those default permissions and have only Can search hostname in DB -
How to add CheckConstraint between related models
I want to add CheckConstraint which concerned different related models. Users are attached in a particular site (research team/institute) for a given study/project. A user can only be attached to one site for a given study. Sites can be involved or not in differents studies/projects. I want to add a constraint that prevent User to be attached to a study and a site id this site is not involved in this study. Below database model -
How to sent password reset mail from another view?
I have a view to create a restaurant. In the same view a user is also being created. After the user creation, I have to sent a mail to the user with the link to reset the password. My view looks like: def create_restaurant(request): form = RestaurantForm() user_form = RestaurantUserForm() if request.method == 'POST': form = RestaurantForm(request.POST, request.FILES) user_form = RestaurantUserForm(request.POST) if form.is_valid() and user_form.is_valid(): #----user is saved here------ user_obj = user_form.save() #----have to sent the mail here------ #-----restaurant is saved here----- restaurant_obj = form.save() restaurant_obj.user = User.objects.get(id=user_obj.id) restaurant_obj.save() messages.success(request, 'Restaurant Added Successfully.') return redirect('create_restaurant') context = { "title": "Add restaurant", "form": form, "user_form": user_form } return render(request, "restaurant/restaurant.html", context) I have implemented the password reset procedure using urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name='password_reset' ), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name='password_reset_done' ), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name='password_reset_confirm' ), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name='password_reset_complete' )] How can I sent the email as mentioned above? -
Unable to delete a user in django's built in auth app
When I try to delete a user from Django's built in auth app, I have this error: django.db.utils.OperationalError: no such table: main.auth_user__old I searched on the web and I found this question : Django - No such table: main.auth_user__old So I updated Django and I am now using the version 3.2.4 (I am using sqlite). Then I tried to delete auth tables from the db but when I did a ptyhon manage.py makemigrations auth, it told me that no changes were detected. Also, I can't delete the whole database. Does someone have an idea what I can do to fix this? -
Display Hierarchical Tree (Parent & Child) From Django Self Reference Model
I am trying to generate a nested/hierarchical structure (categories & sub-categories) that will appear on the Django Admin side. This is my current model for the Category. class Category(models.Model): name = models.CharField(blank=False, max_length=200) slug = models.SlugField(null=False) parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.SET_NULL) class Meta: db_table = "dj_categories" # Add verbose name verbose_name = 'Category' verbose_name_plural = "Categories" unique_together = ('slug', 'parent',) def get_categories(self): if self.parent is None: return self.name else: return self.parent.get_categories() + ' -> ' + self.name def __str__(self): return self.get_categories() This is how my category table looks like.Category table The above code generate the structure like this in the Django admin panel. Category Layout Instead I want to achieve the following structure: Electronics - Mobile - Digital Cameras Fashion - Men Footwear -- Casual Home Appliances - Washing Machine - Air Conditioner -- Windows -- Split Note: I don't want to leverage any third party package such as: Django MPTT or Django Treebeard A complete example to the problem is highly appreciated. -
Updating an existing Serializer class partially for transactional data in mongodb
I have setup the following model for my transactions data from several invoices and I want to be able to update them on API call in case the same invoice's data is passed again. My model is as follows: class GSTTransactions(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) gstin = models.ForeignKey(GSTMaster, on_delete=models.CASCADE, to_field='gstin') transactionType = models.TextField() gstNumber = models.TextField() invoiceDate = models.DateField() invoiceNumber = models.TextField() totalTransactionValue = models.TextField() CGSTAmount = models.TextField() SGSTAmount = models.TextField() IGSTAmount = models.TextField() CSAmount = models.TextField() rate = models.TextField() transactionValue = models.TextField() month = models.TextField() year = models.TextField() dataType = models.TextField() class Meta: db_table = 'gst_transactions' unique_together = (('gstin','gstNumber','invoiceDate','invoiceNumber'),) enter code here My serializer class looks like this: class GSTTransactionsSerializer(serializers.ModelSerializer): class Meta: model = GSTTransactions fields = ['gstin','transactionType','gstNumber','invoiceDate','invoiceNumber','totalTransactionValue','CGSTAmount','SGSTAmount','IGSTAmount','CSAmount','rate','transactionValue','month','year','dataType'] My function for adding/updating data looks like this: def gstTransactionsSave(context): gstin = context['analysisResult']['gstin'] salesData = context['analysisResult']['salesData'] for sales in salesData: try: sales['gstin'] = gstin sales['dataType'] = 'sales' sales['invoiceDate'] = str(sales['invoiceDate']) snippet = GSTTransactions.objects.get(gstin=gstin,gstNumber=sales['gstNumber'],invoiceDate=sales['invoiceDate'],invoiceNumber=sales['invoiceNumber']) serializer = GSTTransactionsSerializer(snippet) sale = serializer.data sale['totalTransactionValue'] = float(sale['totalTransactionValue']) sale['CGSTAmount'] = float(sale['CGSTAmount']) sale['SGSTAmount'] = float(sale['SGSTAmount']) sale['IGSTAmount'] = float(sale['IGSTAmount']) sale['CSAmount'] = int(sale['CSAmount']) sale['rate'] = int(sale['rate']) sale['transactionValue'] = float(sale['transactionValue']) sale['year'] = int(sale['year']) for key in list(sales.keys()): if sales[key] == sale[key]: pass else: print(key) print('Overwriting in progress') newSerializer = … -
Why is_valid returns None when I use PasswordChangeForm? I'm perfectly sure that the credentials I entered are correct
When I try to submit the form, it throws a ValueError. Below is my code. def passchange(request): if request.user.is_authenticated: if request.method == "POST": print(request.POST) fm = PasswordChangeForm(user=request.user, data=request.POST) print(fm) if fm.is_valid(): fm.save() update_session_auth_hash(request, fm.user) messages.success(request, 'Password Changed Successfully') if fm.user.location=="Latur": return HttpResponseRedirect('/laturhome/') elif fm.user.location=="Nashik": return HttpResponseRedirect('/nashikhome/') elif fm.user.location=="Dhule": return HttpResponseRedirect('/dhulehome/') elif fm.user.location=="Akola": return HttpResponseRedirect('/akolahome/') elif fm.user.location=="Solapur": return HttpResponseRedirect('/solapurhome/') else: print(fm.error_messages) return HttpResponse('Not valid') else: fm = PasswordChangeForm(user=request.user) return render(request, 'account/passchange.html', {'form':fm}) else: return HttpResponseRedirect('/login/') The fm.error_messages part in the else part of is_valid shows me the following in the terminal: {'password_mismatch': 'The two password fields didn’t match.', 'password_incorrect': 'Your old password was entered incorrectly. Please enter it again.'} Where did I go wrong? -
Anchor href doesn't work when i add dynamically hr tag after user clicjk
<div class="nav-center"> <ul class="center"> <a class="nav-item" href=""> <li>Random facts</li> <hr class="line"> </a> <a class="nav-item" href="/blog/technology/"> <li>Technology</li> </a> <a class="nav-item" href="/blog/sport/"> <li>Sports</li> </a> <a class="nav-item" href=""> <li>About poeters</li> </a> </ul> </div> //JavaScript Code let navItems = document.querySelectorAll(".nav-item"); let addchild = document.createElement("hr"); addchild.classList.add("line"); let Handler = (e) => { e.preventDefault(); navItems.forEach((node) => { if (node.contains(removechild)){ node.removeChild(removechild); } }); e.currentTarget.appendChild(addchild); }; navItems.forEach((node) => { node.addEventListener("click", Handler); }); See the first anchor tag i added hr tag through html it is showing line below Random Facts and also works fine for my expected link.. But when i add dynamically after user click, line shows but anchor link does not work after user click why?? -
Django REST framework One-to-many relationship and database queries
I am new to django and I am developing my first project with Django REST framework. Models: class Sticker(Model): image = models.ImageField(upload_to=sticker_image_directory_path, null=False) title = models.CharField(max_length=150) def __str__(self): return self.title class StickerTag(Model): name = models.CharField(max_length=100) sticker = models.ForeignKey(Sticker, on_delete=models.RESTRICT, related_name='tags') def __str__(self): return self.name Serializer: class StickerSerializer(serializers.ModelSerializer): tags = serializers.StringRelatedField(many=True) class Meta: model = models.Sticker fields = ['id', 'image', 'title', 'tags', 'countries'] View: class StickerView(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = serializers.StickerSerializer queryset = models.Sticker.objects.all() I was debugging call to http://127.0.0.1:8000/stickers/ with django-debug-toolbar. I was surprised to see that for each sticker instance Django makes a query to stickertag table like that: SELECT `stickerapp_stickertag`.`id`, `stickerapp_stickertag`.`name`, `stickerapp_stickertag`.`sticker_id` FROM `stickerapp_stickertag` WHERE `stickerapp_stickertag`.`sticker_id` = 1 Means it is grabbing sticker tags for each sticker one by one. So if there are 10 stickers it will make 10 DB calls with that above query. But I think that those are too many queries and can be reduced by using "IN" clause of MYSQL for example: SELECT * FROM stickerapp_stickertag where sticker_id in (1,2,3,4,5); I don't know how to do that in Django REST framework. Kindly guide! -
Django ORM: recursive query with select_related and prefetch_related
Consider having a family tree, Grandpa, Father and Son models. Facing 2 problems fetching the tree.. First: if we need to fetch all family member we would use recursion for that. psudo code: * get person * if person has a childPerson * execute first step Second: if we want to breakdown the results by filtering psudo code: * get person 'Grandpa' (and filter results for grandpa if filter applied) * if person has a childPerson (father) * execute first step (with filter result 'Father' if filter applied) //filter changes here and changes again with 'Son' How To apply this approach with Django ORM and Models? because I'm searching for days I found this link might help to figure out solution (the closest to my approach), but need expert support to make code works for the approach. -
How to solve NoReverseMatch at / (Error during template rendering) in django 3.2?
Here is the screenshots of error i am getting. and App Name is greeting_app Now greeting_app/urls.py has the following code from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('about/<int:id>/', views.about, name="about"), ] greeting_app/views.py has the following code from django.shortcuts import render, HttpResponse from .models import basicinformation # Create your views here. def home(request): information = basicinformation.objects.all() return render(request, 'index.html', {"info":information}) def about(request, id): data = basicinformation.objects.get(id=id) return render(request, 'about.html', {"data":data}) templates/index.html has the following code. I have included only the url part in index.html file. <a href="{% url "about" data.id %}">Description</a>