Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'db' with arguments '('',)' not found. 1 pattern(s) tried: ['db/(?P<db_id>[^/]+)/$']
when I am trying to grab items from db.html with the help of id it is showing an error I cant understand where is the problem please help me out venue.html {% extends 'MYapp/index.html' %} {% block content %} <center> <h1> venue.html </h1> <br> <div class="card-header"> Featured </div> <div class="card-body container-fluid"> <h5 class="card-title">Special title treatment</h5> {% for venues in venue_list %} <p class="card-text container-fluid"> <a href="{% url 'db' all.id %}"> {{ venues }} {{ venues.lastname}}</a> {% endfor %} </p> </div> </center> {% endblock %} views.py from django.shortcuts import render from django.http import * from MYapp.models import * from .form import * def index(request): return render(request,'MYapp/index.html') def venue(request): venue_list = Task.objects.all() return render(request,'MYapp/venue.html',{'venue_list': venue_list}) def db(request, db_id): all = Task.objects.get(pk= db_id) return render(request,'MYapp/db.html',{'all': all}) urls.py another error occers hear it is showing page is not found because of this path('db/<db_id>/', views.db, name ='db'), from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('nature', views.nature, name ='nature'), path('', views.index, name ='index'), path('footer', views.footer, name ='footer'), path('navebar', views.navebar, name ='navebar'), path('form', views.form, name ='form'), path('venue', views.venue, name ='venue'), path('db/<db_id>/', views.db, name ='db'), ] -
DJANGO : How to iterate a ListView items to convert in cards
I am coding an app "dash" how a startpoint to many users. "a applications dashboard". I want to convert the list of applications in cards, "portfolio style". the user login in the platform, and in the url .../dash open the dash(django app). To here it's perfect. with the generic view - ListView - we obtain the list of applications will be available in the platform (if exist in the model, the application it's installed and available to the user) urls.py: path('dash/', views.ListView_Dash_Apps.as_view()), views.py: class ListView_Dash_Apps(ListView): template_name = "dash/ListarAplicaciones.html" model = App and in the html template, How to iterate the columns of the object_list??? with this i can iterate the rows, but not the column, i receive the str output declarated in the model. <ul> {% for e in object_list %} <li>{{ e }}</li> {% endfor %} </ul> If i can to read the columns data and include in the html (App, url_app, icon, etc etc..) -
Django and CKEditor as a template
Is it possible to use db variables in ckeditor? for example: My name is : {{ form.name }} My age is : {{ form.age }} and then i can render the ckeditor entry as a template populated by the model. All advice would be appreciated. Thanks. -
django filter on a large list- giving incorrect count or syntax error on ms sql- filtering in chunks is very slow
I am trying to filter records from a model using a list of values: Sample: items= ['a@xyz.com','b@xyz.com','c@abc.com'.......] data= TestModel.objects.filter(email__in=items) items contains more than 2000 entries and the database being used in SQL. To avoid count incorrect error: I tried: data= TestModel.objects.all() chunks = [items[x:x+1000] for x in range(0, len(items), 1000)] for chunk in chunks: chunk_data=Testmodel.objects.filter(email__in=set(chunk)) data= data | chunk_data return data I am not sure if this is the right approach and also the results are very slow. Any suggestions if there is a proper work around to filter data using a large list in django? -
How do I migrate vieys.py file without exceptions?
when Im trying to migrate my my .py file I'm facing an error "^ if request.method == 'POST' SYNTAX ERROR : Invalid character in Identifier error" this is my code def register(request): registered = False if request.method() == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) # Check to see both forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save User Form to Database user = user_form.save() # Hash the password user.set_password(user.password) # Update with Hashed password user.save() # Now we deal with the extra in # Can't commit yet because we still need to manipulate profile = profile_form.save(commit=False) # Set One to One relationship between # UserForm and UserProfileInfoForm profile.user = user # Check if they provided a profile picture if 'profile_pic' in request.FILES: print('found it') # If yes, then grab it from the POST form reply profile.profile_pic = request.FILES['profile_pic'] # Now save model profile.save() # Registration Successful! registered = True else: # One of the forms was invalid if this else gets called. print(user_form.errors,profile_form.errors) else: # Was not an HTTP post so we just render the forms as blank. user_form = UserForm() profile_form = UserProfileInfoForm() # This is the render and context dictionary to feed # back to the … -
Add percent(%) sign in the Django URL
I'm doing API migration part where I have URL with % sign in it. However I want to do the same URL mapping with the Django API URL. I have tried with creating space and also tried creating % sign.I'm getting only 404 URL not matching How could I able to achieve it error msg: The current path, api/Data/CurrentRunningActivity2/10|checkrequest, didn't match any of these. existing .net API URL: http://localhost:1400/api/Data/CurrentRunningActivity2/10%7Ccheckrequest To Django URL: Here I have used space to created percent sign in front of 7Ccheckrequest path('Data/CurrentRunningActivity2/<int:implementor> 7Ccheckrequest', CurrentRunningActivityView2, name='CurrentRunningActivity2'), -
When I search useing SearchRank, if it does not find anything, it returns everything
When I search using SearchRank, if it does not find anything, it returns everything. How can I fix this problem? views : self.search = form.cleaned_data['search'] vector = SearchVector('title', weight='A') + SearchVector('description', weight='C') + SearchVector('category', weight='B') query = SearchQuery(self.search) self.results = post.annotate(rank=SearchRank(vector, query)).order_by('-rank') -
Django How to add loop column in model from another model
I want to add each City name in models A data to models B table Column name. When I add a new City is it possible to add and update the model B table? class ModelA(models.Model): city_name = models.CharField(max_length=50) def __str__(self): return f"{self.city_name}" class ModelB(models.Model): for eachCity in ModelA: code = eachCity.city_name code = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return f"{self.options}" -
How to require an additional charge for the first-time users in stripe subscription?
I am building a Saas project. This system has several pricing plans. The first-time users should pay an additional amount of money. This money is charged only once per account and is not required anymore after the user paid once regardless of the purchased plan. It seems Stripe have no such option. And if I use the normal checkout method and subscription method together, the user should pay twice the first time. This is bad for the user experience. I would be appreciate if you could help me to solve this problem. In addition, I am using Django+React for the project. -
Django - Join between models and only get `url` field of ImageField attribute of one of the joined models
I have this class called User, which has an ImageField attribute, which stores the user's avatar/profile picture. I'm trying to annotate a Post query set so that just the user's avatar url gets returned with the post none of the other data. I've tried 2 different ways to annotate the query, but get errors as you can see below when I ping the views to get posts. How do I attach user avatar url with the return annotated Post query set? models.py class User(AbstractDatesModel): uuid = models.UUIDField(primary_key=True) username = models.CharField(max_length=USERNAME_MAX_LEN, unique=True, validators=[ MinLengthValidator(USERNAME_MIN_LEN)]) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) avatar = models.ImageField(upload_to=avatar_directory_path, blank=True, null=True) @property def avatar_url(self): return self.avatar.url class Post(models.Model): uuid = models.UUIDField(primary_key=True, default=generate_ulid_as_uuid, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) annotator.py def query_to_full_post_data_serializer(post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar_url') ) return FullPostDataSerializer(query_set_annotated, many=True) annotator_version_2.py def query_to_full_post_data_serializer(post_query_set: QuerySet): query_set_annotated = post_query_set.annotate( creator_username=F('creator__username'), creator_avatar_url=F('creator__avatar__url') ) return FullPostDataSerializer(query_set_annotated, many=True) annotator.py gives the error: django.core.exceptions.FieldError: Cannot resolve keyword 'avatar_url' into field. Choices are: avatar, cheer_post, cheer_reply, created, creator_username, followee_id, follower_id, friendship_creator, friendshiprequest, goal_creator, goal_follow, goal_join, post_creator, reply, updated_at, … -
Is there a Django library that automatically display local currency based on a visitors country IP address
I'm trying to integrate a functionality on an Ecommerce website in Django, Where victors are automatically shown local currency base on their country IP address, Is there any library that i can use to achieve this functionality. what is the best way to write a function view or class base view to accomplish this fit. Is it possible to have the manipulations of the currency on one template ? -
How to combine Celery with asyncio to handle HTTP requests asynchronously?
How to receive async HTTP requests and process the requests asynchronously using celery? Here is what I have tried, is this the right way to combine async with celery so I can receive async HTTP requests and process them asynchronously The url is: urlpatterns = [ path('api/example/', example, name='example'), ] The views.py is async def example(request): res = await process_data(request) json_data = json.loads(res.content) return render(request, "index.html", {"task_id": json_data["task_id"], "task_status": json_data["task_status"]}) async def process_data(request): result = some_CPU_heavy_function.delay("yes") return JsonResponse({"task_id": result.id, "task_status": result.status}, status=status.HTTP_200_OK) @shared_task def some_CPU_heavy_function(some_data): return {"reply": "yes"} And the command from Docker is command: gunicorn server.asgi:application --bind 0.0.0.0:8000 -w 17 -k uvicorn.workers.UvicornWorker -
How to connect MySQL with Django SQLalchemy?
I'm trying to connect Django app with MySQL, My model: **models.py** from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker engine = create_engine('mysql://root:root0000@localhost', echo=True) Base = declarative_base() Session = sessionmaker(bind=engine) Session.configure(bind=engine) session = Session() class School(Base): __tablename__ = 'schools' id = Column(Integer, primary_key=True) title = Column(String) address = Column(String) created = Column(DateTime(timezone=True), server_default=func.now()) My Controller: views.py class SchoolViewSet(ViewSet): query = models.session.query(models.School).all() def list(self, request): return Response(self.query) Getting this error: in raise_mysql_exception raise errorclass(errno, errval) sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1046, 'No database selected') -
deploying multiple dockerized django backend + ReactJS front end app in Apache2 Linux
I've built 2 demo applications for a client using Django as backend and ReactJS frontend as asked by client. These apps are working fine in Dockerized way, running fine using Database based user login credentials. They however want to move authentication to their official LDAP, which is where I'm kind of lost. the target server is Red Hat, where we've different containers for backend/frontend. We're asked to use Apache2 web server, kerberos for authenticating against ldap. After authentication, further steps will take place e.g. fetching data using API layer. Rough diagram of the system is as following. At the moment django backend,Fast API server, React frontend, Apache are running in separate docker containers. I am unable to get past Apache2 setup in first place, I've setup kerberos and kdc file and stored in mapped volume to which Apache2 docker points to. when I hit my Account App URL, I'm seeing a popup login page instead of my own Login page. Here the client rightfully expects that login should occur automatically as users are logged in to their office network. When I submit my AD login name and password, I'm getting error stating improper kdc file format. Accounts and HR system … -
Join request in django between three tables and display all attributes
I have three models class A(models.Model): field1 = models.IntegerField() class B(models.Model): id_a = models.ForeignKey(A,on_delete=models.CASCADE) field1 = models.IntegerField() field2 = models.IntegerField() class C(models.Model): id_a = models.ForeignKey(A,on_delete=models.CASCADE) field1 = models.IntegerField() field2 = models.IntegerField() I want to write a request that looks like this: SELECT * FROM B,C,A WHERE B.id_a=C.id_a WHERE A.id_a=2 and display all the attributes of the two tablesHere is what I tried to do: a_id_att = 1 data = B.objects.filter(id_a=C.objects.filter(id_a=a_id_att)[0]) It does not work. How to write the join and make to display all the attributes of the tables? -
How to use patch with (from django.views.generic import View)
What patch method do I use while creating an API with the View , (from django.views.generic import View) Suppose I have a class like this : from django.views.generic import View class ArticleView(View): def patch(self, request, article_id, *args, **kwargs): # How can I patch data here pass def get(self, request, *args, **kwargs): pass def put(self, request, *args, **kwargs): pass -
how to update / replace a file in a Django FileField()
I have a Django model that holds a file like so: class Excel(models.Model): the_generated_file = models.FileField() I know want to access this file with an updated version of the file. If this was a int, foat or Json field etc I could use something like: File_to_update = Excel.objects.all() File_to_update.update(the_generated_file = my_new_excel_previously_defined) But for some reason as it is of type FiledField() there is no update operation. How can I replace the old file with a new file? -
Django how to get 0 instead of null
I'm filtering a query set to get the number of visitors and pageviews but when there is no data it returns None. How to get 0 instead of None when filtering a queryset when there is no data? yesterday_visitors = queryset.filter(date__gte=yesterday, page=None).aggregate(Sum('visitors')) yesterday_page_views = queryset.filter(date__gte=yesterday, page=None).aggregate(Sum('page_views')) -
How to register specific column(field) in models.py file in admin
this is my model i like to register field 'tag' in admin.py file class Content(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) content_type = models.CharField(max_length=255) # show=models.CharField(max_length=255) show=models.ForeignKey(Show,on_delete=models.CASCADE) sponsor_link=models.CharField(max_length=255) status=models.BooleanField(default=False) added_on=models.DateTimeField(null=True) content_file=models.FileField(upload_to='media/') title = models.CharField(max_length=255) shows_name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255) description = models.CharField(max_length=500) publish_now = models.BooleanField(default=False) schedule_release = models.DateField(null=True) expiration = models.DateField(null=True) tag = models.CharField(max_length=255) category = models.CharField(max_length=255) topic = models.CharField(max_length=255) def __str__(self): return self.title I've used tagset = Content.objects.all() def content_register(): for a in tagset: admin.site.register(a.tag) content_register() But i get this error AttributeError: 'str' object has no attribute '_meta' can anyone help me here -
how to get username form django session
i am trying to get user name from session by using request.user but i am getting AnonymousUser, how do i get user name def login_two(request): if request.method == 'POST': uname = request.POST.get('name2') pwd = request.POST.get('password2') check_user = User.objects.filter(username=uname, password=pwd) if check_user: request.session['user'] = uname return redirect('index') return render(request, 'login2.html') models.py class User(models.Model): username = models.CharField(max_length=30) password = models.CharField(max_length=50) -
Why django migrations crashes using collections instead typing?
I have a class in models: class UserFilters(typing.NamedTuple): enabled_exchanges: typing.Optional[list[Exchange]] = None enabled_coins: typing.Optional[list[Coin]] = None enabled_fiats: typing.Optional[list[Fiat]] = None enabled_paymethods: typing.Optional[list[Paymethod]] = None consider_volumes: typing.Optional[bool] = None consider_vendor_rating: typing.Optional[bool] = None I run: python3 manage.py makemigrations Seems good But when I run: python3 manage.py migrate Output is: Traceback (most recent call last): File "/Users/lifr0m/PycharmProjects/p2p/manage.py", line 22, in <module> main() File "/Users/lifr0m/PycharmProjects/p2p/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 88, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 214, in build_graph self.load_disk() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 116, in load_disk migration_module = import_module(migration_path) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/lifr0m/PycharmProjects/p2p/authentication/migrations/0002_auto_20211213_1118.py", line 7, in <module> … -
Django, DRF, nginx, Jmeter: Sample Time becomes large even though there is no load on the CPU, etc
I am using Jmeter to load test the DRF, and even though the CPU and memory are not at 100%, the throughput and response time is slow. The Django + nginx and Postgres servers are separated, and both have the following specs 4CPU, 4GB memory. nginx is using docker's https-portal as shown below. version: "3" services: https-portal: image: steveltn/https-portal:1 ports: - "80:80" - "443:443" environment: DOMAINS: "my.domain.com -> http://backend:8000" STAGE: "production" volumes: - https-portal-data:/var/lib/https-portal - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./static:/static depends_on: - backend restart: always backend: build: . command: uwsgi --http :8000 --module privatine.wsgi --processes 4 volumes: - .:/usr/src/app - ./static:/usr/src/app/static expose: - 8000 env_file: - .env - .env.prod restart: always volumes: https-portal-data: Looking at the django logs, there doesn't seem to be anything wrong with django, what do you think could be causing this? generated 8302 bytes in 29 msecs (HTTP/1.0 200) 7 headers in 208 bytes (1 switches on core 0) Setting up Jmeter: Django + nginx server: DB(postgres) server: After 5 minutes of continuous loading. If there is any other information you need, please let me know. -
What's the correct way to use helpers to extend functionality in Django models?
I'm adding some extended functionallity to my models in Django. In order to not overload the model root interface (and file), i'm using some helpers as attributes of the model. What i want is to group the methods and properties into this helpers, and what i want is something like: class Product(models.Model): downloads = DownloadsHelper() # .... pass p = Product.objects.first() p.downloads.files_count(p) p.downloads.reset_permissions(p) # ... In order to not to have to pass the instance to the helper each time, I could use another approach. class Product(models.Model): def __init__(self, *args, **kwargs): super(Product, self).__init__(*args, **kwargs) self.downloads = DownloadsHelper(self) self.shipping = ShippingHelper(self) p = Product.objects.first() p.downloads.files_count p.downloads.reset_permissions() And finally, a more python-generic/conceptual way to do this stuff would be like: class Helper: def __init__(self, helped): self.helped = helped class Helper1(Helper): attribute_name = 'helloing' def hola(self): print("hola") class Helper2(Helper): attribute_name = 'goodbying' def chau(self): print("chau") class Helped: def __init__(self): self._install_helpers() def _install_helpers(self): for helper in self.helpers: setattr(self, helper.attribute_name, helper(self)) class MyHelped(Helped): helpers = [Helper1, Helper2] h = MyHelped() h.helloing.hola() h.goodbying.chau() And the question is: Is this last approach a correct way /good practice to do the stuff from a pythonic-OOP and "Djangoid" point of view. Has this any problem? Thanks for reading! -
Test database for Django + Heroku. Error creating the test database: permission denied to create database
I'm trying to run the tests for my Django project. I wrote this project some time ago, I had different settings then and tests were passing. Now I changed settings and deployed it on Heroku with Heroku Postgres database. Everything works fine already except I can't run tests. I've tried many different settings and nothing worked. Most of the time I'm getting this error: permission denied to create database My last setting is following the instruction from this article on medium Basically I have added 2nd Heroku Postgres database, add settings like below (but with valid variables of my heroku databases): if 'test' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd7osdssadag0ugv5', 'USER': 'lhwwasadqlgjra', 'PASSWORD': '1524f48a2ce41177c4ssdadasd3a11680b735302d14979d312ff36', 'HOST': 'ec2-54-75-2326-118.eu-west-1.compute.amazonaws.com', 'PORT': 5432, 'TEST': { 'NAME': 'd7osdssadag0ugv5', } } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd7hasadas9hqts5', 'USER': 'nybkduadsdgqot', 'PASSWORD': 'bb535b9cdsfsdfdsfdsfac54851f267444dd8cc230b2a786ab9f446', 'HOST': 'ec2-54-247-132-38.eu-west-1.compute.amazonaws.com', 'PORT': 5432, 'TEST': { 'NAME': 'd7hasadas9hqts5', } } } Then run python manage.py test --keepdb in my venv. Then I get an error: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable … -
Passing Django variable to an accordion attribute in HTML
I am newbie to Django and apologize in advance for such a basic question to most of you, but I looked for similar questions all over and haven't encountered a workable solution. I am trying to create a Bootstrap Accordion for each item of a Django for-loop. So a list of items is displayed, and when you click on one item, the description of it will collapse to show. The segment currently looks like this using this template: <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </head> <body> {% for item in items %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-parent="#accordion" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> {{ item }} </button> </h2> <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> {{ item.description }} </div> </div> </div> </div> </body> Now, this is giving the same value (collapseOne) to data-bs-toggle, aria-controls and id of accordion-collapseclass(collapsing element) for every for-loop item, resulting in all the accordion items collapsing when one of them is clicked though I want only the clicked one to collapse. So I tried to pass the Django variable as such: {{ item }} in place of collapseOne {{ forloop.counter }} in place of collapseOne The …