Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When should "_set" be added to a Django query?
In the following query, the reference to tweet has a "_set" in prefetch, but not in annotate. The relationship from user to tweet is many-to-one in both cases as well." How do I determine if "_set" should be added? class User(models.Model) name = models.CharField(max_length=50) class Tweet(models.Model) user = models.ForeignKey("User") favorite = models.IntegerField(default=0) User.objects.prefetch_related( Prefetch( "tweet_set", query_set=Tweet.objects.order_by('favorite') ).annotate(most_favorites=Max("tweet__favorite")) # Why not "tweet_set__favorite"? -
Could not parse the remainder: '${id}' from '${id}'
Hi there I am working on a blogpage using django rest framework api system. I am trying to set the url id using javascript DOM but don't know where it all go wrong my javascript code: fetch('http://127.0.0.1:8000/getdata') .then(response => response.json()) .then(data => { ul = document.getElementById('my-list'); ul.innerHTML = ''; data.forEach(element => { const list = document.createElement('div') id = element.id list.innerHTML = ` <h1 class='text-uppercase' >${element.title}</h1> <hr> <h5>@${element.author}</h5> <div>${element.content} </div> <button class="btn btn-danger" onclick="deleteitem(${element.id})">delete</button> <a href="{% url 'editpost' ${id} %}" class="btn btn-info"></a> `; list.classList.add('card'); list.classList.add('card-body'); list.classList.add('mb-2'); ul.appendChild(list); console.log(element.title) }); }) if you need more informations please ask I have try it to use {{}} and {} and just raw id it didn't work -
TemplateSyntaxError at / Could not parse the remainder: 'product.tk' from ''main-product-detail'product.tk'
I'm stuck on a problem that I solve most of the time but now, when I place the links in my home.html files for the product detail page, an error appears: TemplateSyntaxError at / Impossible to analyze the rest: 'product.tk' of ''main-product-detail'product.tk' I checked everywhere and modified things but nothing changed. take a look at my code and tell me where is the error views from django.shortcuts import render, redirect,get_object_or_404 from django.contrib.postgres.search import SearchVector from django.db.models import Q from main.models import Cart from command.models import * from notification.models import * from user.models import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ReadOnlyModelViewSet from main.serializers import ProductSerializer # CategorySerializer from .utils import get_cart_data import validators from amazon import scrape, scrape_search def home(request): products = Product.objects.all() product_recommadeds=Product.objects.all().order_by('-date') # new_products= Product.objects.filter(date='') cart_id = request.COOKIES.get('cart_id') cart = None cart_count = 0 if cart_id: try: cart = Cart.objects.get(id=cart_id) cart = get_cart_data(cart) cart_count = cart and len(cart['cart_products']) or 0 except Exception as e: print(f'panier non trouvé: {e}') response = render(request, 'main/home.html', locals()) if not cart and cart_id: response.delete_cookie('cart_id') return response def product_detail(request,tk): product = Product.objects.get(id=tk) similar_products = Product.objects.annotate(search=SearchVector( 'name', 'description', 'keywords', 'price','color')).filter(Q(search=product.keywords) | Q(search__icontains=product.keywords.split(' ')))[:12] product = vars(product) … -
Cannot make namespace work for main django app
TL;DR I want to use namespaces for all of my django apps. It works fine for all the regular apps, but I get a "NoReverseMatchError: 'myproject' is not a registered namespace" for my main project app. Is there anything specific to this app that causes the namespace to not work? Details I just started a new django app and I'm using namespaces for the first time. My project tree is as follow (only relevant files and directories included): myproject/ ├── myproject/ │ ├── templates/ │ │ ├── base.html │ │ └── home.html │ ├── settings.py │ └── urls.py └── app1/ ├── templates/ ├── urls.py └── views.py My urls.py files are as follows: myproject/urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from myproject import views app_name = 'myproject' urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('app1/', include('django.contrib.auth.urls')), path('app1/', include('app1.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app1/urls.py from django.urls import path from app1 import views app_name = 'app1' urlpatterns = [ path('login', views.login, name='login'), path('logout', views.logout, name='logout'), ] When calling {% url 'app1:login' %} or return redirect('app1:login') everything works fine. However, when I try to use … -
Optimal filtering of the manytomany relationship
I have a model called "Car" and another model called "Preference". The car field has a M2M relationship with "Preference". I am doing a query to get all the cars that have the preference (for example) with id= 1 and 2. (The car has many more preferences assigned to it). How can I get optimally all the cars that have strictly the Preferences with id 1 and 2? The actual functional code is the following (very suboptimal): preferences_list = [1, 2] for preference_item in preferences_list: cars = cars.objects.filter(preferences__id=preference_item) I have tried this but it doesn't work either: preferences_list = [1, 2] cars_q = Q() for preference_item in preferences_list: cars_q &= Q(preferences__id=preference_item) cars=cars.objects.filter(cars_q) Is there any more optimal alternative that does not do a query for each Preference? -
How to show a link after login on the basis of user authentication whether user has a blogging account or not
Problem context: Below is my Blogger model. I am using a one-to-one relation ship with inbuilt user class Blogger(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) about = models.TextField(max_length=2000, null=True) def __str__(self) -> str: return f'{self.user.first_name} {self.user.last_name}' Before logging in I get the the following Login page. ( I am using django.contrib.auth.urls with custom login page that extends base_generic.html. HTML has link in the side bar About Yourself which would only show up after successful login only. {% if user.is_authenticated %} <li>User: {{ user.get_username }}</li> <li><a href="{% url 'blogger-create' %}">About yourself!</a> </li> When a user after sign up or login clicks on About yourself link then user is redirected to blogger create form where he will update his About information. User Registration creates an instance of user which would be mapped to a new instance of Blogger via About Yourself Problem I want to have two views UpdateView and CreateView that would ensure if a blogger instance is already mapped to user then the update view would be called. this would require conditions in the template of base_generic.html. if else conditions would use something like models.Blogger.objects.filter(user=self.request.user). The trouble is as already stated I am using inbuilt accounts\login. How to achieve this logic … -
Consuming API that is big part of my application
I need to consume API of my second app which will be big part of my main application. This API will affect to my main tables/models and it will extend them. I have a problem with authorization. I created standard authorization depending on access_tokens, but there is a problem with it. As I said, API will extend my main models, so I need to override save(), get() and similar methods to work with. For example: Saving ModelA in my app performs the save of ModelB in external API Geting ModelA in my app performs get of ModelB in external API The problem is when I try to talk with external API in overrided method. To do this I need request (where access_token is stored) but I can't get request in model save() method. Even if I will somehow get it, it will always be problem in diffrent places of application when I have no request. I don't know how to make it works and create the code clean. Maybe I should change the type of authorization in my second APP? -
Django project run from terminal but not from PyCharm
I can run my Django project from terminal like: python manage.py runserver, but if I try to run it from PyCharm it give me a lot of various errors. I've checked if interpreters are the same by typing "pip -V": from terminal: /home/user/Desktop/project/venv/lib/python3.8/site-packages/pip in configuration, interpreter path: ~/project/venv/bin/python -
why distinct can't save changes in value
I have this code trees = AssessmentTaskForm.objects.distinct('tree') print(trees.count()) # output is 1 trees = trees.distinct('tree_status__name_en') print(trees.count()) #output is 3 and the output are 1 in 1st print 3 in 2nd print my need is : i want to use first filtring query and use it as input in 2nd query -
Django: Get absolute file path of template file from template name, without parsing the template
How to get the absolute file path of a template file from it's template name, without parsing the template? E.g. given foo/bar.html return home/user/project/app/foo/templates/foo/bar.html The django.template.loader.get_template will parse the template. I think there was a django.template.loader.find_template but it was deprecated. Please note this is not a duplicate of How to get the template path in the view django becaue that solution parses the whole template, which is slow when trying to find the path of many template_names. -
HTTPSConnectionPool(host='newsapi.org', port=443): Max retries exceeded with url
I am trying to communicate between Django and Python file but I am getting below error : [enter image description here](https://i.stack.imgur.com/saR0y.jpg) I tried to use the api to construct a website based on django,these are my code and the error,I have tried set time out,false verify,and even changed my network connection, but it still could not connect -
Working on django project. want to make api access restricted based upon the user's group permissions
I have a custom user model with group as a field. from django.contrib.auth.models import Group class Users(AbstractBaseUser): group=models.ManyToManyField(Group, blank=True) i'm assigning model permissions to the group from django admin panel. Now i want to make sure that user's group permission should be checked before a user can access an api like this: @authentication_classes([TokenAuthentication]) class SiteList(generics.ListCreateAPIView): permission_classes = [IsAuthenticated, GroupPermission] //GroupPermission as a check queryset = Site.objects.all() serializer_class = SiteSerializer -
uwsgi not starting and returns no error, exit after showing "[uWSGI] getting INI configuration from ../ubuntu/ENV/uwsgi.ini"
When i am trying to run uwsgi, it starts and exit with out any error only return single line responce "[uWSGI] getting INI configuration from ../ubuntu/ENV/uwsgi.ini" my uwsgi.ini strict = true #binary = /home/xyz/pqr/bin/uwsgi chdir = /home/xyz virtualenv = /home/xyz/pqr uid = ubuntu gid = ubuntu wsgi-file = /home/xyz/deploy/wsgi.py socket = /home/ubuntu/sockets/uwsgi.sock master = true # threads = 4 #run uwsgi with process only thread-stacksize = 512 threads-stacksize = 512 # auto scaling cheaper-algo = busyness processes = 64 ; Maximum number of workers allowed cheaper = 4 ; Minimum number of workers allowed cheaper-initial = 4 ; Workers created at startup cheaper-overload = 1 ; Length of a cycle in seconds cheaper-step = 2 ; How many workers to spawn at a time cheaper-busyness-multiplier = 30 ; How many cycles to wait before killing workers cheaper-busyness-min = 25 ; Below this threshold, kill workers (if stable for multiplier cycles) cheaper-busyness-max = 75 ; Above this threshold, spawn new workers cheaper-busyness-backlog-alert = 16 ; Spawn emergency workers if more than this many requests are waiting in the queue cheaper-busyness-backlog-step = 4 ; How many emergegency workers to create if there are too many requests in the queue harakiri = 60 … -
Free(): Invalid Pointer error while trying to upload multiple layers in cartoview?
I have installed cartoview and trying to upload multiple layer files (total 6) in cartoview, but when i upload it then this error occurs: Free(): Invalid Pointer Aborted (core dumped) I tried to find the solution to the problem but it was not found on the web. Can someone kindly help? -
Django form save: Object is None, but form is valid
I expect the answer here is related to the problem I have, but it is unfortunately not the same and I have not been able to use it to solve the problem. I also tried following the method here, which also is not proving successful in solving this particular issue. Here is the issue: I am trying to use a simple form to create a new object. Some of the info comes from the user, some of the info comes from the system. When I process the POST request, using simple print statements I can see that the form is valid, and that it has the right data. But then when I go to save it tells me the object is None so it's not saving anything. Below follows: views.py forms.py models.py template.html What am I missing? Thank you! views.py def add_set_to_active_workout(request): workout = get_active_workout() if request.method == "POST": form = SetForm(request.POST) if form.is_valid(): print(f"Cleaned data is: {form.cleaned_data}") # This prints what I'd expect, namely, the user submitted data. set = form.save(commit=False) set.workout = workout print(f"Set is {set}") # This prints: Set is Set object (None) set.save() print("set saved") return HttpResponseRedirect(reverse("log:active_workout")) else: return render(request, "log/active_workout.html", { "set_form": form, 'workout': workout … -
Django Queryset partition data
I have a django queryset result with n results. The Django model they originate from has an attribute DateTime. I need to counts of these objects but based on the following rule, that a single count must be records that are no more than 1 minute apart. My Django Model class MyModel(models.Model): event = models.CharField(max_length="50") created_on = models.DateTimeField(auto_now=True) -
Django-mptt with different parent model
I'm adding a new feature to the existing application. This new feature will inform the user how to get an award by collecting emblems. The application will show how to get the award (I plan to use the Django-mptt or probably the Django-treebeard?). For example, to get Award A, the user needs to collect emblems as follows: — Award A: — Emblem AA — Emblem BB: — Emblem CC — Emblem DD Each emblem will be unique. Below is the model from an existing application. class EmblemClass(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE, related_name=“emblemclasses”) name = models.CharField(max_length=255) image = models.FileField(upload_to=‘images’, blank=True) description = models.TextField(blank=True, null=True, default=None) The following is the model I'm about to make: class AwardInfoClass(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE, related_name=“awardinfoclasses”) name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True, default=None) class AwardAlignmentClass(models.Model): awardinfoclass = models.ForeignKey(AwardInfoClass, on_delete=models.CASCADE) award_name = models.ForeignKey(Emblem, on_delete=models.CASCADE) award_parent = models.ForeignKey(Emblem, related_name='emblemclasses', blank=True, null=True, on_delete=models.CASCADE) In the documentation from the Django-mptt, the 'award_parent' is set to 'self' and not from a different model. I'm using an adjacency list for designing the tree and extending the existing application. Am I making the wrong model design? I have tried manually without the Django-mptt library. However, I have a … -
How to unit test for natural key in models.py in django
I want to unit test for the models.py in django. I do not know how to unit test for the function natural_key() class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=10, default="default", null=True, blank=True) @property def natural_key(self): return (self.email, self.username) I tried self.user1 = User.objects.create( email="user@email.com" username="username1") def test_natural_key_is_created(self): self.assertEquals(self.user1.natural_key, "user@email.com", "username1") but my unit test is failed -
Django F expression changes
We used to run Django 1.6 with Python 2.7 and one of our models had a field called balance, defined as: balance = models.F('gross') + models.F('refunded') - models.F('paid') the output of this field would be, for example: DecimalField('1200'). After upgrading to Django 3.2 and Python 3.9.2, balance returns: <CombinedExpression: F(gross) + F(refunded) - F(paid)> We tried to work around this by replacing balance with: @property def balance(self): return self.gross + self.refunded - self.paid and this worked until we ran into the error: FieldError: Cannot resolve keyword 'balance' into field. Does anyone know of the new correct way to keep the same functionality as we had before when using F expression to define balance? Also, I have seen some help regarding .refresh_from_db(), but when running a shell and executing: o = Order.objects.all().first() o.balance Output: <CombinedExpression: F(gross) + F(refunded) - F(paid)> o.refresh_from_db() Output: <CombinedExpression: F(gross) + F(refunded) - F(paid)> The output remains the same... Time and patience greatly appreciated fellow coders. Kindest regards -
Consume django data in nextjs
I struggle to consume rest API data with NextJs. In particular, I don't understand how to fetch the end points. My need is to loop through the data, but using posts.map, raises error data.map is not a function which is logical as my API describes an object and not a list. But then if I call only {data.id} the result is a blank page. I.e. without the mapping. What am I missing here? If possible, I'd like to convert the object into a list so I can loop and call it by the props, but how? Any input would be highly appreciated. API: { "meta": { "total_count": 3 }, "items": [ { "id": 3, "meta": { "type": "home.HomePage", "detail_url": "http://localhost:8000/api/v2/pages/3/", "html_url": "http://localhost:8000/", }, "title": "Home" }, { "id": 4, "meta": { "type": "news.NewsPage", "detail_url": "http://localhost:8000/api/v2/pages/4/", "html_url": "http://localhost:8000/breaking-news/", }, "title": "Breaking news" }, { "id": 5, "meta": { "type": "blog.BlogPage", "detail_url": "http://localhost:8000/api/v2/pages/5/", "html_url": "http://localhost:8000/blog-api/", }, "title": "blog api" } ] } Index.js import Link from "next/link" //getStaticProps export const getStaticProps = async () => { const API_URL = "http://127.0.0.1:8000/api/v2/pages/" const request = await fetch(API_URL) const data = await request.json() return{ props:{ data }, } } //route export default function Game({ data … -
Plotly graph not showing in tabs when filtering using dropdown
I'm using django-plotly-dash package to plot the graphs inside a django app. I'm trying to put the graphs in tabs where they have a dropdown to filter the result. I've been struggling for a few hours but still can't find what I've done wrong here. This is the tab layout: app_tabs = html.Div([ dcc.Tabs(id='tab-parent', children= [ dcc.Tab(label="Chart", id='tab-chart'), dcc.Tab(label="Map", id='tab-map', children=[dcc.Graph(figure={})]), ], ) ]) Here are the main layout and the callbacks: app.layout = html.Div([ html.H1('Daily Cases', style={'textAlign': 'center', 'color': colors['background']}), app_tabs, dcc.Dropdown(id='country-dropdown', options=country_options, multi=True, value=['Bangladesh', 'India', 'China', 'United States'], style={'width': "50%"}), ]) @app.callback( [Output(component_id='tab-parent', component_property='children')], [Input(component_id='country-dropdown', component_property='value')] ) def switch_tab(tab_chosen, country_list): if tab_chosen == "tab-chart": dff = daily_case[daily_case['location'].isin(country_list)] fig_chart = px.line( data_frame=dff, x='date', y='new_cases_smoothed', color='location', title='Daily Cases', labels={'new_cases_smoothed': '', 'date': ''}, template='plotly_white' ) return dcc.Graph(figure=fig_chart) elif tab_chosen == "tab-map": pass return html.P("This shouldn't be displayed for now...") Can anyone guide me what I'm doing wrong here? -
thousand seprator for integer fields input in django form
I want to have thousand separator while inputting numerical data in forms(int field),I tried using text type and JS to solve the problem but I want something more logical. I'd be glad to receive your answers with samples. best regards, -
Django. Automatic field change via admin panel
I am new to Django. I am writing the first project, I came across the following problem. We have a 'Post' model with a 'district' field. And there is a "Record" model. How to dynamically change the entry number when creating a journal entry (via the admin panel). For example, there are already 3 records with area #1, and when creating the next record, number 4 is automatically filled in. Or maybe there is a way to automatically fill in the number, immediately after creating the record? I have already achieved the automatic creation of the record number through the function. But now it does not take into account different district, but numbers all records in order, regardless of the selected district. class Post(models.Model): """Post in journal.""" def auto_number_post(): all_posts = Post.objects.all() if all_posts: next_number = max(all_posts, key=lambda x: x.number_post) return next_number.number_post + 1 return 1 number_post = models.PositiveIntegerField( default=auto_number_post, unique=True, ) district = models.ForeignKey( 'District', blank=False, null=True, on_delete=models.SET_NULL, related_name='posts', ) class District(models.Model): title = models.CharField(max_length=100) -
Django & Paypal button integration
I am integrating a paypal payment method into my website which is working perfectly.... until I try to add a description so I can view all of the order details on the paypal invoice. As soon as I add description: {} to the createOrder function below, paypal fails to load: <script> var total = '{{order.get_cart_total}}' // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { color: 'blue', shape: 'rect', }, // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value:parseFloat(total).toFixed(2) }, description: { order_id }, }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(JSON.stringify(details)); submitFormData() }); } }).render('#paypal-button-container'); </script> in console i get the following errors: I have added the settings below to my settings.py file: SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SAMESITE = 'None' -
React hook is not updating state after completing a fetch request
I am trying to retrieve article data from my backend api using a fetch request and display it on screen. The request retrieves the data successfully, however when I try to update the state of the component variables using the setArticle hook, nothing happens and the request completes without passing any data in. function Home(props) { const [articles, setArticles] = useState([]); useEffect(() => { fetch(`http://localhost:8000/api/articles/`, { method: 'GET', }) .then(response => response.json()) .then(result => { if (result.error) { console.log('Error:', result.error); return false; } console.log(result); setArticles(result); console.log(articles); }) }, []) const articleList = articles.map((article) => <ArticleCard article={article} width='400'/> ) return( // return page HTML and articleList ) } export default Home; console.log(result) shows a populated array, but it doesn't get set anywhere, please help.