Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when I try to render tags I get Wallpaper.Wallpaper.None
views.py def download(request, wallpaper_name): try: wallpaper = Wallpaper.objects.get(name=wallpaper_name) similar_wallpapers = wallpaper.tags.similar_objects()[:2] except Exception as exc: wallpaper = None similar_wallpapers = None messages.error = (request, 'Sorry! data does not exist') context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers} return render(request, 'Wallpaper/download.html', context) models.py class Tags(models.Model): tag = models.CharField(max_length=100) def __str__(self): return self.tag class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = TaggableManager() Device_Choices = [ ('PC', 'pc'), ('mobile', 'mobile') ] Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC') image = models.ImageField(upload_to='Wallpaper/Images/', default="") def __str__(self): return self.name download.html <div class="tag"> <h3>Tags</h3> <ul> <li>{{wallpaper.tags}}</li> </ul> </div> I want all the tags of that particular wallpaper to be rendered and if possible please tell me if there is any other way to handle tags, because using taggit its very difficult i am getting manny errors -
django multiple random questions with same answer options
Have this small app with a model for questions and their answers are picked from a tuple. My current challenge is to display the questions with a dropdown for the answers using a modelform. Once submitted the form should save noting the question id and answer option selected. class Question(models.Model): question = models.CharField(max_length=100) active = models.BooleanField(default=True) class Answer(models.Model): answer_options = [ ('EM', 'Exceeded Expectations'), ('ME', 'Met Expectations'), ('BE', 'Below Expectations'), ] question = models.ForeignKey(Question, blank=True, Null=True, on_delete=models.CASCADE) answer_selected = models.CharField(max_length=20, choices=answer_options, default='ME') The form layout is as follows: Question 1 Answer option dropdown Question 2 Answer option dropdown Kindly assist -
Django Handling Public API use (anonymouse users making calls to API)
I am making a simple website with as Django as backend. Ideally, you should be able to use it without creating an account and then all of your saved items ('notes') in there would be visible to anyone. For now I have created a dummy user on Django, and every time an anonymous user makes an API call to add/delete/modify a notes, on Django's side it selects dummy user as a user. It would work okey (I think) but one of Django's API can take a really long time to run (~1-2 minutes). Meaning that if multiple people are trying to make API calls while being anonymous, at some point the server will freeze until the long API finishes run. Is there a way such case should be handed on the server side to prevent freezing of server ? -
Reverse for 'tutorial_home' with arguments '('',)' not found. 1 pattern(s) tried: ['tutorial/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
Reverse for 'tutorial_home' with arguments '('',)' not found. 1 pattern(s) tried: ['tutorial/(?P[-a-zA-Z0-9_]+)/\Z'] views.py from django.shortcuts import HttpResponse, render from tutorial.models import IndexTutorial # Create your views here. def tutorial_home(request, slug): main_topic = IndexTutorial.objects.filter(slug=slug).first() print(main_topic) context = {'main_topic':main_topic} return render(request, 'tutorial/main.html', context) urls.py from django.urls import path from .import views app_name = 'tutorial' urlpatterns = [ path('<slug:slug>/', views.tutorial_home, name='tutorial_home'), ] index.html <div class="position-absolute bottom-0 start-0 w-100"> <a href="{% url 'tutorial:tutorial_home' main_topic.slug %}" class="btn btn- danger d-block rounded-0">Start Learning</a> </div> -
How to specify the value column for CSV output of data model with ForeignKey in Django
I would like to export CSV file of a Django Model that is using ForeignKey. By default, the file is exported with ID value of ForeignKey model, but I want have other column's data as value of the CSV file. Here is example models.py class Task(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) assign = models.ForeignKey(Member, on_delete=models.CASCADE) class Member(models.Model): name = models.CharField(max_length=100) role = models.CharField(max_length=100) views.py def export_to_csv(request): task = task_set.all() task_list = task.values() df = pd.DataFrame(list(task_list.values())) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=task.csv' df.to_csv(path_or_buf=response) return response If I implement as above, column for Member model would be ID. But I want to have name column of Member model on CSV file. Thank you! -
django pytest --log-level not works
I have .ini file where specified -s --log-level=WARNING And in django's settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(asctime)s [%(levelname)s] " + " %(module)s - %(name)s: %(message)s", }, }, "handlers": { "console": { "level": "WARNING", "class": "logging.StreamHandler", "formatter": "verbose", }, }, "loggers": { "": {"handlers": ["console"], "level": "INFO", "propagate": False}, }, } But logger.info is being seen in pytest running -
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