Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
PYTHON PACKAGE OVERRIDE Django-Machina App error if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class
First and foremost, I appreciate all the help you guys have given me by just reading the forum. I have a problem that iv been trying to figure out for a while. I have two django frameworks that i am trying to merge together. The two systems are one of mine and Django-Machina which is forum. Each of the frameworks has 2 "accounts models". Im probably not setting this up correct. Any ideas how to set this override up? I need the Accounts.User model to feed its data into Forum_member model. The Documentation for Django-Machina says to create a python package to override its native model with one of my interest. So im attempting to override the Machina forum-member application with my own accounts models. I get this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/zeitgeist/opt/anaconda3/lib/python3.7/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class (base) Zeitgeists-MacBook-Pro:backend zeitgeist$ Here … -
Django migration duplicate operation
I'm using Django for the backend of my application and everything is fine except a little problem with my migrations. I'm using a custom User model by inheriting from AbstractUser and I have something like the following : class User(AbstractUser): class Meta: verbose_name = "User" # Fields and methods here # ... which results in this part of the migration in my 0001_initial.py migration file : options={ 'verbose_name': 'User', 'verbose_name_plural': 'Users', 'abstract': False, }, The thing is, when I run makemigrations later on, it creates an automatic migration with this little part in it : migrations.AlterModelOptions( name='user', options={'verbose_name': 'User'}, ), I do not understand why it tries to apply this modification a second time. Can someone help me ? I could let it as it is but I try to keep my migration files as clean as possible. Thanks in advance. -
csv + Kafka + Spark streaming + MLlib + Django Dashboard
I have a (personal) project where i need to develop a big data pipeline starting from an upgradeable csv. The final goal is to build a dashboard that allow to monitor and make real time forecast based on the csv file. I would like to show the dashboard from a django web app. From what i've seen one kind an infrastructure that might be suitable includes: kafka ---> spark ---> PostgreSQL -->django--->dashboard. Does anyone have any advice or faced a similar problem? -
Django NameError: name 'Instractor' is not defined
I have two apps in Django project . one is "accounts" another is " Courses " I have a model in accounts app class Student(SoftDeleteModel): user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='student_info') name = models.CharField(null=True, blank=True, max_length=250) course_enrolled = models.ForeignKey(Courses,on_delete=models.CASCADE,blank=True) trx_id = models.CharField(max_length=20) date_of_birth = models.DateField(null=True, blank=True) education_qualification = models.CharField(null=True, blank=True, max_length=250) institution_name = models.CharField(null=True, blank=True, max_length=250) image = models.ImageField(upload_to='photos/%y/%m/%d',null=True, blank=True) address = models.CharField(null=True, blank=True, max_length=250) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.email class Instractor(SoftDeleteModel): user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='instractor_info') name = models.CharField(null=True, blank=True, max_length=250) degination = models.CharField(null=True, blank=True, max_length=250) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name This is model for accounts and Course Model is: from accounts.models import * class Courses(models.Model): title = models.CharField(max_length=200,blank=True,null=True) image = models.ImageField(null=True,upload_to="photos/course/") category = models.ForeignKey(Category,on_delete=models.CASCADE) instractor = models.ForeignKey(Instractor, on_delete=models.CASCADE,blank=True) total_student_enrolled = models.IntegerField(null=True,blank=True) price = models.IntegerField(blank=True,null=True) course_length_in_hour = models.IntegerField(blank=True,null=True) course_length_in_weeks = models.IntegerField(blank=True,null=True) programming_language = models.CharField(max_length=500,null=True,blank=True) course_requirements = models.TextField() course_description = models.TextField() what_you_will_learn = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now_add=True) is_published = models.BooleanField(default=False) slug = models.SlugField(null = False, blank = True) def __str__(self): return self.title I have import courses.model but it showing that Instractor not Defined. But if i remove course_enrolled = models.ForeignKey(Courses,on_delete=models.CASCADE,blank=True) course_enrolled field from accounts model the error is not showing :/ I don't get … -
Getting KeyError when using request.session['value'] in django
I am trying to write session and want to read session from another view function in django. I am using django 3.1.5. Here is my views.py code, I set a session after user is logged in request.session['value'] = 'istiak' def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) request.session['value'] = 'istiak' return redirect('home') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'library_site/login.html') And In this view I tried to get this session data. Code-> usern = request.session['value'] def bookprofile(request): usern = request.session['value'] return render(request, 'library_site/bookprofile.html') But I am getting error KeyError: 'value' . Here is full error Traceback (most recent call last): File "C:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "B:\django\Django_Project\Library\library\library_site\views.py", line 31, in bookprofile usern = request.session['value'] File "C:\python\Python38\lib\site-packages\django\contrib\sessions\backends\base.py", line 65, in __getitem__ return self._session[key] KeyError: 'value' -
Django Filter for Model function
I am trying to filter through a TextField where I have stripped it of its HTML tags. However, it gives me this error: "Cannot resolve keyword 'search' into field." Here is my code: models.py class Entry(models.Model): body = models.TextField() def search(self): tags = re.compile('<.*?>') cleantext = re.sub(tags, '', self.body) return cleantext views.py from django.db.models import Q ... def search_list(request, query=None): search = "search" entrys = Entry.objects.filter(status="publish").filter(Q(search_body__icontains=search)).distinct() Is there a way to do this? -
Error while fetching values from list of dictionaries inside a dictionary
I need to fetch values from product_name which is a key in the list of dictionaries inside a dictionary. [{'id': 53, 'loc_latitude': 19.036798, 'loc_lonitude': 72.8424038, 'address1': 'Paradise Cinema, Mahim(west)', 'address2': 'Mumbai 12345', 'pincode': '400016', 'address_category': None}] {'order_id': 'helit', 'user_id': 75, 'wallet_amount': None, 'payable_amount': None, 'payment_status': False, 'payment_mode': None, 'order_status': 'book', 'delivery_status': 'In process', 'order_delivery_type': 'Delivery', 'get_cart_total_discount': 0.0, 'get_cart_total_GST': 0.0, 'get_cart_total': 81.0, 'get_cart_sub_total': 56.0, 'get_cart_quantities': 2, 'get_cart_items': 1, 'deliveryCharges': 25.0, 'subscription_type': False, 'subscriptionId': None, 'products': [{'product_id': 'NNPTA', 'product_name': 'CHASS 200 ML', 'product_description': 'The secret recipe of butter milk from Punjab Sind Foods is a refresher any time! an excellent source of probiotics and a must have with every meal for better digestion.', 'product_images': '/images/productImages/Masala_Chass_yGg9K92.png', 'product_price': 28.0, 'gst': 0, 'product_status': None, 'discount': None, 'rating': None, 'product_quantity': 2, 'get_product_total': 56.0, 'get_product_total_gst': 0.0}]} What I've tried Assuming products is a variable containing all the data products = product_data['products'] product_name = [x for x in product_price['product_name']] Doing this would give me tuple indices must be integers or slices, not str