Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CORS issue with HTTP requests when sendign http get request to host IP
I have a development environment with python's django web server running locally. I had setup django to respond to API requests and whenever I send http GET requests to http://localhost:8000/api/service/ the server responds as expected. The issue happens whenever I send the same request using the host IP, i.e, http://192.168.15.66:8000/api/service/ (I realized the issue when trying to get the api data from another host in the LAN) I'm using postman to send the requests in order to validate whether it's working or not, though, I'm developing a javascript react application that already consumes the api data. Through the web javascript application, there's a bit more information. The browser's console presents the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.15.66:8000/api/service/. (Reason: CORS request did not succeed). Status code: (null). I've been searching around and tried a few suggestions, such as: setting server/setting.py ALLOWED_HOSTS to: ['192.168.15.66'] , to [] and to ['*'] whitelisting with CORS_ORIGIN_WHITELIST to: ['192.168.15.66'] and to ['*'] Here's my setting.py MIDDLEWARE varible value: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] Any clues what I could be missing? -
How do I find all descendant models in a child/parent relationship?
Consider the following model: from django.db import models class Person(models.Model): name = models.CharField(primary_key=True, max_length=50) parent = models.ForeignKey('self', null=True, default=None, on_delete=models.SET_NULL) a = Person.objects.create(name='A') b = Person.objects.create(name='B') c = Person.objects.create(name='C', parent=a) d = Person.objects.create(name='D', parent=b) e = Person.objects.create(name='E', parent=c) Is there an easy way to find all descendants of an instance? Example of desired output: a.descendants >>> [a, c, e] -
How do I query for "greater than" on a textfield in Django?
I have a certain field in my database which is a textfield. However, for a certain use I have a set of records that only include numbers (saved as a string of course) and I want to query them using "gte" (greater than). Normally I would do: MyTable.objects.filter(text_field__gte=100) However, this does not return any results. It seems that I need to cast this field as an integer. Can I do that within this same query? The actual query is more cumbersome and involves external tables (something like MyTable.objects.filter(associated_table__other_table__text_field__gte=100)), but I am simplifying above for clarity. -
How would i go about displaying more information of objects in a ModelForm?
I've tried googling this for hours and i just can't seem to understand it. So i have a model (called Vare) that has 8 different fields with information and containes a str function. I have another model called (Rett) where you store 3 different fields and a field where you store Vare objects. I've managed to make a form for this that displayes the 3 fields + the Vare objects field, but the Vare objects field only shows the name of Vare in a dropdownbox (presumebly from the str function). Now i want to display these with more information from the 7 other fields of vare and put the into a nice looking list element instead of just a drop-down showing the name. But i can't seem to find out how you are supposed to do it. What i want is kinda like looking at amazone where you can see lots of information about the different Vare (like date crated, who is selling, price) in a nice orderly list instead of a dropdown with just the name. Currently i am just using the basic ModelForm with a meta class and i accsess it in my template as {{ rett_form.as_p }}. … -
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