Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Performant way to validate numerics or range of numerics with RegexValidator in Django
The problem I have a model that has a CharField field, where the field can only accept numerics or a range of numerics. The numerics must either have a leading zero if they are decimal and are <1, and if they are a whole number, they cannot have a trailing period unless the trailing period has a trailing zero. The ranges are delineated using a hyphen and must not contain any spaces. I'm using Django's RegexValidator to validate the field. Note: I don't care if the ranges are reversed (e.g. 6-3, 10.3-0.13) These are some examples of values that should pass in the validator: 5 0.42 5.0 5-6 5-6.0 0.5-6.13 5.1-6.12 13.214-0.1813 These should be invalid values for the validator: 5. 5.1.3 5.13.215 5-13.2-14 .13-1.31 5-6. 5 - 6 My current solution my_field = models.CharField( ... validators=[ RegexValidator( r'^[0-9]+([.]{1}[0-9]+){0,1}([-]{1}[0-9]+([.]{0,1}[0-9]+){0,1}){0,1}$', message='Only numerics or range of numerics are allowed.' ) ] ) What I need help at As you can see, this is a pretty gnarly regex pattern, and I'm not so sure if this pattern is performant. I'm not a regex guru so I'd appreciate if someone offers a better solution. -
Data added in Request session lost when using HttpResponseRedirect between views
I have an API, in which if the user is not permitted to access it, am redirecting it to another view along with a user message adding to request session and using that info am using django message framework to display the message in templates. In this process the session data passed from one view is lost while I look in the redirected view. And this is happening only in Production environments. Here is the code. Views - def data_asset_alert_track(request, edf_data_asset_id): data_asset = EdfDataAsset.objects.get(data_asset_id=edf_data_asset_id) x_app_role = access_control.get_xapp_role(request) roles = access_control.get_roles(x_app_role) user = User.objects.get(username=request.user) is_edit_permitted = (access_control.has_edit_all_access(roles, 'edfdataasset'))\ or (True if data_asset.owner_id and data_asset.owner.owner_id == user.username else False)\ or (access_control.is_auth_user(data_asset.owner, user) if data_asset.owner_id else False) if not is_edit_permitted: request.session['message'] = 'Unauthorized Action: Edit DataAsset - %s not permitted'%data_asset.data_asset_name return HttpResponseRedirect(reverse('data_assets')) if data_asset.alert_fl is False: data_asset.alert_fl = 'True' else: data_asset.alert_fl = 'False' data_asset.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) Redirected to view- def data_assets(request): if 'message' in request.session: logr.info("There is a message") messages.add_message(request, messages.ERROR, "A trial message") data_asset_list = EdfDataAsset.objects.select_related('provider').order_by('data_asset_name') field_filter = DataAssetFilter(request.GET, queryset=data_asset_list) context = {'data_asset_list': data_asset_list, 'filter': field_filter, } return render(request, 'edf/data_assets.html', context) This works completely fine in all dev and test environments. What could be the issue? I tried adding these two … -
Django Webpack React: Plugin/Preset files are not allowed to export objects, only functions
I'm trying to configure my react with django. but for some reason whenever I try to npm run start I get this error: Plugin/Preset files are not allowed to export objects, only functions. I've tried: npm install @babel/preset-react npm install babel-preset-react --save-dev npm install -D babel-loader @babel/core @babel/preset-env webpack but did nothing. Django version: 2.2.6 Webpack config: var path = require('path'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { entry: path.join(__dirname, 'assets/src/js/index'), output: { path: path.join(__dirname, 'assets/dist'), filename: '[name]-[hash].js' }, plugins: [ new BundleTracker({ path: __dirname, filename: 'webpack-stats.json' }), ], module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, options: { presets: ['react'] } }, ], }, } settings: WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'dist/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } .babelrc: { "presets": [ "es2015", "react" ] } package.json: { "name": "collegeapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "./node_modules/.bin/webpack --config webpack.config.js", "watch": "npm run start -- --watch" }, "repository": { "type": "git", "url": "git+https://github.com/FendyPierre/collegeapp.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/FendyPierre/collegeapp/issues" }, "homepage": "https://github.com/FendyPierre/collegeapp#readme", "devDependencies": { "@babel/core": "^7.7.4", "@babel/preset-env": "^7.7.4", "babel-cli": "^6.26.0", "babel-core": "^6.26.3", "babel-loader": "^8.0.6", "babel-preset-env": "^1.7.0", "babel-preset-es2015": "^6.24.1", … -
benefit of Django REST Framework when using django with API like calls?
reading This question it looks like I can setup DRF within an existing django project. That got me thinking... I have a django application that uses ajax calls which return very simple view partials which quickly display on the page, and then a few seconds later another ajax call is made to return another view. (you can think of it like the Whac-a-mole games, but each mole is a different view partial being returned from the server.) so essentially I have 30-50 calls per minute to mysite.com/ajax_new_mole with a view similar to (just made this up on the fly, ignore any errors) ... def ajax_new_mole(request): random_id = get_random_mole_id() random_mole = Mole.objects.get(id = random_id) return render(request, 'partials/_mole_photo.html, {'mole':random_mole}) ... and the _mole_photo.html template {% load load_cloudfront %} <div class="img-wrapper" id="{{ photo.id }}"> <span class="album-title" id="album-title">Title: {{ mole.name }}</span> <img src='{% load_cloudfront_medium mole.name %}' id="image{{ photo.id }}"/> </div> Now to my question. In this situation. Would Django REST Framework offer any performance benefits in the reduced overhead for responding to and rendering this content? -
Django filter to check if there are any other booking between the given dates
I am trying to make a hotel booking app. So I have two models, i.e., Room and Booking. # models class Room(models.Model): name = models.CharField(max_length=50) class Booking(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) booked_for_datetime = models.DateTimeField() booked_till_datetime = models.DateTimeField() How can I lock the room A, so the room will not be available to book if there is already another booking for a room A. Eg: Room 101 was booked between 01-12-2019 to 04-12-2019. I would like to block the booking if someone's trying to book the same room (101) between 29-11-2019 to 01-12-2019 between 29-11-2019 to 02-12-2010 between 01-12-2019 to 04-12-2019 between 02-12-2019 to 03-12-2019 between 04-12-2019 to 07-12-2019 I am working with django rest framework, so I will have to apply these validation on the create and update method, maybe something like this: # serializers def roomAvailable(validated_data): available = False # ... # validation check here... # ... return available class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = '__all__' def create(self, validated_data): if roomAvailable(validated_data): return Booking.objects.create(**validated_data) else: raise serializers.ValidationError({ "detail": "Room is not available for these dates." }) def update(self, instance, validated_data): if roomAvailable(validated_data): ... instance.save() else: raise serializers.ValidationError({ "detail": "Room is not available for these dates." }) return … -
django.urls.exceptions.NoReverseMatch: Reverse for 'user-list' not found. 'user-list' is not a valid view function or pattern name
Tutorial 5: Relationship and Hyperlink API Errors Tutorial link address is:https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/ I tried query-related solutions, and encountered similar problems on stackoverflow, but after testing, I still couldn't use them. views.py class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(owner=self.request.user) class SnippetDetail(generics.RetrieveDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly) class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer @api_view(['GET']) def api_root(request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'snippets': reverse('snippet-list', request=request, format=format), }) class SnippetHighlight(generics.GenericAPIView): queryset = Snippet.objects.all() renderer_classes = [renderers.StaticHTMLRenderer] def get(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) urls.py urlpatterns = format_suffix_patterns([ path('', views.api_root), path('snippets/', views.SnippetList.as_view(), name='snippet-list'), path('snippets/<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'), path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet-highlight'), path('users/', views.UserList.as_view(), name='user-list'), path('users/<int:pk>/', views.UserDetail.as_view(), name='user-detail'), ]) urlpatterns += [ path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] serializers.py class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: model = Snippet fields = ['url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style'] class UserSerializer(serializers.HyperlinkedModelSerializer): snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) class Meta: model = User fields = ['url', 'id', 'username', 'snippets'] -
Possible to escape or otherwise pass a value that includes / in Django URL
I'm building a tool using Django that works with the part numbers that my company uses, one set of part numbers includes /'s which I didn't realize when I set up the url to access the part summary. Now when try to pass one of those part numbers it breaks things, is there a way to work around this? I'd like to avoid changing the part number or adding a unique id with no other meaning to the model. an example part number that causes the problem is P-030-P-401/ND the url pattern is /parts/ Thanks in advance -
How to save search result to a model
Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() comment = models.TextField() date_posted = models.DateField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) patient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='patient') def __str__(self): return self.title def get_absolute_url(self): return reverse('public:post-detail', kwargs={'pk': self.pk}) HTML search <div class="content-section"> <form method="GET" action="{% url 'public:home' %}"> <input name ="q" value="{{request.GET.q}}" placeholder="search.."> <button class="btn btn-success" type="submit"> Search </button> </form> </div> VIEWS.py class SearchResultsView(ListView): model = User template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list I want to save this object_list in "patient" model. How can i save search result to model. Is there any different method to search user and save to model? -
I continue getting an error whenever I run my Django program
I started building an application using Django but whenever I run it I always get this error message. django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is p robably caused by a circular import. I currently have three files: mysite/urls.py : from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^account/', include('accounts.urls')) accounts/urls.py : from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home), ] and views.py : from django.shortcuts import render, HttpResponse def home(request): return HttpResponse('Home page') This should theoretically print "Home page" on my ip but the error message continues arising in cmd when I run : python manage.py runserver 127.0.0.1:8080 (I cd'd it too) This is a simplified version of my hierarchy: Mysite accounts urls.py views.py mysite urls.py I have been following a tutorial and checked that everything is correct. Can someone help me find a solution? (Please don't beat me up if I messed something very obvious up. I am new and quite inexperienced) -
Cannot resolve keyword 'active' into field. Choices are... Django
I'm following a tutorial online. but now is driving me crazy. i'm trying to update a view. but honestly after a couple of days i can not find the issue. i have been following the trace, but i can get it. i get the Cannot resolve keyword 'active' into field. Choices are: activate, cart, cart_id, id, product, product_id, quantity message After click the button to get the details of the product and create a new or add a product to a cart the message show up lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\db\models\sql\query.py", line 1049, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\db\models\sql\query.py", line 1419, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'active' into field. Choices are: activate, cart, cart_id, id, product, product_id, quantity [28/Nov/2019 02:18:14] "GET /cart HTTP/1.1" 500 106045 [28/Nov/2019 02:18:26] "GET /cart/add/5 HTTP/1.1" 302 0 Internal Server Error: /cart Traceback (most recent call last): File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\k-her\OneDrive\Escritorio\New\store\views.py", line 51, in cart_detail cart_items = CartItem.objects.filter(cart=cart, active=True) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\db\models\manager.py", line … -
Emails not sending through Django Contact Form
I created a Contact form on my website built in Django but emails sent from the form do not seem to actually send. Here is my form code in forms.py: class ContactForm(forms.Form): email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) Here is the code in my views.py: def contact(request, success=""): submitted = False template_name = "main/contact.html" if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['markbekker1998@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect("success/") if success != "": submitted = True context = {"form": form, "submitted": submitted} return render(request, template_name, context) And finally here is the forms html code: {% load crispy_forms_tags %} <h1>Contact Us</h1> <form method="post"> {% csrf_token %} {{ form|crispy }} <div class="form-actions"> <button type="submit" class="btn btn-primary mb-2">Send</button> </div> </form> If any other code is needed to help debug please let me know and I will include it. Thank you. -
Django: Defining an Admin Action when the Queryset has been modified
If I have some ModelAdmin that defines a custom queryset like: def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate( other_amount=Sum('other__amount'), delta = Sum(-1*F('amount') - F('other__amount')), ) return queryset When I go to create an admin action like: def makeReimbursableUnsubmitted(modeladmin, request, queryset): queryset.update(updated_status='RU') and then go to run the action, I get the following error: Cannot resolve keyword 'delta' into field. Choices are: <fields defined in the model> How can I update my action to work again? -
URL, GET, POST parameters in Django
I am super fresh in Django, I might need some help. Case: I made endpoint in urls.py. There will be pass latitude and long to his endpoint as parameters. router.register( r'name', views.NameView, base_name='name') urlpatterns = [ path('name/', views.NameView.as_view(), name='getLocation') ] What I want to achieve: View connected to the endpoint take the parameters and passes it to the '.../product' API and it receive the data and return the data to front end. I have read a lot about request, but I am confused. This is my view: class NameView(views.ModelViewSet): def getLocation(Location): # here I want to GET with params in URL r = requests.get(url, params=Location) # POST to URL and next should receive data and send to front r = requests.post(url, params=Location) I used Location, beacuse I have definied class in model Location with lat and long params. I will appreciate any help -
Don't know how to convert the Django field (<class 'django.contrib.gis.db.models.fields.MultiLineStringField'>)
I am trying to do a query to my graphql api and I get the next error when i do a query to my api using postman. I understand that the error says it doesn't know how to convert the MultiLineStringField field route=models.MultiLineStringField() in my Route Model, and I think I should do it manually but I don't know where or how. The graphql api is buildins using django 2.2.7, graphene 2.1.8. This is the error: Exception at /graphql Don't know how to convert the Django field routes.Route.route (<class 'django.contrib.gis.db.models.fields.MultiLineStringField'>) Request Method: POST Request URL: http://localhost:8000/graphql Django Version: 2.2.7 Exception Type: Exception Exception Value: Don't know how to convert the Django field routes.Route.route (<class 'django.contrib.gis.db.models.fields.MultiLineStringField'>) Exception Location: /home/jccari/code/gosip-server/venv/lib/python3.6/site-packages/graphene_django/converter.py in convert_django_field, line 95 Python Executable: /home/jccari/code/gosip-server/venv/bin/python Python Version: 3.6.8 Python Path: ['/home/jccari/code/gosip-server', '/home/jccari/code/gosip-server/venv/lib/python36.zip', '/home/jccari/code/gosip-server/venv/lib/python3.6', '/home/jccari/code/gosip-server/venv/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/jccari/code/gosip-server/venv/lib/python3.6/site-packages'] Server time: Thu, 28 Nov 2019 00:30:29 +0000 Route model: from django.contrib.gis.db import models class Route(models.Model): name = models.CharField(max_length=50) route = models.MultiLineStringField() def __str__(self): return self.name This is my queries.py import graphene from graphene_django.types import DjangoObjectType, ObjectType from ..models import Route class RouteType(DjangoObjectType): class Meta: model = Route class Query(ObjectType): route = graphene.Field(RouteType, id=graphene.Int()) routes = graphene.List(RouteType) def resolve_route(self, info, **kwargs): id = kwargs.get('id') … -
Django: Nothing happens when I run 'py manage.py runserver'
I am following the tutorial on the Django website. I have changed the directory to where mysite is and nothing happens when I run the script from the tutorial in the Command Prompt. It just goes to the next line with no errors. I read from previous responses it has to with Environment Variables but when I added the directory it still did not work. I have the latest version of Python and Django. -
dockerized django gunicorn nginx doesn't find static files when i add URL to urls.py
This is really weird and i've tried fixing it for over 20 hours over the past few days, but no luck. This is a project that i'm trying to dockerize and it's almost done except for being able to show static files. My issue is that the static files aren't being served when I add the URL to the urls.py file that is creating a path to my index app. Basic urls.py (main project urls.py) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ] If I visit http://localhost:8000 the admin static files are shown perfectly with no issues at all with the config above. If I then add the URL to my index app like the following inside urls.py (main project urls.py) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls', namespace="index",)), ] And once again I navigate to http://localhost:8000 and this time the static files aren't being shown! I am baffled and honestly have no idea. I have the full source code available on Github. Feel free to take a look in there, clone the project and try for yourself. -
Django tries to find template in a non-existing folder
I'm new to Django and I'm following the guide at https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django. So I thought I would follow along but not entirely copy the code. I must have made some basic mistake, but I can't figure it out. I read many threads describing similar problems but none solved mine. When I try to access any page other than index.html I get this Error message: TemplateDoesNotExist at /catalog/livros/ catalog/livro_list.html Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\templates\catalog\livro_list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\myvenv\lib\site-packages\django\contrib\admin\templates\catalog\livro_list.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Gledyson\PROJECTS\Websites\Library\myvenv\lib\site-packages\django\contrib\auth\templates\catalog\livro_list.html (Source does not exist) Django is trying to find my templates in 'templates/catalog/' instead of 'templates/'. I tried moving my templates to 'library/catalog/templates/catalog/' and it works. But I can't manage to make it find my template in 'library/templates'. My project tree looks somewhat like this: Library/ | -- catalog/ | | | -- static/, admin.py, apps.py, models.py, tests.py, urls.py, views.py | -- locallibrary/ | | | -- settings.py, urls.py, wsgi.py -- myvenv/ | -- templates/ | -- base.html, index.html, livro_detail.html, livro_list.html My locallibrary/settings.py is: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for … -
Serializer is not valid
When I try to make a POST request to my API endpoint to create a user in my Users table, I get mysterious Serializer errors. The error says that the email, password, codename (3 strings needed to create a user) are required. But I am sending all three strings. It is because the serializer is NOT valid (go to serializers.py, the if serializer.is_valid() check)... but I can't figure out why it's not valid. Entire said error message: {'codename': [ErrorDetail(string=u'This field is required.', code=u'required')], 'password': [ErrorDetail(string=u'This field is required.', code=u'required')], 'email': [ErrorDetail(string=u'This field is required.', code=u'required')]} All these files are in my users folder within my Django directory. serializers.py: from rest_framework import serializers from .models import User class UserPostSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password', 'codename') views.py: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from .serializers import * from .models import User from argon2 import PasswordHasher import json @api_view(['POST']) def create_user(request): print("inside create_user") """ POST = Create user. """ data = {} # print("request.data:\n", request.data) serializer = UserPostSerializer(data=request.data) print("got serializer") if serializer.is_valid(): print("serializer is valid!") email = serializer.data['email'] codename = serializer.data['codename'] password = serializer.data['password'] user = User.objects.filter(email=email) if not user: # Apply Argon2 … -
Modify QuerySet data and return a paginated QuerySet in Django REST API
I want to create an API endpoint that returns all upcoming products. If a product is upcoming is determined by the values release_date and timezone. To reduce the database load I want to return a paginated result. The problem is that I need to call a function on every entry that can't be achived by SQL (as far as I know). The following code works but it's very inefficient because first I load all data from the database, then I filter it by calling the is_upcoming() function and then I'm creating another queryset with the filtered products. Is there a way to improve the code so to make the filtering directly in the query? # views.py class ListProducts(ListAPIView): # ... def get_queryset(self): products = Product.objects.all() upcoming_products = [product.pk for product in products if product.is_upcoming()] return Product.objects.filter(pk__in=upcoming_products) # models.py class Product(models.Model): # ... release_date = models.DateTimeField() timezone = timezone = models.CharField(max_length=100, choices=TIMEZONE_CHOICES) def is_upcoming(): timezone = pytz.timezone(self.timezone) return now().astimezone(tz) < self.release_date.astimezone(tz) -
Searching for a Python-Mentor
I am currently learning Python with Mosh's Python online course on codewithmosh.com and I was wondering if there is someone who would be interested in becoming "a mentor". What would that mean? In case that I have questions, I would send you a message on Discord, WhatsApp, .. (whatever you prefer) to get some help. Maybe you could even teach me some stuff. Therefore, If I learn the language, we could maybe start projects together and I could help you as much as I can in return - while learning. There are probably people who think this is a waste of time and it is totally fine for me if you have that opinion, but I would like to please you to accept my request and not blaming me for it. I am really willed to learn the language, but as a not-native-english speaker it is tough. To make it a bit easier, I am looking for the mentor thingy. If you are interested, just send me a message on Discord (Mievo#6594) or answer on this post. Thank you in advance! :) PS: I'm a 27 year old nurse and student from Germany. -
Improve Django queryset performance when using annotate Exists
I have a queryset that returns a lot of data, it can be filtered by year which will return around 100k lines, or show all which will bring around 1 million lines. The objective of this annotate is to generate a xlsx spreadsheet. Models representation, RelatedModel is manytomany between Model and AnotherModel Model: id field1 field2 field3 RelatedModel: foreign_key_model (Model) foreign_key_another (AnotherModel) Queryset, if the relation exists it will annotate, this annotate is very slow and can take several minutes. Model.objects.all().annotate( related_exists=Exists(RelatedModel.objects.filter(foreign_key_model=OuterRef('id'))), related_column=Case( When(related_exists=True, then=Value('The relation exists!')), When(related_exists=False, then=Value('The relation doesn't exist!')), default=Value('This is the default value!'), output_field=CharField(), ) ).values_list( 'related_column', 'field1', 'field2', 'field3' ) -
Django queries with cursor slow
I have a problem with some queries that are taking 15 seconds onwards (it is a lot) with cursor in Djando (without using orm because it takes even more) and directly in mysql it takes 4 or 5 seconds, which I think I can be affecting cursor = connection.cursor() cursor.execute("select m.ub ,m.eq , MONTH(m.fecha) as fecha, AVG(m.cantidad) as cantidad , e.contt from mytable as m left join table2 as e on e.id = m.equipo_id where m.equipo_id = %s and m.udm = 8 and YEAR(m.fecha) = %s GROUP BY MONTH(m.fecha)",[eq,anio]) -
Configure Django's builtin authentication to use a different template folder other than "registration"
When using Django's built-in authentication mechanism, how can I configure it to look for template pages like login.html in a different directory besides "registration"? -
Django get model field
I am trying to select a user_id base on the user that was selected and then pass the user_id to another function to perform some calculation for the selected user when a form entry is saved. But I am not sure how to accomplish that. When a new entry is added and save (add_monthly_entitlement) and the form is saved, I want to pass the selected user_id to another method to perform some calculation. class month_and_year(models.Model): user = models.ForeignKey(User, default='', on_delete=models.CASCADE) Month = models.CharField(max_length=100, default="", null=True) Year = models.CharField(max_length=100, default='') def __str__(self): return self.user.first_name @login_required() def add_monthly_entitlement(request): if request.POST: entitlement_form = update_entitlement_form(request.POST) my_field = month_and_year._meta.get_field('user_id') if entitlement_form.is_valid(): calculate_monthly_entitlement(my_field) entitlement_form.save() return HttpResponseRedirect('/staff_balances') else: entitlement_form = update_entitlement_form args = {} args.update(csrf(request)) args['form'] = entitlement_form return render(request, 'update_entitlement_form.html', args) def calculate_monthly_entitlement(get_id): get_id = get_id get_leave_balance_id = Leave_Balance.objects.get(user_id=get_id) get_entitlement_id = monthly_entitlement.objects.get(user_id=get_id) get_leave_balance_id.Leave_current_balance = get_leave_balance_id.Leave_current_balance + get_entitlement_id.entitlement get_leave_balance_id.save() -
Django count objects field
I need to create a field that count the number of registered books of each own library. Each book is related to a library by a ForeighKey If I register or delete a book it should update automatically in a "book_count" field related to your own library. I tried it: libraries/models.py from django.db import models from books.models import Books class Libraries(models.Model): name = models.CharField(max_length=50) book_count = models.IntegerField(default=0) def save(self, *args, **kwargs): self.book_count = self.Books.count() super(User, self).save(*args, **kwargs) def __str__(self): return self.name books/models.py from django.db import models from libraries.models import Libraries class Books(models.Model): library = models.ForeignKey(Libraries, on_delete=models.DO_NOTHING, blank=True, null=True) book = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.book But return this error: from libraries.models import Libraries ImportError: cannot import name 'Libraries' How can I create this simple book counter in the model of each library?