Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, custom managers, base_manager_name and the failure to save model
I'll simplify my problem: In my project I have a Person model and that person has an age. I changed the default manager applied to Person using base_manager_name to my version of objects. Person` has this: objects = MySpecialAgeFilterManager() objects_all = models.Manager() So, when I ask for Person.objects.all() I will get only people between the ages of 20 and 30. Don't ask me why-- it's just for the sake of this question.. I have a certain Person instance with the age of 10. That person will not show up on Person.objects.all() -- however it will be included in Person.objects_all.all() My problem is this. p = Person.objects_all.filter(age=10).first() # works, I get my person. p.age = 20 # trying to bring him into the light.... p.save() # CRASH!!! The crash claims the pk for p creates a duplicate violation on the database. It's as if it's trying to save it with the objects scope in mind, and not the objects_all scope I retrieved that person with. In the objects context it doesn't exist so it tries to save... but the database has that PK already in use. The database doesn't care about Model Manager scopes.... How do I resolve this? -
Class "Room" has no "objects" members
I'm doing a web app with Django, but I keep getting this error all the time. This is the code from my models.pty, where I create the class Room. from django.db import models import string import random def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if Room.objects.filter(code=code).count() == 0: break return code class Room(models.Model): code = models.CharField(max_length=8, default="", unique=True) host = models.CharField(max_length=50, unique=True) guest_can_pause = models.BooleanField(null=False, default=False) votes_to_skip = models.IntegerField(null=False, default=1) created_at = models.DateTimeField(auto_now_add=True) And here is where I import the room to views.py, I'm also getting the same error here. from django.shortcuts import render from rest_framework import generics from .serializer import RoomSerializer from .models import Room class RoomView(generics.CreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer What's wrong with my code? -
Trouble viewing cart items from admin page on django site
Here is my views.py from django.shortcuts import render from .models import Cart def cart(request): Cart = Cart.objects.get(id=1) context = { 'items': Product.objects.all(), 'object': obj, 'id': obj.id, 'name': obj.name, 'cover': obj.image, 'author': obj.author, } return render(request,'bookstore/cart.html', context) ``` Here is my models.py from django.db import models from apps.bookstore.models import Product class Cart(models.Model): products = models.ManyToManyField(Product,blank=True) total = models.DecimalField(max_digits=65, decimal_places=2,default=0.00) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False,auto_now=True) active = models.BooleanField(default=True) def __unicode__(self): return "Cart id: %s" %(self.id) ``` Here is my cart.html {% extends 'bookstore/main.html' %} {% load crispy_forms_tags %} from .models import Product from cart.models import Cart {% block content %} <h1>Shopping Cart</h1> <table> {% for item in items %} <tr> {{ item.name }} <td>{{ item.author }}</td> </tr> {% endfor %} {% endblock content %} It seems like something is wrong with my models.py portion. In my admin page I can add the items I have from the bookstore to the cart however when I go to look at them on the website nothing is displayed. -
Complex Django CheckContraint won't migrate
I'm having issues running a Django (2.2) migration that contains a somewhat complex CheckConstraint, running over python 3.6.9. The underlying database is PostGIS 9.5. The Model: class Subscription(BaseModel): class Meta: constraints = [ models.CheckConstraint(name='%(app_label)s_%(class)s_valid_product', check=( (models.Q(variant_id__exact=None) & models.Q(product_id__exact=None)) | (~models.Q(variant_id__exact=None) & ~models.Q(product_id__exact=None)) )) ] ... product_id = models.IntegerField() variant_id = models.IntegerField() The migration: ... migrations.AddConstraint( model_name='subscription', constraint=models.CheckConstraint( name='%(app_label)s_%(class)s_valid_product', check=models.Q( models.Q( models.Q(variant_id__exact=None), models.Q(product_id__exact=None) ), models.Q( models.Q(_negated=True, variant_id__exact=None), models.Q(_negated=True, product_id__exact=None) ), _connector='OR' ) ), ), ... And the big bad trace: File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 827, in database_forwards schema_editor.add_constraint(model, self.constraint) File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 345, in add_constraint self.execute(sql) File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 137, in … -
Django de-structuring of URLs
I am learning the Django Web Framework but just could not work my head around this logic. Let's say we have a Django App that has a very big urls.py where all the patterns are stored here. How would one go about splitting this into a urls folder, wherein it contains multiple 'urls.py' files? And not only that, to have a nested directory within the urls folder as well. Example project structure of what I am thinking of: >main_base >__init__.py >asgi.py >settings.py >wsgi.py >urls.py >secondary_app >admin.py >apps.py >models.py >__init__.py >views >home.py >idea.py >project.py >business_partners >customers.py >vendors.py >urls >__init__.py >home.py >idea.py >project.py >business_partners >__init__.py >customers.py >vendors.py in main_base/urls, I would have the following: from django.urls import path, include urlpatterns = [ path('', include('secondary_app.urls')), ] in secondary_app/urls/init.py, I would expect to do the following: from django.urls import path, include urlpatterns = [ path('', include('secondary_app.urls.home')), path('', include('secondary_app.urls.idea')), path('', include('secondary_app.urls.project')), path('', include('secondary_app.urls.business_partners')), ] And lastly in secondary_app/urls/business_partners/init.py, I would do the following: from django.urls import path, include urlpatterns = [ path('', include('secondary_app.urls.business_partners.customers')), path('', include('secondary_app.urls.business_partners.vendors')), ] I have tested it and it works all the way up till the secondary_app/urls directory level. But once I go one more level down, it throws a reverse match … -
Is there a way to enable verbose logging in Django Channels?
I have Django Rest Framework and Channels installed on a Heroku server. I am having issues with socket signals my API is sending to my sockets actually getting received by the consumer. I know this because the print()s in my consumer don't print. This is an intermittent issue - sometimes I refresh and it works fine for some users. Is there a way to enable some sort of verbose logging so I can see every call that Channels is receiving, and where it is sending it to? -
can't get the profile object firstname
I'm trying to get the profile firstname but it gives me this error File "/home/marwan/Desktop/Gowd/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. WebSocket DISCONNECT /public_chat/1/ [127.0.0.1:53742] INFO 2021-03-12 01:43:30,570 runserver 119412 140507688003328 WebSocket DISCONNECT /public_chat/1/ [127.0.0.1:53742] I think that this error has something to do with trying to get the user profile in line 56 "profile": self.scope["user"].profile.firstname, if I remove it will work fine this is my consumers.py file from channels.generic.websocket import AsyncJsonWebsocketConsumer import json from django.contrib.auth import get_user_model from gowd_project.users.models import User, Profile User = get_user_model() # Example taken from: # https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/consumers.py class PublicChatConsumer(AsyncJsonWebsocketConsumer): async def connect(self): """ Called when the websocket is handshaking as part of initial connection. """ print("PublicChatConsumer: connect: " + str(self.scope["user"])) # let everyone connect. But limit read/write to authenticated users await self.accept() # Add them to the group so they get room messages await self.channel_layer.group_add( "public_chatroom_1", self.channel_name, ) async def disconnect(self, code): """ Called when the WebSocket closes for any reason. """ # leave the room print("PublicChatConsumer: disconnect") pass async def receive_json(self, content): """ Called when we get a text frame. Channels will JSON-decode the payload for us and pass … -
Passing Django ContentFile to an ImageField doesn't create an image file on the disk on Docker
The code below works on local when I don't use Docker containers. But when I try to run the same code/project in Docker, while everything else is working great, the part of the code below doesn't work as expected and doesn't save the ContentFile as image file to the disk. The ImageField returns the path of the image but actually it doesn't exist. from django.core.files.base import ContentFile ... photo_as_bytearray = photo_file.get_as_bytearray() # returns bytearray cf = ContentFile(photo_as_bytearray) obj.photo.save('mynewfile.jpg', cf) # <<< doesn't create the file only on Docker Not sure if there's something I need to change for Docker. -
django.db.utils.OperationalError: ('HYT00', '[HYT00]
I am trying to run a virtual Python Django environment and have run this command. python manage.py runserver Now, I receive the following error(s). Could someone point me in the right direction? I know this has somethingt to do with ODBC/the backend but am not sure exactly what is going on. Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection conn = Database.connect(connstr, pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/christinadias/code/lux/.venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line … -
Replacing CharField with a ForeignKey based on the CharField
While refactoring an app, I've started removing a config file and replacing it with a new model, Foo in this example. Because of this, another model, Bar in this example, needs to change from having a CharField that was for the config file, to a ForeignKey that is for the new model. Say I have class Foo(models.Model): name = models.CharField(primary_key=True, max_length=100) class Bar(models.Model): name_of_foo = models.CharField(max_length=100) and I want to change name_of_foo to instead be a ForeignKey... class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, default=???) I would like the default to be based on what name_of_foo was. If name_of_foo was "abc", I would like it to do something akin to default=Foo.objects.get("abc"). Is there a way to fill in the ??? such that this works nicely? If not, what steps can I take to arrive here, so that the existing data is converted? -
Crispy forms not working on django login form created with "django.contrib.auth.urls"
Good Day, i am trying to use crispy forms on a login form created with the django authentication system(using 'django.contrib.auth.urls' to be specific) but crispy forms didn't work on it. urls.py from django.conf.urls import include, url from users.views import dashboard urlpatterns = [ url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^dashboard', dashboard, name='dashboard') ] This autamotically passed the context to the login template i made.(i didn't even need a view) login.html <form method="POST"> {% csrf_token %} <fieldset class=''> <legend class='border-bottom mb-4 text-center'>Log In</legend> {{ form|crispy }} </fieldset> <div class=""> <button class="btn btn-outline-info btn-primary" type='submit'>Login</button> <small class = "text-muted ml-2" > <a href="">Forgot Password?</a> </small> </div> </form> But when i tried using crispy forms on the context variable 'form', it didn't work on it. But it worked on the other elements inside the form(like the link that says "Forgot Password?" and the login button). So i guess the way the form variable is passed to the template doesn't allow crispy forms work on it. Please is there a way(maybe with a view or something) to access the variable and make it like a regular form context variable that crispy can work on. Thank You -
How do I get the value of the object being created in Django CreateView for further logic?
So I have a CreateView which is using a model form 'A' and I also have a different model which I want to edit when this model inside model form 'A' gets submitted. How do I access the object when it's not created? Is there any better approach? Here is the form_valid function() def form_valid(self, form): member = self.object form.instance.registration_upto = form.cleaned_data['registration_date'] + delta.relativedelta( months=int(form.cleaned_data['subscription_period'])) if form.cleaned_data['fee_status'] == 'paid': payments = Payments( user=member, payment_date=form.cleaned_data['registration_date'], payment_period=form.cleaned_data['subscription_period'], payment_amount=form.cleaned_data['amount']) payments.save() return super().form_valid(form) Self.object is None as the object is not yet created. I want to access that object as it's the user in my payments model. I have to stick to class-based views only. Is there a way I can do this? I'm a little new to Django and looking at the docs didn't help much. Thanks for any advice -
How to update the las row of the table with Django OMR queryset?
I´m trying to make an update with the django OMR but I don´t know the id. Only I konw that I want to update the last record. The other columns are not useful because the data is similar except for the date column(could be an aoption but the django OMR don´t recognized my query) My actual query: Tracking = TrackEExercises.filter( exe_date = (fecha + delta).replace(microsecond=0) ).update(data_tracking = dataT) -
Django backend, reactjs frontend - How do I pass context variable from views.py to app.js?
I'm creating an application that webscrapes data. I've created all my logic in the Django backend and it works perfectly fine. I put the variables needed into a dictionary to be rendered out. views.py return render(request, 'index.html', context_dict) It properly renders out to my index.html, I am able to see the variable. However I need these context_dict variables to render out to my app.js file, so I can use it with react on the frontend. Please let me know how this is possible. Thanks in advance! app.js function App() { return ( <div className="App"> <div className="center-column"> <div className="item-row"> <div class="centered"> <span> - - - - NEED TO CALL MY CONTEXT_DICT HERE! - - - - </span> </div> </div> </div> </div> ); } export default App; Local Server - 127.0.0.0.1:8000 -
Djnago live viewers counter in rtmp
I have a few livestreaming pages on my site. And i want to count users who are watching my stream at this moment. Like on twitch. How to implement it? -
Handling pages in a vue + django webpack application
I added Vue to my Django project, but since i didn't want to decouple frontend from backend, i decided to load webpack directly from Django. My setup seems to work with django webpack loader, but i'm having some doubts on how i structured the project. Here is my folder: my_site - django settings my_app - views, urls, models, templates vue_frontend - webpack and vue stuff My doubt is: should routing be handled by Django or should it be handled by Vue in a SPA? Here is what i have now: django_template2.html {% extends 'header.html' %} {% load render_bundle from webpack_loader %} {% block content %} <body> <div id="app"> <firstVueComponent /> </div> </body> {% render_bundle 'chunk-vendors' %} {% render_bundle 'main' %} {% endblock %} django_template2.html {% extends 'header.html' %} {% load render_bundle from webpack_loader %} {% block content %} <body> <div id="app"> <secondVueComponent /> </div> </body> {% render_bundle 'chunk-vendors' %} {% render_bundle 'main' %} {% endblock %} So Django handles the urls here: from django.urls import path, include from . import views urlpatterns = [ path('first_page/', views.first_page, name='first'), path('second_page/', views.second_page, name='second'), ] So here i'm not using Vue to handle routes, but i load individual Vue components of the same app … -
Is there a way we can pass context through extra_context param without subclassing TemplateView?
Take the following urls.py: path( "credits/", TemplateView.as_view(template_name="static_pages/credits.html", extra_context={"updated": "123"}), name="credits", ), In my template, when I do the following {{ updated }} nothing shows up. Do I really need to subclass the TemplateView and create my context through get_context_data()? Seems like so much work to just pass an eventual datetime object. -
how Video sitemaps and video sitemap alternatives for django
The sitemap framework Django comes with a high-level sitemap-generating framework to create sitemap XML files. Overview A sitemap is an XML file on your website that tells search-engine indexers how frequently your pages change and how “important” certain pages are in relation to other pages on your site. This information helps search engines index your site. The Django sitemap framework automates the creation of this XML file by letting you express this information in Python code. how use Django The sitemap framework for videos don't work from django.urls import path from django.conf.urls import url from . import views from django.contrib.sitemaps.views import sitemap from .sitemaps import PostSitemap sitemaps = { 'posts': PostSitemap } app_name = 'blog' urlpatterns = [ path('', views.home, name='homepage'), path('search/', views.post_search, name='post_search'), path('articles/<slug:post>/', views.post_single, name='post_single'), path('videos', views.videos, name='videos'), path('video/<slug:post>/', views.post_single, name='video_single'), # path('category/<category>/', views.CatListView.as_view(), name='category'), url(r'^a/(?P<hierarchy>.+)/$', views.show_category, name='category'), # url(r'^(?P<slug>[\w-]+)/$', views.post_detail, name="detail"), path('bodyOrgans/<bodyOrgans>/', views.bodyOrgans.as_view(), name='bodyOrgans'), path('page/<page>/', views.page.as_view(), name='page'), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='sitemap'), path('custom-sitemap.xml', views.index, { 'sitemaps': sitemaps, 'template_name': 'custom_sitemap.html' }), ] how make output like it <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"> <url> <loc>http://www.example.com/videos/some_video_landing_page.html</loc> <video:video> <video:thumbnail_loc>http://www.example.com/thumbs/123.jpg</video:thumbnail_loc> <video:title>Grilling steaks for summer</video:title> <video:description>Alkis shows you how to get perfectly done steaks every time</video:description> <video:content_loc> http://streamserver.example.com/video123.mp4</video:content_loc> <video:player_loc> http://www.example.com/videoplayer.php?video=123</video:player_loc> <video:duration>600</video:duration> <video:expiration_date>2021-11-05T19:20:30+08:00</video:expiration_date> <video:rating>4.2</video:rating> <video:view_count>12345</video:view_count> <video:publication_date>2007-11-05T19:20:30+08:00</video:publication_date> … -
Make field of submodel unique in django
I want to make the name of a submodel unique but I can't think of a way to do it. Imagine I have the following model architecture: class Animal(models.Model): name = field.CharField(...) class Meta: abstract = False class Panther(Animal): class Meta: ... class Tiger(Animal): class Meta: .... Now, what I want is that within the scope of the subclasses, the name of should be unique. So let's say I have a Tiger called JackTheTiger and a Panther called JackyThePanther, then no other Tiger with this name should allowed to be created and no other Panther with the name JackyThePanther should be allowed to be created. But I want to be able to create a Tiger which is called JackyThePanther and a panther which is also called JackyThePanther. So the uniqueness should only be applied within the scope of the submodel. I tried 2 ways to achieve what I want, both are not optimal: I create a name field for each submodel and make it unique. But then I can't query all animals and serialize the name. It also seems like bad architecture to me I make Animal abstract. But this is no option for me since I need the database … -
"ERROR root: code for hash md5 was not found." when running virtualenv python3
I am trying to run a virtual environment in python using the following line: virtualenv -p python3 .venv However, I am receiving this error. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha1 ERROR:root:code for hash sha224 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha224 ERROR:root:code for hash sha256 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha256 ERROR:root:code for hash sha384 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor … -
Django Count with filter
iam trying to count with filter and it doesn't show any error but there is no count showing I have tried all what I know and search every where didn't find any solution : class UsersAnswersSerializer(serializers.ModelSerializer): Answers = serializers.SerializerMethodField('get_answers') def get_answers(self, obj): queryset = AnswersModel.objects.filter(Question=obj.Answer.Question.id)\ .annotate(answersCount=Count('UsersAnswer', distinct=True)) serializer = Answersserializer(instance=queryset, many=True) return serializer.data class Meta: model = UsersAnswerModel fields = ['Answer', 'APNSDevice' ,'RegistrationID','Answers'] and this is my models : class AnswersModel(models.Model): Question = models.ForeignKey(QuestionsModel, related_name='QuestionAnswer', on_delete=models.CASCADE) Answer = models.CharField(max_length=200) class UsersAnswerModel(models.Model): Answer = models.ForeignKey(AnswersModel, related_name='UsersAnswer', on_delete=models.CASCADE) RegistrationID = models.CharField(max_length=200) APNSDevice = models.CharField(max_length=200,default='no name') class QuestionsModel(models.Model): created = models.DateTimeField(auto_now_add=True) Question = models.CharField(max_length=200) what is get is { "Answer": 12, "APNSDevice": "byname", "RegistrationID": "asdasdasdasdasdasdasdasdsa", "Answers": [ { "id": 10, "Question": 4, "Answer": "Answer 1", "UsersAnswer": [ "gfgdgdfgdf", "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4" ] }, { "id": 11, "Question": 4, "Answer": "Answer 2", "UsersAnswer": [ "sfgdfgdf", "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4", "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4", "c748dfd8aa7dd73a6c1ef17676aa7667161ff7e0f8e2ef21ef17e964a26150e4" ] } I need to make "UsersAnswer" show a count of its array -
Reverse for 'view' with keyword arguments '{'user_id': ''}' not found. 1 pattern(s) tried: ['account/(?P<user_id>[0-9]+)/$']
I wanna create a search function for searching in users when I try to run the searching page this error appear I try everything to access the user profile but I couldn't make this my views def video_search(request): form = VideoSearchForm() q = '' results = [] if 'q' in request.GET: form = VideoSearchForm(request.GET) if form.is_valid(): q = form.cleaned_data['q'] video = Video.objects.filter(title__contains=q) account = Account.objects.filter(email__icontains=q).filter(username__icontains=q).distinct() results = chain(video, account) my template <div class="col-md-4"> <a class="text-dark" href="{% url 'account:view' user_id=account.0.id %}"> <div class="card mb-4 box-shadow"> <img class="card-img-top" src="" alt=""> <div class="card-body"> <h2 style="font-size:18px;font-weight:bold">{{account.username}}</h2> <p class="card-text"></p> <div class="d-flex justify-content-between align-items-center"> <small class="text-muted"></small> </div> </div> </div> </a> </div> my urls path('<int:user_id>/', account_view, name="view"), -
Django TypeError 'ProductFeaturesValue' object is not iterable
I want to render multiple inline formsets, the first formset is being rendered but the objects of the second and third formsets are not iterable. I don't understand what I'm doing wrong here. Please help me. Here's my Model: class Product(models.Model): product_code = models.CharField(max_length=50, unique=True) product = models.CharField(max_length=100, unique=True) keywords = models.CharField(max_length=50, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) detail = models.TextField(blank=True, null=True) cost_price = models.DecimalField(max_digits=10, decimal_places=2) sale_price = models.DecimalField(max_digits=10, decimal_places=2) quantity_per_unit = models.CharField(max_length=100, blank=True, null=True) discontinue = models.BooleanField(default=False) photo = models.ImageField(upload_to = 'images/product/', default = 'images/product/None/no-img.jpg') categories = models.ManyToManyField('Category', blank=True) brand = models.ForeignKey('Brand', blank=True, null=True, on_delete=models.SET_NULL) slug = AutoSlugField(_('slug'), max_length=50, unique=True, populate_from=('product',)) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name="+", blank=True, null=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(User, related_name="+", blank=True, null=True, on_delete=models.SET_NULL) is_deleted = models.BooleanField(default=False) class Meta: default_related_name = 'product' def __str__(self): return self.product def __str__(self): return "%s (%s)" % ( self.product, ", ".join(categories.category for categories in self.categories.all()), ) def image_tag(self): return mark_safe('<img src="{}" height="50"/>').format(self.photo.url) class Image(models.Model): def images_directory_path(instance, filename): return '/'.join(['images/product/', str(instance.product_id.id), str(uuid.uuid4().hex + ".png")]) product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='images') title = models.CharField(max_length=50, blank=True, null=True) image = models.FileField(blank=True, null=True, upload_to=images_directory_path, default = None) def __str__(self): return self.title class ProductFeaturesValue(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='featuresvalues') feature = models.ForeignKey('ProductFeatures', blank=True, … -
Django passing data from one form to another
I might be going about this all wrong but I'm trying to get a filterset passed between forms in Django and not getting anywhere fast. The objective is to filter objects in my model and then be able to send an email to each of the objects owners. The filter is working and presenting a subset of records as expected. How do I pass that subset to another view. This is an extract of what I have so far... urls.py from django.urls import path from . import views from linuxaudit.views import SystemListView, SearchResultsView from linuxaudit.filters import SystemFilter from django_filters.views import FilterView from django.urls import path urlpatterns = [ path('', views.index, name='index'), path('filter/', views.filter, name='filter'), path('contact_form/', views.contact_form, name='contact_form'), ] views.py def filter(request): system_list = Linuxaudit.objects.all().order_by('Hostname') system_filter = SystemFilter(request.GET, queryset=system_list) context = { 'filter': system_filter, 'system_list': system_list, } return render(request,'linuxaudit/filter_list.html', context) def contact_form(request): system_list = request.POST.get('system_list') system_filter = SystemFilter(request.GET, queryset=system_list) for system in system_list: print(system) return render(request, 'linuxaudit/contact_form.html', { 'system_list': system_list }) import django_filters from django_filters import DateRangeFilter, DateFilter, DateTimeFromToRangeFilter from django_filters.widgets import RangeWidget from .models import Linuxaudit from django import forms class SystemFilter(django_filters.FilterSet): Hostname = django_filters.CharFilter(lookup_expr='icontains') IPADDR = django_filters.CharFilter(lookup_expr='istartswith') ContactEmail = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Linuxaudit fields = ['Hostname', 'IPADDR', … -
How to translate API response to charts in Django
Hello im a beginner in Django and i have this project where i need to show charts for Croptocurrencies transactions and i'm struggling with it. this is my views.py : import requests import os import numpy as np import pandas as pd from pandas import Series, DataFrame from pprint import pprint from django.views.generic import TemplateView import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.blockchair.com/bitcoin/stats' 'https://api.blockchair.com/ethereum/stats' 'https://api.blockchair.com/litecoin/stats' ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() json_data2 = result[1].json() json_data3 = result[2].json() context = { "bitcoin": json_data1, "ethereum": : json_data2, "litecoin": : json_data3, } return render(request, "index.html", context) and to show the transactions on the html i just have to call: (example for bitcoin) {{ bitcoin.data.transactions }} Can you help me please on how to transalate these values to graphs/charts ? or at leasat give me the keywords to search to avoid waisting time, Thanks!