Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add url custom items to the apps menu in the Django admin?
i want add custom url in left menu Django admin -
How to create a dataframe from a nested JSONField in Django?
My Django model has a DateTimeField and a JSONField fields I would like to create a timeseries dataframe with. The package django-pandas has a method to_timeseries to do that but my problem is that it puts all the JSONField field into a column. How can I flatten this column into multiindexed columns ? models.py class Indicator(models.Model): dt = models.DateTimeField(null=True) metrics = models.JSONField(default=dict) JSONField dictionary: {'housing': {'1d_percent': 73.62755998, '2d_percent': 3e-08}, 'fund-flower': {'ratio': 0.01981295}, 'mpi': {'mpi': -0.6527736158660562}} Converting queryset to a timeseries dataframe : >> qs = Indicator.objects.all() >> qs.to_timeseries(index='dt', fieldnames='metrics').sort_index().dropna() metrics dt 2018-01-01 00:00:00+00:00 {'mpi': {'mpi': -0.01679772442974948}, 'fund-f... 2018-01-02 00:00:00+00:00 {'mpi': {'mpi': 1.1785319016689795}, 'fund-flo... 2018-01-03 00:00:00+00:00 {'mpi': {'mpi': 1.047678402830424}, 'fund-flow... 2018-01-04 00:00:00+00:00 {'mpi': {'mpi': 1.111703887319459}, 'fund-flow... 2018-01-05 00:00:00+00:00 {'mpi': {'mpi': 2.3908629334035343}, 'fund-flo... ... 2022-09-17 00:00:00+00:00 {'mpi': {'mpi': -1.0434999082318062}, 'fund-fl... 2022-09-18 00:00:00+00:00 {'mpi': {'mpi': -0.9680468633746766}, 'fund-fl... 2022-09-19 00:00:00+00:00 {'mpi': {'mpi': -0.9287818619840235}, 'fund-fl... 2022-09-20 00:00:00+00:00 {'mpi': {'mpi': -0.8487296227267782}, 'fund-fl... This is the desired output: mpi fund-flower housing dt mpi ratio 1d_percent 2d_percent 2018-01-01 00:00:00+00:00 value value value value 2018-01-02 00:00:00+00:00 value value value value 2018-01-03 00:00:00+00:00 value value value value 2018-01-04 00:00:00+00:00 value value value value 2018-01-05 00:00:00+00:00 value value value value ... 2022-09-17 00:00:00+00:00 value value value value 2022-09-18 00:00:00+00:00 value value … -
Django - annotating a field to a model query which adds a datefield value to an existing model field in views
I want to add a field to my model in views without adding it to the database using the annotate function. user_accounts_extension.objects.filter(types='trial').annotate(expire_date=duration + datetime.timedelta(days=180)) The model user_accounts_extension is an extension of the included auth models. "Duration" is a datefield which represents the date when the account is closed. I want my view to render this field + 180 days to my template - but the above code doesn't work. I've also tried: user_accounts_extension.objects.filter(types='trial').annotate(expire_date='duration' + datetime.timedelta(days=180)) To no avail. Is this possible to do, or do I need to add a new field to my model? -
Django: Best practice to sum all total amounts based on a model field
Here is my code reports: queryset for reports in reports: data.append(DataModel( model_id=report.num, title=report.title, total_price=report.total_amount, )) This code will create some DataModel objects and will append the object into a list. I want to sum total_price of all the objects with the same obj.id. For example: If we have these objects on the queryset: id:obj1 total_price: 10 id:obj3 total_price: 20 id:obj2 total_price: 30 id:obj1 total_price: 40 id:obj2 total_price: 50 In the list I want to have these object in the list: id:obj1 total_price: 50 id:obj3 total_price: 20 id:obj2 total_price: 80 What is the best practice to do that? -
Wagtail 2.14.2 ModulNotFound error after running makemigrations
3rd try of wagtail I did install it after having created a virtual environment named wag-env with virtualenv within the directory websites/wag/, not in the .virtualenv folder. Command was "virtualenv wag-env". Did pip install wagtail Then ran wagtail start ready_wag I then ran python3 manage.py makemigrations and get this error messages "ModuleNotFound error wagtail.models". A check in the lib confirmed that there is a models folder at wagtail root level, but no models.py. That's my third try since yesterday, first was with mkvirtualenv, had the same problem, second was with virtualenv, trying to integrate a finished django project, and now trying to start a project from scratch. I ran a pip freeze --user, there's a wagtail installed globally. Should I get rid of it ? Thanks in advance for your answers -
django inspectdb, foreignkey from different schema
in schema_curriculum & table clearance_item I added a constraint(ForeignKey) to schema_srgb & table_student then, I try to run inspectdb with the following command py manage.py inspectdb --database=curriculum clearance_item > models.py class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' I was hoping studid should change from CharField to ForeignKey, is it possible to form a connection from db1.schema2 > db.1schema1 tables -
Why am I getting "Invalid salt" in django?
I have written a code for registration and login in django. While doing login, I am getting the error "Invalid salt" Following is the code: @api_view(['POST']) def login(request): email = request.data.get('email') mobile_number = request.data.get('mobile_number') pin = request.data.get('pin') res = dict() print(dict, "dictonaryyyyyy") if email != None: email_result = Users.objects.filter(email= email).first() print(email_result.pin, "emaillll") if email_result != None: if bcrypt.checkpw(pin.encode("utf-8"), email_result.pin.encode('utf-8')): # if bcrypt.checkpw(pin, ) print("........") payload_data = dict() payload_data['email'] = email_result.email token = generate_token(payload_data) print(token, "token.........") res['messages'] = "Authentication Successful" res['status'] = 200, res['token'] = token return Response(res, status = status.HTTP_200_OK) ... ... How to get rid of this error? -
Automatic avoidance of category duplicates
I have the problem with Category Model. I have 2 tables: class Category(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False) class Movie(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False) so they are standard models with categories. User can create Category by creating a movie with the name of category additionaly. The problem is when user is trying to create Movie with category name that already exists, because it will create another category with the same name (like duplicate) and I want to avoid it. How to do it? I can't create unique name field, because many users can have same category (but I can use ManyToManyRelation) but still I don't know how to automatically avoid duplicates like bellow: If Category with that Name and this User does not exist > create Category If Category with that Name and this User exists > use this Category Regards -
How to Redirect tenant to subdomain home page after user can login in public schema
I have to redirect to home page without login in subdomain after login in public tenant That means suppose - public domain is : logic.com subdomain is : tenant1.logic.com I have tried to login to the public domain (logic.com/login) so now I have to redirect to the home page of the subdomain(tenant1.logic.com/home) Without subdomain login def login_user(request): if request.method == 'GET': return render(request, 'users/login-user.html', {'form': AuthenticationForm()}) else: user = authenticate(request, username=request.POST['email'], password=request.POST['password']) if user is None: return render(request, 'users/login-user.html', {'form': AuthenticationForm(), 'error': 'Username and ' 'password did not ' 'match'}) else: client = Client.objects.filter(owner=user).first() with schema_context(client.schema_name): login(request, client.owner) host = request.META.get('HTTP_HOST', '') scheme_url = request.is_secure() and "https" or "http" url = f"{scheme_url}://{client.slug}.{host}" return HttpResponseRedirect(url) What can I do if anyone has know about this? Thanks in advance -
What are the technologies i have to use to bulid news website and app with live news streaming option
what are the technologies required, is it possible with using Wordpress -
how to mail an image stored in an array variable as attachment without saving it on the drive
I have an image stored in the memory as a NumPy array format( stored in a NumPy array variable). I want to mail this image as an attachment to a user without saving it on my drive. Is there a way for doing this? I have tried various codes but have not gotten the mail. can someone help me with this? any help is truly and sincerely appreciated. -
From a list of dictionaries in python Django how to filter/find and highest valued prize per user per day
I want to find out per day per user what is the highest prize he has won my_list = [{'id': 1, 'user_id': 4, 'date': datetime.datetime(2022, 9, 9), 'prize': '45.00'}, {'id': 2, 'user_id': 5, 'date': datetime.datetime(2022, 9, 5), 'prize': '85.00'}, {'id': 3, 'user_id': 5, 'date': datetime.datetime(2022, 9, 5), 'prize': '35.00'}, {'id': 4, 'user_id': 4, 'date': datetime.datetime(2022, 9, 9), 'prize': '95.00'}, {'id': 5, 'user_id': 3, 'date': datetime.datetime(2022, 9, 9), 'prize': '10.00'}, {'id': 6, 'user_id': 6, 'date': datetime.datetime(2022, 9, 5), 'prize': '15.00'}] the result should be as below result = [{'id': 2, 'user_id': 5, 'date': datetime.datetime(2022, 9, 5), 'prize': '85.00'}, {'id': 4, 'user_id': 4, 'date': datetime.datetime(2022, 9, 9), 'prize': '95.00'}, {'id': 5, 'user_id': 3, 'date': datetime.datetime(2022, 9, 9), 'prize': '10.00'}, {'id': 6, 'user_id': 6, 'date': datetime.datetime(2022, 9, 5), 'prize': '15.00'}] In above Example user_id=4 have 2 prizes on date(2022, 9, 5) i.e $45 and $95. Among these 2 we have to pick the highest valued record $95 -
Error when returning JsonResponse(). Django
It's returning error when i use instance or without that in JsonResponse. Maybe JsonResponse cannot serialize data. The error is Traceback (most recent call last): File "/Users/admin/Documents/Projects/food/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/admin/Documents/Projects/food/venv/lib/python3.10/site-packages/django/utils/deprecation.py", line 138, in call response = self.process_response(request, response) File "/Users/admin/Documents/Projects/food/venv/lib/python3.10/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'tuple' object has no attribute 'get' I couldn't find source of error. I tried to solve that with helping google. But I did't find any exact solution. Yes tuple doesn't have a method get. views.py class CreateCategoryAjaxView(View): def post(self, request, *args, **kwargs): form = CategoryForm(request.POST, request.FILES) if form.is_valid(): instance = form.save() return JsonResponse( {'is_success': True, 'id': instance.id, 'title': instance.title}), return JsonResponse({'is_success': False, 'errors': form.errors}) forms.py class CategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' widgets = { 'title': forms.TextInput( attrs={'placeholder': ' Пиццы...', 'class': 'form-control', 'id': 'id_category_title'}), 'image': forms.FileInput(attrs={'accept': 'image/*', 'id': 'id_category_image'}), } -
What's the difference between get_user_model() and importing CustomUser model directly?
This is my views.py in a API server running Django REST framework. from rest_framework import generics from users.models import CustomUser from .serializers import CustomUserSerializer class PCAPIView(generics.ListAPIView): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer This code works fine. However, when I google around, I discovered that the recommended way is to use get_user_model(). So, the proper views.py should look like this; from rest_framework import generics from django.contrib.auth import get_user_model from .serializers import CustomUserSerializer class PCAPIView(generics.ListAPIView): queryset = get_user_model().objects.all() serializer_class = CustomUserSerializer I tested and both code worked as I wanted. What is the difference between the 2 code? Is get_user_model() really better? I am using django v4, python 3.9, django rest framework. -
I am currently using django 4.0 getting this error while including ('rest_auth.urls')
from django.contrib import admin from django.urls import path,include from Users.urls import * from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path("",include("Users.urls")), path('api/v1/rest-auth/', include('rest_auth.urls')), ] Error:-ImportError: cannot import name 'url' from 'django.conf.urls' -
Use diffrent model for users who login with django google allauth login
I am using Custom User model for only admins but I have to create seperate login sysytem for clients who uses django allauth google login system and these clients have below model: class ClientUser(models.Model): username = models.CharField(max_length=50, blank=True, null=True, unique=True) email = models.EmailField(("email address"), unique=True) first_name = models.CharField(max_length=50, blank=True, null=True, unique=True) last_name = models.CharField(max_length=50, blank=True, null=True, unique=True) phonenumber = models.CharField(max_length=15, null=True) def __str__(self): return "{}".format(self.email) How could I make google allauth use this model? -
how to set django datatable in dropdown manue in admin pannel?
I need help in django admin custom designing. I have datatables for example blog tables in one dropdown scubscription tables on other. I have shared screen short of my datatables. here GSMAPP datatables that I want to divide in some dropdown.any suggestion please -
How can I access form(in template) which is defined in another app(views) in Django
New to Django. So please help me. What my goal here is that I want to access form from another application(cart) to my current application(shoppApp). views.py(cart application): from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shoppApp.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product,quantity=cd['quantity'],update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id,slug=slug,available=True) cart_product_form = CartAddProductForm() return render(request,'shop/product/detail.html',{'product': product,'cart_product_form': cart_product_form}) forms.py(cart application) from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES,coerce=int) update = forms.BooleanField(required=False,initial=False,widget=forms.HiddenInput) details.html(shoppApp application) {% extends "shop/base.html" %} {% load static %} {% block title %} {{ product.name }} {% endblock %} {% block content %} <div class="product-detail"> <img src="{% if product.image %}{{ product.image.url }}{% else %}{% static 'img/no_img.jpg' %}{% endif %}"> <h1>{{ product.name }}</h1> <h2><a href="{{ product.category.get_absolute_url }}">{{product.category }}</a></h2> <p class="price">${{ product.price }}</p> <form action="{% url 'cart:cart_add' product.id %}" method="post"> … -
How to set port in Django channels websocket
I am working on Django project and built Chat application, now troubling with websocket port, when i start chat with any one person the default port generating and i leave that user and chat with other user port is changing so i can't receive other person message notification because of port changing every time so please help for that consumers.py class PersonalChatConsumer(WebsocketConsumer): def connect(self): my_id = self.scope['user'].id other_user_id = self.scope['url_route']['kwargs']['id'] if int(my_id) > int(other_user_id): self.room_name = f'{my_id}-{other_user_id}' else: self.room_name = f'{other_user_id}-{my_id}' self.room_group_name = 'chat_%s' % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def receive(self, text_data=None, bytes_data=None): data = json.loads(text_data) message = data['message'] email = data['email'] data_base = self.save_message(email, self.room_group_name, message) print("This is a database output", data_base) print(text_data) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message, 'email': email, } ) def chat_message(self, event): message = event['message'] user_id = event['email'] user_obj = User.objects.get(id=user_id) self.send(text_data=json.dumps({ 'message': message, 'email': user_obj.email, 'user_id': user_id })) print(f"{user_obj.email} : Messaage sent") def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # @database_sync_to_async is used with asynchronous code def save_message(self, email, thread_name, message): sendername = User.objects.get(id=email) sender_name = str(sendername) my_id = self.scope['user'].email new_message = ChatModel.objects.create(sender=email, sender_name=sender_name, receiver_name=my_id, message=message, thread_name=thread_name) new_message.save() return "Succes" setting.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
how to find value in (txt) python string
i'm new to python world and i'm trying to extract value from text. I try to find the keyword by re.search('keyword') , but I want to get the value after keyword text = word1:1434, word2:4446, word3:7171 i just want to get the value of word1 i try keyword = 'word1' before_keyword, keyword, after_keyword = text.partition(keyword) print(after_keyword) output :1434, word2:4446, word3:7171 i just want to get the value of word1 (1434) -
How can I authenticate a user who belongs to another database in my other service in django rest framework?
I'm new to django and I am required to create two microservices with separate databases; One to hold user information and the other to hold todo/tasks information. So far, I have created two separate projects with two separate databases, To authenticate the user using simplejwt authentication. (todo_auth project with todo_auth database) To show the todo/task information specific to that user. (todo project with todo database) Once I login the user in the todo_auth project I need the todo project to detect that I have logged in the user when I pass in the jwt token that I got when I logged into the todo_auth project. How can I achieve this? Many thanks. PS: I'm running the two django projects on the same server with different port numbers. -
Is it possible for django template url direct to another project?
I have two projects called blog, user_auth, both are all django projects. In blog project, I need to do a user authentication. Of course we can do it in current blog project like the following. <span class="sign-in"> <a href="{% url 'blog:sign-in' %}">sign-in</a> </span> <span class="sign-up"> <a href="{% url 'blog:sign-up' %}">sign-up</a> </span> The question is if we have more projects which also need to do user authentication, we will have many repeated codes. Here user_auth project is to manage all the projects' user authentication. My question is if we can use {% url %} in a templates in blog project to direct to user_auth project? -
How do I allow a user to to select an arbitrary number of 'n' languages during account registration?
Suppose I am creating the next language learning application like Duolingo. Initially during the account registration process, the user can select up to 5 studying languages. At a later time, a user can subscribe to a premium subscription and set up to N number of languages in a different page like in their account settings. These selected languages will eventual filter a user's feed. How should I go about this in the proper way? What would something like this be called, so that I can read more about it in the documentation. Thank you kindly. It would be nice if I could define the allowed number directly in the settings file: STANDARD_USER_LANGUAGE_ALLOWANCE = 3 SUBSCRIBED_USER_LANGUAGE_ALLOWANCE = 5 Method 1 (Most likely terrible and not DRY): class User(AbstractUser): // Manually list all of them here and keep adding in the future language1 = ... language2 = ... language3 = ... class Language(models.Model): name = models.CharField( max_length=20, ) short_name = models.CharField( max_length=20, ) def __str__(self): return self.name class Meta: ordering = ['name'] Method 2 (Maybe use a ManyToMany relationship with a multiple checkbox as the widget)? Would this even be a good application of ManyToMany? class User(AbstractUser): languages = models.ManyToManyField(Language) -
Django annotate count for another queryset
Models: class Regions(models.Model): name = models.CharField(max_length=255, unique=True) class Owners(models.Model): name = models.CharField(max_length=255, null=False, unique=True) url = models.URLField(null=True) class Lands(models.Model): region = models.ForeignKey(Regions, on_delete=models.CASCADE) owner = models.ForeignKey(Owners, on_delete=models.PROTECT, null=True) description = models.TextField(max_length=2000, null=True) class LandChangeHistory(models.Model): land = models.ForeignKey(Lands, on_delete=models.CASCADE, null=False, related_name='lands') price = models.IntegerField() size = models.IntegerField() date_added = models.DateField(auto_now_add=True) Queryset that works but i need it to be annotated in another queryset somehow: lands_in_region = Lands.objects.values('region__name').annotate(count=Count('region_id')) returns for example: {'region__name': 'New York', 'count': 3}, {'region__name': 'Chicago', 'count': 2} In the 2nd queryset i need count of lands available in region. But instead of real count, i always get count = 1. How to combine them? Im pretty sure i could do it in raw sql by joining two tables on field "region__id", but dont know how to do it in django orm. f = LandFilter(request.GET, queryset=LandChangeHistory.objects.all() .select_related('land', 'land__region', 'land__owner') .annotate(usd_per_size=ExpressionWrapper(F('price') * 1.0 / F('size'), output_field=FloatField(max_length=3))) .annotate(count=Count('land__region_id')) ) For example. If it returns: land1 | 100$ | 100m2 | New York land2 | 105$ | 105m2 | New York land3 | 102$ | 102m2 | Chicago i need 1 more column, that counts for each land how many NewYork's and Chicago's are there land1 | 100$ | 100m2 | New York … -
Refused to execute script ... MIME type ('text/html') is not executable, and strict MIME type checking is enabled -- django reactjs whitenoise heroku
im currently in the process of deploying (read: struggling) my: django(backend) react-js/redux(frontend) django-ninja(api) whitenoise(backend - staticfiles) app to heroku. however, i keep getting this error message whenever i launch the app and go live: "Refused to execute script from 'https://off-world-v0.herokuapp.com/static/js/main.6b71531f.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled." "Manifest: Line: 1, column: 1, Syntax error." This error does NOT appear when im in development, so after spending the past 2 days crawling stackoverflow, reddit, youtube, etc. - a number of other individuals seem to be running into the same problem, yet no reliable answer (to my knowledge) has been postulated at this time. The strange part is the app did work on one try after i removed this line from the build/static "index.html" file: <link rel="manifest" href="./manifest.json"/> However, after updating and launching the app again the same errors came back, this time with a different staticfile asset as the source of the error. Attached below are some snippets of my code. Any insight or help would be greatly appreciated and would come with gifts/tributes/alms/bounty of your choosing to be delivered in the afterlife. django settings.py import os from pathlib import Path from dotenv …