Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF + SimpleJWT
We use DRF + SimpleJWT and we're finding that when our servers get overloaded or timed out, we're passing a 401 on the token refresh endpoint and causing users to be thrown back to the login screen (because a 401 indicates that the user is no longer authorized to view anything). Does anyone know why this might be? It only happens under really bad network conditions – we've ruled out the client and do believe it's the server returning a 401 somewhere now. When the user kills the app after being thrown back home, they are authenticated on next launch again, so it seems like we're issuing a 401 on timeout or something like that. -
How to temporatily store many user inputs somewhere in the backend within 60s?
I've been searching for solutions to this problem for weeks. My underlying struggle is that I am having trouble storing user inputs temporarily (like 60 seconds for a game. It's not like storing user IDs for each account in the backend). I want to develop a website game where it takes user input(one word as input) and counts how many words a user can give in 60 seconds. This requires the website to go back to the same website after submitting the input (but recorded each user input in the backend and count on it). I guess that I should use session in django but I'm still not sure about how should I approach this problem. -
How to Aggregate By with django-tables2 and keep linkify?
With django-tables2, I found I can either have an aggregate by querying model.objects.values('foo_bar').annotate(...) but only the values themselves are passed. If I try to linkify a column, I get an error that for linkify=True, 'FOOCOLUMN' must have a method get_absolute_url. If I pass model.objects.all(), I can linkify columns, however, it seems that you cannot aggregate. Is there a way to aggregate/annotate in django-tables2 while keeping linkify? -
Serving Vue.js static files and Django app running on gunicorn over Nginx
I have a web backend implemented in Django and running on Gunicorn. Plus, I also have a Vue.js app that uses this backend. I want to run both of them on nginx and also do HTTPS configs. This is how my "/etc/nginx/nginx.conf" file looks like: ... server { server_name .website.com; listen 80; return 307 https://$host$request_uri; } server { location / { proxy_set_header Host $host; proxy_pass http://localhost:8080; # where the Django app over gunicorn is running } location /static { root /code/frontend/dist/; # static frontend code created with vite on vue.js autoindex on; index index.html; try_files $uri $uri/ /index.html; } # ssl configs listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/website.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/website.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } Both of them, Django and Vue.js part, are hosted in a single Docker container. 80 and 8080 ports of this container is mapped to 80 and 8080 ports of the host PC. 443, 8080 and 80 ports are open on the machine for inbound connections. Sending a post request to http://website.com:8080/bla do returns correct values, meaning that backend seems to be working but on http only … -
How do i make a list from Django queryset and format the annotate field?
I'm trying to make my django query json serializable queryset= list(Products.objects.filter(status=True, salelog__created__range=(start,today)).values("name").annotate(individual_sales=Count("salelog__quantity")).annotate(combined_quantity=Sum("salelog__quantity"))) so i return json_response(queryset) and i get the following for combined_quantity: null but when i print(queryset) in terminal i get the following: [{'name': 'STEAK', 'individual_sales': 21, 'total_quantity': Decimal('300.00')}, {'name': 'RIBEYE', 'individual_sales': 18, 'total_quantity': Decimal('500.00')}, {'name': 'T-BONE', 'individual_sales': 8, 'total_quantity': Decimal('450.00')}] i guess the Decimal(xxx) doesnt play well with my front end. how do i fix this? btw im using vue and django and pretty new at this -
Is there a known way to pass variables from django views to a js scipt on a template? I am building a chart, and need to display information
So, I would want to pass a variable into NEED_VARIABLE_PASSED. This code is in one of my html templates. I understand I can't use {{variable}}, so is there a way? <script type="text/javascript"> function drawChart() { var data = google.visualization.arrayToDataTable([ ["Element", "Density", { role: "style" }], ["WLWS", NEED_VARIABLE_PASSED, "#696969"], ["Upperbin", NEED_VARIABLE_PASSED, "#696969"], ["Solenoid", NEED_VARIABLE_PASSED, "#696969"], ["BrakeSW", NEED_VARIABLE_PASSED, "color: #696969"] ]); </script> -
How to Pass Back Slug to Render_Foo In Django?
How do I pass a slug back through a render_foo with django-tables2? models.py class Library(models.Model): name = models.CharField(max_length=128) library_slug = models.SlugField(unique=True) class Author(models.Model): library = models.ForeignKey(Library) author_slug models.Slugfield(unqiue=True) class Book(models.Model): author = models.ForeignKey(Author) book_slug = models.SlugField(unique=True) views.py def LibraryTableView(request): queryset = books.objects.values('author','book').annotate(book_count=Count('book')) table = LibraryTable(queryset) def AuthorTableView(request, author_slug): queryset = books.objects.filter(book__author__author_slug=author_slug) table = AuthorTable(queryset) tables.py class LibraryTable(tables.Table): class Meta: model = Book fields = ('author', 'book_count') def render_book_count(self, value, author_slug): return format_html('<a href="{}">{}</a>', author_slug, value) Library Table | Author| Book Count | |--------|------------| | JK Rowling | 6 | | Brandon Sanderson| 12 | | Herman Melville | 5 | When clicking on author Herman Melville, it will drill down to his books Title Genre Typee Non-Fict Omoo Fict Redburn Fict Moby-Dick Fict Timoleon Poetry Note: If I try author = tables.Column(linkify=True), I get the error for linkify=True, Herman Mellville must have a method get_absolute_url -
How to get related model_set on querying with filter
Let's say I have 2 models class Shipment(models.Model): # ... class ShipmentTimeline(models.Model): shipment = models.ForeignKey( Shipment, on_delete=models.CASCADE,) I want to get related ShipmentTimeline objects along with the Shipment filtered list in one go. For Now, I'm querying the shipments like: Shipment.objects.filter( # some filters ).only('id') As here I have IDs and then if I go with get() query first and then related_set of each shipment and then appending to a new list. it would be a lot of mess I guess in the for loops. Any better way to get the data like qs = [{'Shipment 1', ['ShipmentTimeline_x', 'ShipmentTimeline_y']}, ...] -
How to change ForeignKey to Many-to-Many without any conflicts
_Hi, everyone! I want to change from ForeignKey to Many-to-Many, but I afraid to break my database. This is my class which I want to change: class Ninja(models.Model): id_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="ninja", blank=True, null=True) id_team = models.ForeignKey("mission.Team", null=True, blank=True, on_delete=models.SET_NULL) With this piece of code each user can entry only one team. But I want each user could be in different teams. So, I think I need many-to-many. Hope, I'm right. The question is: 'If I change my model field like this: id_team = models.ManyToManyField("mission.Team", null=True, blank=True, on_delete=models.SET_NULL) will I broke my database with actual data? I have a very negative experience with droping database twice in past. :( -
How to select the individual id of an HTML element that is within a for loop in a Django template?
I am trying to select an HTML button that is within a for loop in a Django template using a querySelector to add an event listener to it in JavaScript. How do you create a unique id for the button and select it through JavaScript? Right now, I have one id set to the button within the for loop, and when you press the button, nothing happens. html % for post in page_obj.object_list %} <div class = "individual_posts"> <a href="{% url 'username' post.user %}"><h5 class = "post_user">{{ post.user }}</h5></a> <h6 id = "post_itself">{{ post.post }}</h6> {% if post.user == request.user %} <button id="editButton" class="edit_button">Edit</button> {% endif %} </div> {% endfor %} JavaScript document.addEventListener('DOMContentLoaded', function(){ document.querySelector('#editButton').onclick = edit_email(); }) -
Django Lower both sides of a string filter operator
I have a queryset that I'm trying to apply a filter to, like so: filter = {f"{property_name}__iexact": cls._cast_field(filter_value, str)} _cast_field is a function like so: @classmethod def _cast_field(self, field, _type): if isinstance(field, _type) or isinstance(field, QuerySet): casted_field = field else: casted_field = _type(field) if isinstance(casted_field, str): casted_field = casted_field.lower() return casted_field So far, this is great. The queryset will look for where the property is an exact match on a lowered string. But what if I also want to lower the value of the data inside the column, as well as the value it's filtering on. I'm not sure if this is the correct way to write this, but something like select * from foo_bar where lower(column) = lower('Foo_Bar') -
DRF: Adding few annotated fields to nested serializer
Sorry i can't find solution in official documentation. My question is how i can add few annotated fields to nested serializer. For example i have computed fields 'likes', 'dislikes' and 'is_voted' for each comment. I want add this fields to different serializer for example 'votes'. But i got error Got AttributeError when attempting to get a value for field likes on serializer CommentVoteSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'likes'. Here is my code views.py class PostViewSet(viewsets.ModelViewSet): likes = Count('votes', filter=Q(votes__choice=True)) dislikes = Count('votes', filter=Q(votes__choice=False)) queryset = Post.objects.all().prefetch_related( Prefetch('comments', queryset=Comment.objects.filter(parent__isnull=True).order_by('-pub_date') .annotate(likes=likes) .annotate(dislikes=dislikes) .prefetch_related(Prefetch('children', queryset=Comment.objects.all() .annotate(likes=likes) .annotate(dislikes=dislikes))))) serializer_class = PostSerializer permission_classes = [IsOwnerOrAdminOrReadOnly] pagination_class = PostPagination lookup_field = 'slug' def get_serializer_class(self): """" Attach related comments when get post detail """ if self.action == 'retrieve': return PostRetrieveSerializer return self.serializer_class def perform_create(self, serializer): serializer.save(author=self.request.user) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) body = models.TextField() tags = TaggableManager(blank=True) pub_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pub_date'] class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(max_length=500) pub_date = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, … -
API Design Questions using Django for OS tasks (REST vs RPC)
Background: I have an application that is supposed to automate some infrastructure & OS-heavy tasks that happen on a network file system (for example: mounting volumes, shutting down / bringing up servers, creating directories, moving data around, ssh-ing etc). Ultimately there are a lot of OS-level commands that need to be run in a sequence for each action. Our consumer/client likely does not know this sequence, but knows "I want to do X task". Tech stack: Python/Django I have been tasked with setting this application up but am perplexed on the best way to approach for modularity from the API standpoint & just overall design. Currently, we have a similar application that is a SOAP-style (rpc) but the way it is written is not very modular. Like for example, one function will have a ton of random hardcoded subprocess commands - not the approach I want to emulate here. Initially I was leaning more towards REST API since Django has a nice django rest framework plug-in, but am having trouble modelling these very action-oriented tasks. The more I read other things online, the more I come to believe I really need to think of every little action as a resource … -
Data from Django-model not showing updates in Django dash app
import plotly.express as px import pandas as pd from django_plotly_dash import DjangoDash from product.models import Products app = DjangoDash("SimpleExample") products = Products.objects.all() to_dic = list(Products.objects.all().values("name", "price")) keys_are = [] values_are = [] dictionary = {} for i in to_dic: keys_are.append(i["name"]) values_are.append(i["price"]) dictionary["name"] = keys_are dictionary["price"] = values_are opts = [] for i in to_dic: opts.append({"label": i["name"], "value": i["price"]}) app.layout = html.Div( [ html.Div( children=[ html.Label("Products"), dcc.Dropdown(id="pid", options=opts, value=values_are[0]), ], style={"padding": 10, "flex": 1}, ), html.Div(id="gr_container", children=[]), html.Br(), dcc.Graph(id="pro_graph", figure={}), ], ) @app.callback( [ Output(component_id="pro_graph", component_property="figure"), Output(component_id="gr_container", component_property="children"), ], [ Input(component_id="pid", component_property="value"), ], ) def update_graph(selected): message = "The option selected is :{}".format(selected) fig = px.bar(dictionary, x="name", y="price") return fig, message if __name__ == "__main__": app.run_server(debug=True) this is my dash-graph.py file in django project, when I run the project it show bar on dashboard, but when I update database i.e. the product model it does not update the bar and show the old graph until I run the server again, also the select box is just for testing no use for that here. -
Django admin, return full name function to list_filter
So I made a model called Customers which has a first_name, a last_name, and a dob (aka Date of Birth). I don't want to store the full_name in a field, I just want to be able to order the customers by their Full name, rather than either first_* or last_*. I wanted to make a function in the model called getFullName, which returns the first and last name together, but Django threw an error saying getFullName does not refer to a field. Any ideas on how I could fix that by avoiding having a full_name attr, which is being set on the save method? I'm also using the default Django admin, just because I love it (especially with Django-jet). -
Validate soft foreign key Django
Have a model in django that has a json field with list of IDs to a different model. How can we validate the inputs to that field are valid foreign key. Not using many to many field or a joining model separately. -
How can I make a user list of those who have given feedback on the particular product?
I have made a feedback form. Now I want to make a user list of those who have given feedback on the particular product. My motive is, that if any user gives feedback on a particular product, he/she won't be able to give another feedback on that particular product and can't see the feedback form. A user can share just one feedback on one product. But he/she will be able to give feedback on other's products. How can I make a user list of those who have given feedback on the particular product? Help me... models.py: class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.pk) + "." + str(self.product_title) class ProductREVIEWS(models.Model): user = models.ForeignKey(User, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) def __str__(self): return str(self.pk) + "." + str(self.product) + "(" + str(self.user) + ")" views.py: def quick_view(request, quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) AllProductFeedback = quick_view.productREVIEWrelatedNAME.all() TotalProductsFeedback = AllProductFeedback.count() OverallFeedback = ProductREVIEWS.objects.all() context = { "quick_view":quick_view, "TotalProductsFeedback":TotalProductsFeedback, "AllProductFeedback":AllProductFeedback, "OverallFeedback":OverallFeedback, } return render(request, 'quickVIEW_item.html', context) -
Django: Linking Models in different apps gives circular import error
I have two apps in my project names quiz_app_teacher and accounts many models from these files are connected with each other, but when i try to migrate I get this error File "F:\self\quiz_site\quiz_app_teacher\models.py", line 2, in from accounts import models as account_models File "F:\self\quiz_site\accounts\models.py", line 13, in class Student(models.Model): File "F:\self\quiz_site\accounts\models.py", line 15, in Student quizzes = models.ManyToManyField(quiz_models.Quiz) AttributeError: partially initialized module 'quiz_app_teacher.models' has no attribute 'Quiz' (most likely due to a circular import) quiz_app_teacher/models.py from django.utils import timezone from accounts import models as account_models from django.db import models # Create your models here. ANSWER_CHOICES = ( ('A', 'A'), ('B', 'B'), ('C','C'), ('D','D'), ) class Quiz(models.Model): #https://www.sankalpjonna.com/learn-django/the-right-way-to-use-a-manytomanyfield-in-django name=models.CharField(max_length=250) quiz_id = models.CharField(max_length=300,) created_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(account_models.User, on_delete=models.CASCADE,related_name='quizzes') #Using related_names Author.quizzes.all() #will list all the quizzes which are made by that author. course = models.ForeignKey(account_models.Course, on_delete=models.CASCADE, related_name='quizzes') def save(self, *args, **kwargs): #override default save method to do something before saving object of model if not self.quiz_id: self.quiz_id = self.name+"-"+self.created_date.strftime("%M%S") #TODO:Edit this super(Quiz, self).save(*args, **kwargs) def __str__(self): return self.name class result(models.Model): #quiz=models.OneToOneField(Quiz,on_delete=models.CASCADE) student=models.ForeignKey(account_models.Student , on_delete=models.CASCADE,related_name='my_results')#maybe use account_models.User quiz=models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='results') points=models.IntegerField() def __str__(self): return f"Student name: { str(self.student)} Points:{ str(self.points)}" class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') #quiz=models.ForeignKey(Quiz, on_delete=models.CASCADE) question=models.CharField(max_length=300,) A … -
How to handle too many elements in django-ajax-select admin panel?
I am using the django-ajax-select library to display a many to many relationship in the admin panel. The problem is that I have too many objects linked and it is making super long page. Do you know if is there any way I can customize that element so it can have some kind of scrollbar or pagination? Here is an example illustrating the problem: Image link And this is how I added the element to the admin panel: form = make_ajax_form( MainClass, { "users": "user", # LookupChannel is registered as user "admins": "user", }, ) -
how to get value exists in two separate lists using python
Compare two lists and find duplicate that exist in both lists from two lists remove the existing duplicates and create new lists. Input a= [ "DJI_0229.jpg", "DJI_0232.jpg", "DJI_0233.jpg" "DJI_0235.jpg" ] b= [ "DJI_0229.jpg", "DJI_0232.jpg", "DJI_0233.jpg" "DJI_0230.jpg", "DJI_0231.jpg", "DJI_0234.jpg" ] output = [ "DJI_0230.jpg", "DJI_0231.jpg", "DJI_0234.jpg", "DJI_0235.jpg" ] -
Django Filter get value from field
How do I get the value from a field after a running filter? all_q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False) I need to get the values of the field choice_weight from the returned queryset? The ProjectQuestoinnaireAnswer model has a fk to a Choices model that has a choice weight value class ProjectQuestionnaireAnswer(models.Model): YN_Choices = [ ('Yes', 'Yes'), ('No', 'No'), ('Unknown', 'Unknown') ] question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE) answer = models.ForeignKey(Choice, on_delete=models.CASCADE,null=True) value = models.CharField(max_length=20, blank=True) notes = models.TextField(blank=True) response = models.ForeignKey(ProjectQuestionnaireResponse, on_delete=models.CASCADE) class Choice(models.Model): question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) choice_value = models.CharField(max_length=20, blank=True) choice_weight = models.IntegerField(blank=True, null=True) Thanks -
How can I select an instance of django model to update the info inside that model or related models?
I have basically three models. class Users(models.Model): name = models.CharField(max_length=100) ... class Portfolio(models.Model): name = models.CharField(max_length=50) user = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='portfolio') class BuySell(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, related_name='buy_sell' ... Any user can have multiple portfolios and portfolios can have many buy-sell. From my viewset how can I access the portfolio instance selected by the user to add buy-sell data? In my Viewset: class BuySellViewSet( viewsets.GenericViewset, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin ): serializer_class = BuySellSerializer queryset = BuySell.objects.all() def get_queryset(self): return self.request.user.portfolio But when I add multiple portfolios for a single user I get the following error message: TypeError at /api/v1/share/buy-sell/ Field 'id' expected a number but got <django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x7f857c7c6940>. How can I select the correct portfolio instance to add buy-sell data inside that instance? -
State isn't visible in Redux store and action isn't running
I am trying to follow a Python/Django tutorial and I've reached a part that has to do with Redux and I'm kinda stuck. So basically I need to be able to add products to a cart, but the cart state doesn't seem to get "created" if that's the correct term to use and without the state normally I'd suppose that the actions wouldn't work either. This is how the reducer looks like currently: import { CART_ADD_ITEM } from "../constants/cartConstants"; export const cartReducer = (state = { cartItems: [] }, action) => { switch (action.type) { case CART_ADD_ITEM: const item = action.payload; const existItem = state.cartItems.find((x) => x.product === item.product); if (existItem) { return { ...state, cartItems: state.cartItems.map((x) => x.product === existItem.product ? item : x ), }; } else { return { ...state, cartItems: [...state.cartItems, item], }; } default: return state; } }; I think a problem here might be that existItem is coming back as undefined. import axios from "axios"; import { CART_ADD_ITEM } from "../constants/cartConstants"; export const addToCart = (id, qty) => async (dispatch, getState) => { const { data } = await axios.get(`/api/products/${id}`); dispatch({ type: CART_ADD_ITEM, payload: { product: data._id, name: data.name, image: data.image, price: data.price, countInStock: … -
When I create an object in Django admin, `form_valid()` method is not called
When a new Listing is created the form_valid() method creates a Bid object. However, when I use Django Admin to create new a Listing then, the Bid object is not created because form_valid() is not called. def form_valid(self, form): form.instance.author = self.request.user self.object = form.save() # place a bid in the Bids table with the value starting bid and users id bid = round(float(form.cleaned_data['starting_bid']), 2) Bid.objects.create( bid_value = bid, bidder = self.request.user, item=self.object ) print('form_valid() called') return HttpResponseRedirect(self.get_success_url()) I am new to Python and Django - perhaps the code for creating a new Bid be should be in a method on the Listing model? -
how to solve this problem in virtual environment?
i want to activate my models in my files, my code in terminal: (env) PS C:\Users\MadYar\Desktop\code.py\learning_log> python manage.py makemigrations learning_logs error: No changes detected in app 'learning_logs' im using django to make a web application and i add models in my settings.py like that: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_logs' ] i dont know why it sais no changes detected in app 'learning_logs'