Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django / pass multiple models to my ListView
Hi everyone.. It's my first project and I'm trying to pass multiple models to my ListView and get them to my template/index via different context_object_names but there're seem to be shortcut or another way to do it that I'm missing models.py from django.db import models class Kunafa(models.Model): name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default=False) class Baklawa(models.Model): name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default=False) class Crunchy_kunafa(models.Model): name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default=False) class Topping(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() enter code here views.py from .models import Kunafa, Crunchy_kunafa, Baklawa, Topping from django.views.generic import ListView `class HomeView(ListView): model = Kunafa template_name = 'index.html' context_object_name = 'Kunafa' ` `class HomeView(ListView): model = Baklawa template_name = 'index.html' context_object_name = 'Baklawa'` `class HomeView(ListView): model = Crunchy_kunafa template_name = 'index.html' context_object_name = 'Crunchy_kunafa'` `class HomeView(ListView): model = Topping template_name = 'index.html' context_object_name = 'Topping'` # index/template {% extends 'base.html' %} {% block body %} `<div class="album py-5 bg-light"> <div class="container"> <div class="row"> {% for kun in Kunafa %} <div class="col-md-4"> <div class="card mb-4 box-shadow"> <img class="card-img-top" src="https://via.placeholder.com/250x200" alt="card image cap"> … -
Why is Heroku PostgreSQL row count much higher than sum of model instances from my Django app?
My Heroku PostgreSQL utilization is showing 32k rows and 20 tables, when I only have 9 different model types in my Django app, and the highest count on any of these model types is <2000. By I figure by this I should have 18,000 items max (and realistically much less because some of these models only have <100 items. Am I misunderstanding how Django models relate to PostgreSQL row counts? Are there other items being stored in the DB that I am not aware of? Thanks! -
Can I access GCS from html in django's html?
I want to read and visualize the pdb file saved in GCS in ngl viewer. The code to read a file in ngl viewer is as follows. function go(){ stage.removeAllComponents() var pdb = document.getElementById('id_pdbid').value var path = "rcsb://" + pdb stage.loadFile(path, {defaultRepresentation: true}) } Here you can simply change the url to something like https://storage.cloud.google.com/example-storage-bucket/folder/example.pdb, but it will cause CORS issues. So I want to access GCS from the script itself in html. (not using url) Is there a way to access it in html, javascript as well as using python's GCS library? Thank you in advance. -
Validating Form for Class-based view
I hope you guys could tell me how to use validation methods in my forms.py for a single field. My view is a generic.FormView and my form is forms.Form. Here is my view: class ClassSetupView(OrganisorAndLoginRequiredMixin, generic.FormView): template_name = "leads/class_setup.html" form_class = ClassSetupForm def get_success_url(self): return reverse("class-setup-sucess-page") def form_valid(self, form): # Some Other Code return super(ClassSetupView, self).form_valid(form) Here is my form: class ClassSetupForm(forms.Form): date = forms.DateField(help_text="Year-01-01",) clean_date(self): date = self.cleaned_data['date'] if date < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) return date I hope you guys could tell me if it is okay to use the clean_date(self) for the form as a way to validate the field date. I saw several examples online, but I am not sure if clean_date(self) will work for my case. Thank you. -
Django model modification
Ok, i have this django app, where the user fills in their detail and then create a web profile(username and password) from django.db import models class UserDetail(models.Model): first_name = models.CharField(max_length=225) middle_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255) email = models.EmailField() def __str__(self): return self.first_name class WebDetail(UserDetail): # user = models.OneToOneField(UserDetail, on_delete=models.CASCADE, primary_key=True,) username = models.CharField(max_length=255) password = models.CharField(max_length=255) and when i create a user that has a webdetail, it shows empty in the database(django admin) I need help to link the WebDetail to inherit from the userdetail and also they could show up in the database(django admin) Thanks for your contribution :) -
how to use in django ListView (three class model)
I create a table as shown below, and return the object of get_context_data in the first field with a for statement to display the total class name of the academy, and in the second field, I want to get the number of entry_date students for each class. In other words, you want to find the number of students who are satisfied in a specific period of each class. However, I am having a hard time figuring out the number for each class. Any help would be appreciated. [Academy App - models.py] class Academy(models.Model): class_name = models.charfield(max_length='50', blank=True, null=True) [Student App - models.py] class Student(models.Model): student_name = models.charfield(max_length='50', blank=True, null=True) sex = models.charfield(max_length='1', blank=True, null=True) age = models.charfield(max_length='3', blank=True, null=True) academy = models.Foreignkey('academy.Academy', , on_delete=models.SET_NULL, null=True, blank=True) class Attribute(models.Model): entry_date = models.DateField(blank=True, null=True) student = models.Foreignkey(Student, on_delete=models.SET_NULL, null=True, blank=True) [Academy App - views.py] class ListView(ListView): model = Academy context_object_name = 'academies' template_name = 'list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['option_radio'] = self.request.GET.get('optionRadios') context['to_date'] = self.request.GET.get('to_date') context['from_date'] = self.request.GET.get('from_date') if context['option_radio'] == 'period': context['academy_id'] = Student.objects.filter(academy_id=self.id) ---- problem context['entry_date_count'] = Attribute.objects.filter( entry_date__lte=context['to_date'], entry_date__gte=context['from_date'], student_id__in=context['academy_id'] ).count() return context [list.html] <form action="/list" method="GET"> <fieldset> <div class="radio" style="display: inline"> <label> <input type="radio" name="optionRadios" id="optionsRadios1" … -
Is it good practice to use the Django template system and/or its admin site in commercial applications?
As a beginner to web applications and front end stuff, I'm really confused about if it's good practice to use the Django template system and its admin interface in commercial applications. As far as I know, the modern approach for web apps is to modularize them between a back end and a front end. It seems that this modularity has important benefits related to separation of concerns, and that would mean: Creating a Django back end with a REST API to be used by the front end. Creating an independent React or Vue front end that makes requests to the API. With this in mind, while I read the Django tutorial, I was convinced that using templates and the admin site was not a good idea because there would be no modularity, as everything would be inside the Django project, and the UI would also be dependent on Django templates, which seems to be limited by design. But on the other hand it seems that CRUD applications for management in general would benefit a lot from the Django admin interface. I wonder if it's a terrible idea to deploy a system that is an extension of a Django admin site … -
How to get django model which was dynamically created using schema_editor?
I am trying to create django model dynamically and get the model later. This is my code. from django.db import models, connection def create_model(model): with connection.schema_editor() as schema_editor: schema_editor.create_model(model) def create_model_from_fields(name, fields, app_label='app', module='app.models'): class Meta: pass if app_label: setattr(Meta, 'app_label', app_label) attrs = {'__module__': module, 'Meta': Meta} if fields: attrs.update(fields) model = type(name, (models.Model,), attrs) return model In django shell, I did the following. import djang.apps import apps model = create_model_from_fields('TestModel', {'name': models.CharField(max_length=10)}}) create_model(model) models = apps.all_models['app'].keys() Then, I found models included TestModel. But, once I exit django shell and reenter django shell, models does not include TestModel. How can I get TestModel after connection is once lost? -
How can I access an image from my database and show it on a html webpage in Django?
I am trying to display multiple images in a grid-like format using a few lines of code on the html page, so I can add or remove images without changing the actual html. Something like this: {% for image in images %} <img class="gallery" src="{% static '{{image.path}}' %}" alt="{{image.description}}"> {% endfor %} The image variable is an object that has its path in this format: images/image1.png The description is a CharField. For some reason when I refreshed my page, all I saw was what's contained in the description variable. I couldn't find a way to show the image itself. I then tried using an ImageField in my models.py file, instead of its path, but I don't know how to actually access and show the image in html. -
How to send push notifications from django to a react native app?
I am building a django aplication and I want to know what is the best approach for sending push notifications to users in a react native app if a certain condition is mee. The idea is to send notifications to groups of users. It could be even 100 users at the same time -
Does FastAPI ecosystem has analogs to Django storages?
Does FastAPI ecosystem has analogs to Django storages? Django has a nice concept of storages - https://docs.djangoproject.com/en/3.2/howto/custom-file-storage/ It lets you easily switch between different file storages (e.g. filesystem storage vs s3). All you have to do is download or write a custom storage class and plug it in using Django settings. What do you use when dealing with file storage in FastAPI? Do you write your custom storage library or does FastAPI ecosystem has some defacto storage library? BTW: I use TortoiseORM as ORM, but it doesn't even have FileFields, nothing to say about storages. -
How to call Docker from Django?
I made some microservises (docker images) to NLP processing. I want to use these microservises in my Django application. But I don't want to set up Docker in Django. I just want to send a request from Django to Docker to use these microservises. I wrote these codes to call Docker. views.py def link1(request): input_text = {} if 'text' in request.POST: text = request.POST['text'] url = 'http://localhost:5000/sentiment' % text response = requests.POST(url) input_text = response.json() return render(request, 'blog/links/Link1.html', {'input_text': input_text}) Link1.html <div class = "item-1"> <form class="text" method="POST"action="{% url 'duyguanalizi' %}"> {% csrf_token %} <label for="textarea"> <i class="fas fa-pencil-alt prefix"></i> Duygu Analizi </label> <h2>Kendi Metniniz ile Test Edin...</h2> <input class="input" id="textarea" type="text" name="text"> </input> </form> <button type="submit" class="btn" name="submit">Dene</button> {% if input_text %} <label >Sonuç </label> <p><strong>{{ input_text.sentiment }}</p> {% endif %} </div> -
Filling two foreign keys fields automatically in Django
Is there a way to fill two foriegn key fields in a model automatically when using a form? I succeeded in filling one foriegn key using inlineformset, but I don't how to fill the other. -
Django Rest Framework - Creating nested JSON without a Model
I'm looking for an output similar to: "live_collection": { "buy": 420, "sell": 69, }, I'm not using a model. Instead, I'm aggregating data from a different model. That part is working fine as I'm able to create a flat JSON response - but I attempt to nest it like the above, I run into issues. Here is the view.py: class PlayerCollectionLiveView(APIView): def get(self, request): live_collection_buy = list(PlayerProfile.objects.filter(series="Live").aggregate(Sum('playerlisting__best_buy_price')).values())[0] live_collection_sell = list(PlayerProfile.objects.filter(series="Live").aggregate(Sum('playerlisting__best_sell_price')).values())[0] collections = { "live_collection": { "buy": live_collection_buy, "sell": live_collection_sell, }, } results = PlayerCollectionLiveSerializer(collections, many=True).data return Response(results) The serializer.py class PlayerCollectionLiveSerializer(serializers.Serializer): live_collection__buy = serializers.IntegerField() live_collection__sell = serializers.IntegerField() And here is the error I'm getting: Got AttributeError when attempting to get a value for field `live_collection__buy` on serializer `PlayerCollectionLiveSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'live_collection__buy'. -
Django - How to re-display the same form choices after submit?
I'm still learning Django and I'm making this project, where I'm consuming API (from Path of Exile) and displaying my account's data. In my views.py GET method, I'm getting all my characters associated with my account and passing them into the Form ChoiceField, so they can be rendered in detail.html. Once I click on a particular character, then in the POST method, I'm extracting certain data associated with that character and displaying its equipment. And this is where I also want to be able to display the same Form ChoiceField, so I can click on a different character and display its info instead, but I don't know how to display/pass in the same form here. views.py from django.shortcuts import render from django.http import JsonResponse from .forms import SelectCharacter from pprint import pprint import requests import json def get_user(request): headers = {'User-Agent': 'Mozilla/5.0 '} cookie = {'POESESSID': '*******************************'} if request.method == 'GET': url = 'https://www.pathofexile.com/character-window/get-characters?accountName=R33son' r = requests.get(url, headers=headers, cookies=cookie) results = r.json() names = [character['name'] for character in results] form = SelectCharacter(names) context = { 'characters': names, 'form': form, 'title': 'Select character', } return render(request, 'user/detail.html', context) elif request.method == 'POST': url = f"https://www.pathofexile.com/character-window/get-items?accountName=R33son&character={request.POST['character']}" r = requests.get(url, headers=headers, cookies=cookie) results … -
How can I retrieve only the value of a field in model A as the field value in model B in django
I have 2 models named Category and Product. I want to retrieve only the id fields value in the Category model as my forign key field value in my Product model. At the minute when I retrieve a product the whole model is listed in the foreign key field in my product model. So for example rather than retrieve all the fields in the Category table I only want to retrieve the id value from the category model into the product foreign key field. Apologies if I am not making sense but hopefully the code can clarify what I am taking about. Category Model class Category(models.Model): id = models.IntegerField(primary_key=True, blank=False, auto_created=True, unique=True) name = models.CharField(max_length=100, blank=False) category_description = models.TextField(max_length=400, blank=False) category_image = models.ImageField(upload_to=upload_path, default='', blank=True) def __str__(self): return str(self.name) Product Model class Product(models.Model): (pink, 'Pink'), ] product_code = models.IntegerField(primary_key=True, auto_created=True, blank=False, unique=True) name = models.CharField(max_length=50, null=False, blank=False) price = models.DecimalField(default=0, max_digits=1000, decimal_places=2) product_image = models.ImageField(upload_to=upload_path, default='', blank=True) category = models.ForeignKey(Category, to_field='id', null=True, default='', blank=False, on_delete=models.PROTECT So when I retrieve a product this is what I get: "product_code": 1, "name": "Test Product", "price": "1.00", "product_image": "http://127.0.0.1:8000/media/images/Test%20Product/91WgL3IbNIL._AC_SL1500_.jpg", "category": { "id": 1, "name": "Test Category", "category_description": "testing", "category_image": "http://127.0.0.1:8000/media/images/Test%20Category/Image.png" } And this is … -
Dinamic django choice field
I have 4 models: Products (the list of products: freezers, microwaves, tvs and pcs), ProductType (entertainment and home appliances), Credit (a credit is registered on each purchase) and PurchaseReason (the reason why the customer has bought the product). The PurchaseReason depend on the productType, so the purchaseReason has a foreignKey field productType. In addition, each credit has a product as foreignKey and a purchaseReason as foreignKey. Also, I have the ProductReason field as a choice field in the credit model, and I want the options to be set dynamically based on the product field of the credit model. I'm creating an API so I think this cant be handle with modelForms, but i'm not sure. The hard work would be with the serializers (DRF) and with the django-admin (specially this one because in my product the django admin plays an important role) What would be the best approach to manage my models in Django? -
Show the main page in the django multi-tenant
I am studing the djanto multi-tenant package (https://github.com/django-tenants/django-tenants). When i try to access the main page (landing page) at http://127.0.0.1:8000/, I got the following message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Raised by: core.views.home No tenant for hostname "127.0.0.1" You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. How do I get the landing page to show correctly? URL FILE from core.views import home urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) THE VIEW OF LANDINGPAGE from django.shortcuts import render def home(request): return render(request, 'core/index.html') PARTIAL SETTINGS FILES DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition SHARED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_tenants', 'customer', 'core', //landing page ] TENANT_APPS = [ # The following Django contrib apps must be in TENANT_APPS 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', # your tenant-specific apps 'myclientapp', ] INSTALLED_APPS = list(set(SHARED_APPS + TENANT_APPS)) Thank you very much! -
How to take Xml file as input in angular and store in data in django
The frontEnd is in Angular and the Backend part is in Django. Question 1: How to implement views in Django to read XML file from angular. Question 2: How to store data from that XML file in django. I need to read the XML file in angular and store data in Django. can you show an example of that? I have already created models for that and also done serialization. Please Help. -
How to send request to Docker from Django?
I made some microservises (docker images) to NLP processing. I want to use these microservises in my Django application. But I don't want to set up Docker in Django. I just want to send a request from Django to Docker to use these microservises. -
Django many-to-many making too many calls
I have a simple m2m relationship as below: class Category(ModelBase): name = models.CharField(max_length=255) icon = models.CharField(max_length=50) class Course(ModelBase): name = models.CharField(max_length=255, unique=True) categories = models.ManyToManyField(Category, related_name="courses") I am using ListView to show all the courses in a category or all courses if no category provided. views.py class CourseListView(ListView): model = Course paginate_by = 15 template_name = "courses.html" context_object_name = "courses" def get_queryset(self): queryset = ( super() .get_queryset() .select_related("tutor") .prefetch_related("categories") .filter(active=True) ) category_id = self.kwargs.get("category_id") return ( queryset if not category_id else queryset.filter(categories__in=[category_id]) ) def get_context_data(self, *args, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) category_id = self.kwargs.get("category_id") if category_id: context["current_category"] = Category.objects.get(id=category_id) context["categories"] = Category.objects.all() return context Django is making duplicate calls as I am doing something like this in the template. <div class="icon"><span class="{{ course.categories.first.icon }}"></span></div> Not sure why, help much appreciated. Thanks! -
Django "Steam Community Market" - Like Open-Source
I'm trying to build a marketplace like the Steam community market on Django. Basically what I'm looking for: 1- Users will have a wallet with a custom currency (Points) that they can use to buy digital stuff. 2- Users will have a pre-defined items they can sell. 3- I'll be taking a percentage of each sale. 4- Wallet & Sale items will be called from my main server 5- Auction/Bidding would be a plus 6- Mobile friendliness is a must Does anyone know an open-source that would be a good start to start building on top of? -
Stumped by DjangoRestFramework
Please help me figure out how to solve the error message ModuleNotFoundError: No module named 'apps.user'. The complexity of this tutorial is several steps above the usual beginners' tutorial and so I had a hard time search for answers. I tested with the standard lines from Django Rest Framework's docs to no avail. I also tested by commenting out everything extraneous to the bare-bottom, basic users app (like views.py). The line in the INSTALLED_APPS still gives me a long list of erros that end in this--Whether I have apps.users or users.apps.UsersConfig: django.core.exceptions.ImproperlyConfigured: Cannot import 'users'. Check that 'apps.users.apps.UsersConfig.name' is correct. This is the first time I have an app inside another folder (ie the users folder is inside apps folder), I wonder if the folder structure is causing the problem, though this is exactly what the tutorial instructs. I can post more code here if needed, but the github repo is here. I've searched through the entire project folder for references to "users", but nothing stood out. Any insight would be greatly appreciated. The folders structure is the following: project_folder apps users apps.py models.py urls.py views.py ... config settings.py urls.py ... manage.py -
Permission is ignored for action decorator
Why is my action decorator ignoring its permission_class? I have a ViewSet that has "IsAuthenticated" for both a generic post/create and for posting to a custom action decorator. However, when I use the custom action decorator for a non-logged in user, the code for the action decorator still runs (and causes an error). Why is this? Shouldn't a non-logged in user receive a 401_Unauthorized when posting to the action? A non-logged in user does receive a 401_Unauthorized when doing a generic post. Here is the ViewSet: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() lookup_field = "pk" serializer_class = ItemSerializer def get_permissions(self): if self.action == "create": permission_classes = [IsAuthenticated] else: permission_classes = [AllowAny] return [permission() for permission in permission_classes] @action( methods=["post"], detail=True, permission_classes=[IsAuthenticated], url_name="action", ) def action(self, request, pk=None): try: item = Item.objects.get(user=request.user) item.status = "actioned" item.save() except Item.DoesNotExist: Item.objects.create(user=request.user, status="actioned") return Response(status=status.HTTP_201_CREATED) I'm using DefaultRouter() for my urls. Here are the tests: # GENERIC POST BY ANONYMOUSUSER DOESN'T RUN AND GIVES 401 def test_public_generic_post(self): payload = {"status": None} response = APIClient.post( reverse("app:item-list"), payload, format="json" ) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # True # ACTION POST BY ANONYMOUSUSER RUNS EVEN THOUGH IT HAS THE SAME IsAuthenticated permission def test_public_action_post(self): item = Item.objects.create() response = APIClient.post( reverse("app:item-action", … -
Django with MONGO DB using DJONGO
I'm using MongoDB on Django for now i trying to use the DJONGO, but I'm struggling to build the same SCHEMA I already created at my database on MongoDB for Django. Follow below one example from my DB schema. { 'stock': 'Microsoft', 'code': 'msft', 'result': { '2020': { 'item1': 123, 'item2': 456, }, '2019': { 'item1': 987, 'item2': 456, }, } }, { 'stock': 'Facebook', 'code': 'fb', 'result': { '2011': { 'item1': 999, 'item2': 555, }, '2015': { 'item1': 753, 'item2': 159, }, } } To access the first line it's pretty simple has you guys can see bellow, but the difficulty start when need access the embedded sub-documents. class Stocks(models.Model): stock = models.CharField(max_length=255, verbose_name='Stock name:') code = models.CharField(max_length=255, verbose_name='Stock code:') I tried several solutions and could find nothing to help. If someone know anything or can give me a hand on this, I will be pleased! Thanks! Cid