Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django handling different databases per country
I have a question related to Django handling different databases. I have this doubt because, I need to create a database for different countries. And, my webapp has one dns, and only one. I want to be able to handle different countries with the same dns. I have this questions in my mind but, I don't know which one is the best practice for this kind of situations... 1- In a Django Project create different apps, for each country and use a Database Router to differentiate. As: if model._meta.app_label == 'customer_data': return 'customer_db' 2 - Store a db name on session and when user logs in, sends every requests to the database related to the user. (don't have any clue of how to do this) I don't know what else I can do, besides the ones I described above. Any senior django developer, can help me with this question? and, if possible provide articles which can help me understand better... Thank you. -
Display all the uploaded files in browser in a div
I am currently working on a Django project so when customers upload a file i will store in my local disk and there is a seperate page for admin, I thought of displaying files uploaded by many users , is there any way to acheive that ?? -
Sorting by generic relations - django-generic-aggregation alternative for large querysets?
My models: class Article(models.Model): title = models.CharField(max_length=255) # reverse generic relation comments = GenericRelation(Comment, object_id_field='object_pk') class Comment(models.Model): comment = models.TextField() content_type = models.ForeignKey(ContentType, verbose_name=_('content type'), related_name="content_type_set_for_%(class)s", on_delete=models.CASCADE) object_pk = models.TextField(_('object ID')) content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk") I'd like to sort articles by number of comments. So far I have been using django-generic-aggregation (https://django-generic-aggregation.readthedocs.io/en/latest/) library and did the following: qs = generic_annotate( self.queryset, Comment.objects.filter(public=True), Count("comments__comment")) This approach worked fine when the number of articles was small. As the number of articles increases (over 10-20.000), it is getting too slow. Any ideas for an alternative how to sort a list of articles by number of comments, if the list of articles is large? -
How would I write this regular expression url pattern with path in django?
I am following a beginner django tutorial and my django version is set up to use path instead of the url and I am unsure how to write this code using path: url(r'^?P<album_id>[0-9]+,views.detail()) -
How to show FK fields in admin? DJANGO
I'm developing an e-commerce site and I'm trying to show in my ADMIN the 'produto_nome' related in my 'Ordem' table. For now, in my admin, in the 'Ordem' table, it's just showing the id of each object. Is it possible to show field 'produto_nome' in that table? Below is my models class Categoria(models.Model): nome = models.CharField(max_length=50) def __str__(self): return self.nome class Produto(models.Model): produto_nome = models.CharField(max_length=70) preco = models.IntegerField() quantidade_em_estoque = models.IntegerField() quantidade_vendida = models.IntegerField() categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) descricao = models.TextField(default='', blank=True, null=True) slug = models.SlugField(unique=True) image = models.ImageField(upload_to="products/%Y/%m/%d", blank=True, null=True) def __str__(self): return self.produto_nome def get_absolute_url(self): return reverse('produto:produto_detail', kwargs={'slug': self.slug}) class Ordem(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, blank=True, null=True) data_pedido = models.DateTimeField(auto_now_add=True, null=True, blank=True) enviado = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) def get_total_preco(self): total = 0 for pedido in self.produtos_itens.all(): total += pedido.get_total_item_preco() return total class OrdemItem(models.Model): produto = models.ForeignKey(Produto, on_delete=models.SET_NULL, blank=True, null=True) ordem = models.ForeignKey(Ordem, on_delete=models.SET_NULL, blank=True, null=True) quantidade = models.IntegerField(default=0, null=True, blank=True) data_add = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): return f'{self.quantidade} unidade de {self.produto.produto_nome}' def get_total_item_preco(self): return self.quantidade * self.produto.preco -
MultiValueDictKeyError on clicking of Unsubscribe in Sendgrid dynamic template
I created on dynamic template for my newsletter app and added custom unsubscribe link and passing uri to template with api in dynamic_template_data but when I click on unsubscribe line it throws error MultiValueDictKeyError at /delete/ Code for ref: models.py class Newsletter(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subject = models.CharField(max_length=150) contents = RichTextUploadingField(blank=True, null=True, extra_plugins= ['youtube', 'imageresize', ], external_plugin_resources= [('youtube', '/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js')]) def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") def send(self, request): contents = self.contents uri = request.build_absolute_uri('/delete/') subscribers = Subscribers.objects.filter(confirmed=True) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) template_id = "d-xxxxxxxxxxxxxxxxxx" for sub in subscribers: message = Mail( from_email=settings.FROM_EMAIL, to_emails=[sub.subscriber_mail], subject=self.subject) message.dynamic_template_data = { "xar_text": "Join Our Elites Club", "uri": uri } message.template_id = template_id sg.send(message) Views.py def delete(request): sub = Subscribers.objects.get(subscriber_mail=request.GET['email']) if sub.subscriber_mail == request.GET['email']: sub.delete() return render(request, 'frontend/unsubscribed.html', {'email': sub.subscriber_mail, 'action': 'unsubscribed'}) else: return render(request, 'frontend/error.html', {'email': sub.subscriber_mail, 'action': 'denied'}) urls.py from django.urls import path from . import views urlpatterns = [ path('subscribe/', views.subscribe, name='subscribe'), path('delete/', views.delete, name='delete'), ] Custom Sendgrid template code: <a href="{{uri}}" style="text-align:center">Unsubscribe</a> Error: Internal Server Error: /delete/ Traceback (most recent call last): File "C:\Users\ASUS\python_workspace\projects\venv\env\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'email' During handling of the above exception, another exception occurred: Traceback … -
how to run a forloop in django views.py?
i want to interate over queryset and if there is a new user added, i want to add some points for a specific user. To be more clear with what i am building: => I am writing a referral system logic in django. The referral system works fine now, but what i want to implement is this. When i refer a user which are "user 2" and "user 3", it is stored that i have refered two users, now i have also implemented a way to know if "user 2" or "user 3" which are refered by me: have gotten a new user refered by them ("user 2" or "user 3"). Now what i want to achieve is this, when there is a new user from "user 2" or " user 3 " i want to add a some points to the "user 1" which refered the two user ("user 2" and "user 3") that referred the new users. I am thinking of using a forloop to iterate over the second_level_recommended, then add the point to the profile but it doesn't seem to work or maybe the code that i wrote was wrong. This is the code that i wrote … -
How to Fix Cannot resolve keyword 'date_added' into field?
the BUG : Cannot resolve keyword 'date_added' into field. Choices are: date, entry, id, owner, owner_id, text here s My Models : from `django`.db import models from `django.contrib.auth`.models import User class Topic(models.Model) : text = models.CharField(max_length=200) date = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.text class Entry(models.Model) : topic = models.ForeignKey(Topic,on_delete=models.CASCADE) text = models.CharField(max_length=200) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): return self.text[:50] + "..." heres My Views functions def topics(request) : topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics':topics} return render(request, 'learning_logs/topics.html', context) -
Fastest way to learn django [closed]
I am learning Django from the past 3 months and I am still at very beginner level. Like I can make class / functions / U r l s and I can take input output from user. I can manage models and database. I can do a little bit of html as well ( copying bootstrap ) ! What will be the fastest way to learn Django and come to intermediate level ? Any tips and suggestions will be highly appreciated. -
ImportError: cannot import name 'native' from 'OpenSSL._util'
This problem occurs when I run Django.I guss it related with kms-client-sdk==0.1.5 -
How to get rid of app name in the particular url?
I have this urls.py in my app from django.urls import path, include from rest_framework.routers import DefaultRouter from products import views app_name = 'products' router = DefaultRouter() router.register(r'products', views.ProductViewSet, basename='products') router.register(r'categories', views.ProductCategoryViewSet, basename='categories') router.register(r'brands', views.BrandViewSet, basename='brands') urlpatterns = [ path('', include(router.urls)), ] And this is my project's urls.py from django.contrib.auth import views as auth_views from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LoginView.as_view(template_name='users/logout.html'), name='logout'), path('__debug__/', include('debug_toolbar.urls')), ] urlpatterns += [ ... path('products/', include('products.urls', namespace='products')), ... ] And viewsets: from rest_framework import viewsets, permissions from .models import ( Product, ProductCategory, Brand, ) from .serializers import ProductSerializer, ProductCategorySerializer, BrandSerializer #all other viewsets are the same class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] A router for my app generates urls almost as expected, I can go to 'site/products/categories' for categories 'site/products/brands' for brands BUT for products url is 'site/products/products'. How to make it not to add app name in this case? I want it to be just 'site/products'. -
Date Format in Django views complex sql
I am new in Python Django and love this... but now I need create select to database where I have rows with date in this format 2020-08-21 10:43:26.000000 And I need change this date like as this Month-Day (Jan-02 for example) and after that this column group by... I am try many things what I found here but nothing works... :/ right now my query looks like this... hist_data = Vpnhistory.objects.filter(bytes_sent__gt=0) hist_data = hist_data.filter(end_time__gte=datetime.now()-timedelta(days=14)) hist_data = hist_data.values('end_time', 'bytes_sent') hist_data = hist_data.annotate(summ=Sum('bytes_sent'), end_time_str=DateToChar(F('end_time'), Value('MM-DD'))) and class DateToChar like thisin my model.py class DateToChar(models.Func): arity = 2 function = 'to_char' output_field = models.CharField() Datum still returns with full datetime format .. :/ thank you for help. Stepan -
How to acces a dict with @ in key, in django templates?
i converted a XML file with the follwing line, to a dict, with xmltodict: <drivers> <driver enable="True" guid="{8702bdfa-53b8-4a83-bd01-854293141f11}"> <Name>Intel Net e1d65x64.inf 12.17.8.7</Name> Then i passed the dict to a django template and want to access the guid. In python i can access it with dict["drivers"]["drivers"]["@guid"], since xmltodict, converted the guid key to @guid. However, i cant use {{item.drivers.drivers.@guid}} in django templates. How can i access the guid in templates? -
Django + htmx vs DRF + React
What are Django + htmx limitations compared to DRF + React? I don't know any React and I want to make something by myself. -
How can i compute a result from related models in django
class Function(models.Model): name = models.CharField(max_length=200) def __str__(self): return str(self.name) class Fractions(models.Model): fraction = models.DecimalField( max_digits = 5, decimal_places = 2) def __str__(self): return str(self.fraction) What i am trying to do if Function.name equals = "x" multiply specific Fractions.fraction by 4 and display it in the template -
How to refer or access the custom made permissions in `has_perm()` and `required_permissions`, in Django?
I want to know that how do I refer the custom made permissions in the has_perm() method of User Model and required_permissions attribute of PermissionRequiredMixin Class? Let's say I create the following custom permission: content_type = ContentType.objects.get_for_model(User) Permission.objects.create( codename='custom_permission', name='Custom Permission', content_type=content_type, ) and suppose my django app where I created this custom permission is named as: mycustomapp How will I refer/access this custom permission in has_perm() method and required_permissions attribute? I tried following for has_perm() from django.contrib.auth.models import Permission user = User.objects.all()[0] user.user_permissions.add(Permission.objects.get(name="Custom Permission")) user.save() user.has_perm("mycustomapp.user.custom_permission") But it resulted in False, instead of True, even though running user.user_permissions.all() show the newly added permission and I tried this for required_permissions attribute: class CustomView(PermissionRequiredMixin, View): required_permission = ["mycustomapp_user_custom_permission"] But it does not work and when I go to this View on front-end I get Forbidden 403 error, even though the logged in user has this required permission. Can anyone tell me how do I refer the custom made permission in has_perm() and in required_permissions. Please tell me while considering all the details exactly as I gave above in example. -
How to generate url for the s3 object without expiring?
I have uploaded an object with the client = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) response = client.put_object( Bucket=BUCKET_NAME, Body=in_mem_file.getvalue(), Key=str(img_name)) and I'm generating the URL by url = client.generate_presigned_url('get_object', Params={ 'Bucket': BUCKET_NAME, 'Key': str(img_name)}, ExpiresIn=518400) I need to generate the URL without expiring in some cases. Is it possible to generate url without expiring in s3 bucket? -
Cannot assign "'T Shirt for mens'": "CartProdVarient.cart_product" must be a "CartProduct" instance
Models class CartProduct(models.Model): cart_product_name = models.CharField(max_length=200) cart_holder = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.cart_product class CartProdVarient(models.Model): cart_product = models.ForeignKey(CartProduct, on_delete=models.CASCADE) cart_prod_varient = models.CharField(max_length=200) def __str__(self): return self.cart_prod_varient Views def add_cart(request): prod = Product.objects.get(id=request.POST.get('product_id')) CartProdVarient(cart_product=prod.product_name).save() return render(request, 'app/service-page.html') Problem i want to assign some value to "cart_product" while its a Foreign key but it giving me error.. i want something like this : CartProdVarient(cart_product="T-Shirt", cart_prod_varient="small size").save() T-Shirt is already in "cart_product_name" -
How to add frontend to my backend project (django - Flutter)
how to add frontend (Flutter) to my back this is my backend the project is my django project and store is my django app backend -
CSRF-token error in django+nginx+gunicorn in docker
I have a problem with CSRF-token error in django+nginx+gunicorn in docker: Origin checking failed - http://185.255.132.54:5000 does not match any trusted origins. Such problem on live production server and this problem with dev local server: Forbidden (403) CSRF verification failed. Request aborted. This error appears only with NGINX port (any POST form, login page too (example.com/admin) (5000 for production and 8001 on dev server), but it's ok on gunicorn port (no static). I read some that I have to add CSRF_TRUSTED_ORIGINS = ['http://185.255.132.54:5000', 'http://185.255.132.54', 'https://185.255.132.54:5000'] to production server, but it didn't help. Here's my code: https://github.com/endlessnights/DjangoDockerNginxSample (all files, included Dockerfile, docker-compose, project files etc are there) What have I to do with such problem? -
Django admin get value of selected date range in filter
I wanted to get value of selected date range (from_date, to_date) in Django admin. Here is sample code. list_filter = (('last_login', filters.MyDateTimeFilter),) class MyDateTimeFilter(DateFieldListFilter): title = 'date filter' parameter_name = 'date_range_filter' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def queryset(self, request, queryset): print(queryset.GET.get('date_range_filter')) return queryset -
TabularInline for through Model not showing on Django 3
First off, I am using Django 3.2.9. Here are my models, pretty straightforward: class AChallenge(models.Model): name = models.CharField(max_length=255, unique=True) class SubAdvanced(models.Model): name: str = models.CharField(max_length=255, unique=True) challenges = models.ManyToManyField( AChallenge, related_name = 'challenge', through='SubAdvancedChallenge') class SubAdvancedChallenge(models.Model): sub_advanced = models.ForeignKey( SubAdvanced, on_delete=models.CASCADE) challenge = models.ForeignKey( AChallenge, on_delete=models.CASCADE) percentage = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(1)]) Here is my admin : class SubAdvancedChallengeInline(admin.TabularInline): model = SubAdvancedChallenge extra = 1 class SubAdvancedAdmin(BelleEmpreinteAdmin): inlines = (SubAdvancedChallengeInline,) admin.site.register(SubAdvanced, SubAdvancedAdmin) According to every single tutorial I see on the internet, I should be getting a nice inline editor like this: Despite all this, I am only getting this: If I try to force the inclusion of the "challenges" field, like this: class SubAdvancedAdmin(BelleEmpreinteAdmin): fields = ("name", "challenges") inlines = (SubAdvancedChallengeInline,) I will get the following error: (admin.E013) The value of 'fields' cannot include the ManyToManyField 'challenges', because that field manually specifies a relationship model. The fact that my TabularInline simply does not appear definitely seems like a bug, but it seems too crazy that this slipped through the cracks for so long. Anybody else met this issue? -
Model a 6-digit numeric postal code in django
I would like to define a 6-digit numeric postal code in Django models.py. At first, I tried this; postal_code = models.PositiveIntegerField(blank=False) However, postal codes can have leading zeros such as 000157. PositiveIntegerField is not suitable for it. If I use CharField, the field can accept alphabets which are not valid for postal codes. How do I define a 6-digit numeric postal code in django models.py? I am using Django v4. -
pyreadstat expected str, bytes or os.PathLike object, not InMemoryUploadedFile
Trying to make endpoint that can read uploaded .sav (SPSS) file and create model with data from it. For getting data from it I'm using pyreadstat library. But now when I'm trying to run it I have an error expected str, bytes or os.PathLike object, not InMemoryUploadedFile How I can change this code so pyreadstat can correctly read the given file? from rest_framework import generics, status import pandas as pd import pyreadstat from rest_framework.response import Response from .models import Research, Data from .serializers import FileUploadSerializer, SaveFileSerializer class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] df, meta = pyreadstat.read_sav(file, user_missing=True) json_df = df.to_json(orient='table') rsch = Research.objects.get(pk=1) Data.objects.create(research=rsch, data={}) -
How to define positive integer field that accepts 6 digits only in Django?
I want to define a database field in models.py that accepts only 6 digits in Django. This is how I define the field in models.py but it can accept any positive integer; six_digit_code = models.PositiveIntegerField(blank=False) I am using Django v4.