Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django use TextInput widget with ModelMultipleChoiceField
I'm using Django 4.2 and trying to make TextInput work with ModelMultipleChoiceField. I am using standard Django template engine and afraid that if I will have too many model objects (which will most likely happen) then SelectMultiple widget on the page will be cluttered with too many options (or even cut some of the option due to exceeding the limit) so I would like to avoid it. I use pk as identifier for both Reports and Environments. Ideally I would like to have frontend field which will take strings like "1, 2, 3, 4" and then convert it to pk list ([1, 2, 3, 4]) for ModelMultipleChoiceField to validate and then for form to save in DB. This is how it looks like for now (simplified): models.py: class Report(models.Model): environments = models.ManyToManyField(Environment) views.py: class CreateReport(CreateView): model = Report form_class = ReportForm template_name = 'reports/new/new.html' forms.py: class ReportForm(forms.ModelForm): class Meta: model = Report fields = '__all__' def __init__(self, *args, **kwargs): super(ReportForm, self).__init__(*args, **kwargs) self.fields['environments'] = forms.ModelMultipleChoiceField(queryset=Environment.objects.all()) How to use widget TextInput with ModelMultipleChoiceField? Or is there maybe a better way to solve this problem with too many option (I tried searching for asynchronous JS querying the server but unfortunately didn't understand … -
Django compressor can't connect to redis
I have a Django 2.2 ASGI application running Python 3.8.10 deployed on AWS in a Docker container. The app is using django-compressor==4.1.0 and django-redis==5.2.0 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "{0}/{1}".format(str(ENV_STR("REDIS_URL", "6379")), 0), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "IGNORE_EXCEPTIONS": True, }, }, } COMPRESS_CACHE_BACKEND = "default" REDIS_URL is defined as: redis://*****-*****.******.ng.0001.use1.cache.amazonaws.com:6379 The get_templatetag_cachekey() function from django-compressor seems to be trying to connect to redis to get a cache key, however this connection is failing and throwing error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 371, in run_asgi result = await app(self.scope, self.receive, self.send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 59, in __call__ return await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/asgi2.py", line 17, in __call__ await instance(receive, send) File "/usr/local/lib/python3.8/site-packages/channels/http.py", line 192, in __call__ await self.handle(body_stream) File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 448, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/local/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 490, in thread_handler return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/channels/http.py", line 244, in handle response = self.get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), … -
How to maintaining modal to process view function?
I'm learning Django and trying to clone Instagram myself. I created a modal using bootstrap, and when I click the Button trigger modal, myModal pops up. there is an id=follow-form where the person follows the user they follow. When I submit this form, I want to follow 'following.user' while maintaining the modal. The code I wrote closes the modal and goes to following.user's profile. how do i solve it? models.py class User(AbstractUser): followings = models.ManyToManyField('self', symmetrical=False, related_name='followers') urls.py app_name = 'accounts' urlpatterns = [ path('profile/<username>/', views.profile, name='profile'), path('follow/', views.follow, name='follow'), ] views.py def follow(request, user_pk): User = get_user_model() person = User.objects.get(pk=user_pk) if request.user != person: if person.followers.filter(pk=request.user.pk).exists(): person.followers.remove(request.user) is_followed = False else: person.followers.add(request.user) is_followed = True context = { 'is_followed': is_followed, } return JsonResponse(context) return redirect('accounts:profile', person.username) profile.html <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal"> Following {{ person.followings.count }} </button> <!-- modal --> <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">following list</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {% for following in person.followings.all %} <p> <a href="{% url 'accounts:profile' following.username %}">{{ following.username }}</a> <!-- Follow --> <form id="follow-form" data-user-id="{{ person.pk }}"> {% csrf_token %} {% … -
QuerySet filter with multiple ManyToMany field lookups does not behave as expected
I am trying to write a simple Django filter which doesn't seem to work as expected. I have a User model and a Vacation model and I want to write a query to get all users that are not on vacation. class User(models.Model): vacation = models.ManyToManyField('Vacation') class Vacation(models.Model): start = models.DateTimeField() end = models.DateTimeField() The obvious solution I tried was: now = timezone.now() User.objects.exclude(vacation__start__lte=now, vacation__end__gt=now) This doesn't work. This queryset will also exclude any User objects that have a future vacation (start time and end time after now). I think this is a result of the combination of the exclude and the many to many lookup but I can't find any documentation on why this behaves this way and there doesn't seem to be a way to get to the simple result using simple queryset chain. The only way I've got this to work is by querying User objects on vacation and then running another queryset excluding users with those IDs. Ex: users_on_vacation = User.objects.filter(vacation__end__gte=now, vacation__start__lte=now).values_list('pk', flat=True) users_not_on_vacation = User.objects.exclude(pk__in=users_on_vacation) Is there a simpler way to write this filter? -
ModueNotFoundError: No module name 'registration'
I ran the python manage.py runserver command on my django project and I ran into this error: Traceback (most recent call last): File "C:\Users\acer\PycharmProjects\CollegeCareerApp\collegecareerapp\manage.py", line 22, in <module> main() File "C:\Users\acer\PycharmProjects\CollegeCareerApp\collegecareerapp\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'registration' PS C:\Users\acer\PycharmProjects\CollegeCareerApp\collegecareerapp> python manage.py ruserver Traceback (most recent call last): File "C:\Users\acer\PycharmProjects\CollegeCareerApp\collegecareerapp\manage.py", line 22, in <module> main() File "C:\Users\acer\PycharmProjects\CollegeCareerApp\collegecareerapp\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\acer\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in … -
Django REST framework: passing additional contextual data from view to serializer
I have a Django REST framework view (generics.GenericAPIView). In it, I want to pass contextual data (the original request received by the view) to a serializer. As per Serializer - Including extra context in Django Rest Framework 3 not working, I've overridden the get_serializer_context() method inherited from Rest Framework's GenericAPIView. My view looks like this: class MyView(GenericAPIView): def get_serializer_context(self): context = super().get_serializer_context() context.update({"original_request": self.request}) return context def put(self, request, *args, **kwargs): my_object = ... get object from database ... serializer = MySerializer(my_instance=my_object, validated_data=request.data) if serializer.is_valid(): logger.warning("MyView/put() - request: " + str(request)) .... other stuff ... My serializer: class MySerializer(): def update(self, my_instance, validated_data): logger.warning("MySerializer/update() - context: " + str(self.context)) ... other stuff ... My view's logs shows that the request details are present: MyView/put() - request: <rest_framework.request.Request: PUT '<URL>'> ... but they are not passed to the serializer: MySerializer/update() - context: {} I'm suspecting that it's because the self.request value in get_serializer_context() is not populated or is not the same as the one supplied in the view's put() method. I've also tried including the context data directly during the instantiation of the serializer, as per https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context but that didn't work either - again, the contextual data was not passed from … -
how to make User instance
i have two applications in my django project accounts and bp in account application i have a custom user model accounts/models.py: class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) is_admin = models.BooleanField(default=False) #other fields accounts/views.py: def signup(request): form = RegistrationForm() if request.method == 'POST': registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): user = registration_form.save(commit=False) user.is_active = True user.save() user_id=user.id return redirect(reverse('bp:profile',kwargs={'user_id':user_id})) return render(request,'signup.html',{'form':form}) bp/models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #other fields bp/views.py def profile(request,user_id): if request.method =='POST': form = NewProfileForm(request.POST) if form.is_valid(): profile=form.save(commit=False) profile.user=User.objects.get(id=user_id) profile.save() else: form=NewProfileForm() return render(request,'profile.html',{'form':form}) bp/urls.py : urlpatterns = [ path('profile/<int:user_id>/',views.profile, name='profile'), ] after creating the user it redirect me to profile html after writing the data when i submit it show me this error can you help me please -
Connecting Postgresql to Django
I am trying to connect 2 databases to django project so I can use one for develop and another on production My setting file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES["default"].update(db_from_env) export DATABASE_URL=path_to_database When i try to run server I got this error: "django.db.utils.NotSupportedError: PostgreSQL 12 or later is required (found 11.18)." But when i write psql in terminal I got: psql (14.7 (Homebrew), server 15.2) And PostgrSQL@11 is not installed on my mac -
how can i call the instance of a model like we do with request.user for the user model
I'm working on a project where users can create a specific store that will only have their own product, but beyond that, there is a main store whose products from different users are displayed, so I don't know how to do it. filter allowing me to display specific products for each user. I know that with the user we make request.user so how to do with other models? my models file class Shop(models.Model): name= models.CharField(max_length=60, verbose_name='nom') adress= models.CharField(max_length=250, verbose_name='adresse') description=models.TextField(max_length=1000) logo=models.ImageField( blank= True ,null=True ) horaire=models.CharField(max_length=100) user= models.ForeignKey(User, blank= True , null=True ,verbose_name="utilisateur", on_delete=models.CASCADE) date= models.DateTimeField(auto_now_add=True, verbose_name='date de création') data=models.JSONField(null=True,blank=True) def __str__(self) -> str: return str(self.name) my views file def products_list(request): shop=Product.objects.all() products= Product.objects.filter(shop=shop) return render(request , 'shop/product_list', locals()) def home(request): products = [{**vars(p), 'image_url': (p.image and p.image.url) or p.image_url} for p in Product.objects.all().order_by('-name')] special_product= Product.objects.filter(vip =True) productOfday=Product.objects.filter(product_of_day= True ) return render(request, 'shop/home.html', locals()) def create_shop(request): form =CreateShopFrom() error='' if request.method == 'POST': form =CreateShopFrom(request.POST) if form.is_valid: form.save() else: error='identifiants Invalides' return redirect('shop') return render(request, "shop/create_shop.html",locals()) I tried that but without success: def products_list(request): shop=Product.objects.all() products= Product.objects.filter(shop=shop) return render(request , 'shop/product_list', locals()) -
Display an expression in an HTML table?Django
I have an expression as follows (text='FX506LH | 8GB RAM | 512GB SSD | i5 | 4GB VGA ا Laptop Asus FX506LH') I want to enter it in a table in a section, what solution do you suggest? Best regard This is what I am looking for I think the image is telling. -
Can't migrate properly a column in a Django database. Anyone know why?
So I'm working on a Django project and I did some changes to my user.py model. I simply added a boolean value to it. When I run the manage.py makemigrations <my app> everything runs smoothly, but when I run manage.py migrate it crashes and displays de following error: django.db.utils.OperationalError: no such column: ""is_admin"" Which I find odd because it is on my model file and I even got to make the manage.py makemigrations <my app> command properly. Does anyone know what's going on? If it makes it more clear I can put the whole error in the comments but I didn't want to add it here since it's very long. I even tried changing the name of my attribute but it doesn't seem to matter. The error still says "is_admin" is not a column. I've tried commenting/deleting the line of code in the model and run the migrations again but it seems kinda stuck on that error. -
keep getting this error message when launching django server
Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs)` File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Python310\lib\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 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'psychology_app' ` That is the command line after using the cd pyschology_project to get into the directory when i try to launch my django server using python manage.py runserver i get the above error -
I am trying to deploy Django project on render.com and have some troubles with Gunicorn
I have project which is working in dev environment. I am trying to deploy it on render.com. According to logs build is successful. But then Gunicorn starts and booting workers for a long-long time. Deploy failed without any error message. Apr 19 10:56:52 PM 125 static files copied to '/opt/render/project/src/myproject/staticfiles', 349 post-processed. Apr 19 10:56:53 PM Operations to perform: Apr 19 10:56:53 PM Apply all migrations: admin, auth, avito, contenttypes, sessions Apr 19 10:56:53 PM Running migrations: Apr 19 10:56:53 PM No migrations to apply. Apr 19 10:56:54 PM ==> Uploading build... Apr 19 10:57:04 PM ==> Build uploaded in 8s Apr 19 10:57:05 PM ==> Build successful 🎉 Apr 19 10:57:05 PM ==> Deploying... Apr 19 10:57:53 PM ==> Starting service with 'cd ./myproject && gunicorn -b :8000 --preload --log-level debug myproject.wsgi' Apr 19 10:58:00 PM [2023-04-19 22:58:00 +0300] [51] [INFO] Starting gunicorn 20.1.0 Apr 19 10:58:00 PM [2023-04-19 22:58:00 +0300] [51] [DEBUG] Arbiter booted Apr 19 10:58:00 PM [2023-04-19 22:58:00 +0300] [51] [INFO] Listening at: http://0.0.0.0:8000 (51) Apr 19 10:58:00 PM [2023-04-19 22:58:00 +0300] [51] [INFO] Using worker: sync Apr 19 10:58:01 PM [2023-04-19 22:58:01 +0300] [52] [INFO] Booting worker with pid: 52 Apr 19 10:58:01 PM [2023-04-19 … -
File "<frozen importlib._bootstrap>", No module name 'material' | AWS ec2 instance, django project
~/blog/blog$ python3 manage.py makemigrations Traceback (most recent call last): File "/home/ubuntu/blog/blog/manage.py", line 22, in <module> main() File "/home/ubuntu/blog/blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/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 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'material' when i tried to run this coomand makemigrations on aws ec2 for my django project, it appeared No module named 'material' how can I fix this problems? -
DJANGO - python manage.py inspectdb - ERROR - TypeError: translation() got an unexpected keyword argument 'codeset'
I have a database with tables and relationships between those tables in MySQL Workbench and I am trying to connect/integrate with Django. I have specified it settings.py in my Django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'data_storage', 'USER': 'root', 'PASSWORD': 'my_password', 'HOST': 'localhost', 'PORT': '3306', } } When I run python manage.py inspectdb or python manage.py inspectdb > DjangoWebPage/models.py in (VS Code) terminal, it shows an ERROR: TypeError: translation() got an unexpected keyword argument 'codeset' Full prompt: (.venv) PS C:\Users\Prakse\Desktop\DjangoApp> python manage.py inspectdb Traceback (most recent call last): File "C:\Users\Prakse\Desktop\DjangoApp\manage.py", line 22, in <module> main() File "C:\Users\Prakse\Desktop\DjangoApp\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Prakse\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\contrib\auth\models.py", line 94, … -
Filtering objects by date
My app has an optional date selection. All objects created on that day will be filtered by the selected date. I have a model: class MyModel(models.Model): name = = models.CharField() ... pub_date = models.DateTimeField(auto_now_add=True) Objects will be added every day and there will be a lot of them in the future. I planned to implement filtering with something like this: object = MyModel.objects.filter(pub_date__year=year pub_date__month=month, pub_date__day=day) But it occurred to me that if I make a separate model for the date, link it to the main model and filter by related_name, then the query will be more optimal and faster. class PubDateModel(models.Model): pub_date = models.DateTimeField(auto_now_add=True) class MyModel(models.Model): name = = models.CharField() ... pub_date = models.ForeignKey(PubDateModel, related_name='my_models') If I understand correctly, then my request will look like this: pub_date = get_object_or_404(PubDateModel, pub_date=date) objects = pub_date.my_models.all() Which option will be faster with a very large number of objects in the database? -
Page not found (404) at /user_signup in Django
Getting 404 error on signup and some more URLs. /login, /logout, /admin is working perfectly. I'm making a web app that lets a user login, logout, search a flight, book a flight and view the bookings made. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('search_flights/', views.search_flights, name='search_flights'), path('book_flight/<int:flight_id>/', views.book_flight, name='book_flight'), path('my_bookings/', views.my_bookings, name='my_bookings'), path('login/', views.user_signup, name='login'), path('signup/', views.user_signup, name='signup'),] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .models import Flight, Booking from django.contrib.auth.forms import UserCreationForm from .forms import SignUpForm, SignInForm, EditProfileForm def home(request): flights = Flight.objects.all() return render(request, 'home.html', {'flights': flights}) @login_required def search_flights(request): if request.method == 'POST': date = request.POST.get('date') time = request.POST.get('time') flights = Flight.objects.filter(date=date, time=time) return render(request, 'search_flights.html', {'flights': flights}) return render(request, 'search_flights.html') @login_required def book_flight(request, flight_id): flight = Flight.objects.get(id=flight_id) if request.method == 'POST': # Check if seats are available if flight.seats_available() > 0: # Book the ticket booking = Booking.objects.create(flight=flight, user=request.user) return redirect('my_bookings') else: # Show error message return render(request, 'book_flight.html', {'flight': flight, 'error': 'No seats available.'}) return render(request, 'book_flight.html', {'flight': flight}) @login_required def my_bookings(request): bookings = Booking.objects.filter(user=request.user) return render(request, 'my_bookings.html', {'bookings': bookings}) def user_login(request): … -
Why am I getting 403 for POST with DRF and rest_framework_api_key?
I am getting a 403 response from the server in my new Django app. It is very simple. I don't even have models, I just want to return an audio file, but I want to do it through an API. Because of that, since I am not going to have users, I need an API key, and I found that I can use the Django REST framework and the REST framework API key modules. I have followed the quickstarts and can't seem to get a response. It was working before, but it was authenticating through CSRF, and like I said, it is going to be an API, so I won't have CSRF cookies. Here is the view I am using: @api_view(["POST"]) def tts_view(request): data = request.POST voice_name = data.get("voice_name") text = data.get("text") if not voice_name or not text: return JsonResponse({"error": "Missing voice_name or text"}, status=400) return JsonResponse({"wav": text_to_wav(voice_name, text)}, status=200, safe=False) The settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_api_key', 'TTS', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] } And the fetch (the API key is just a test, so it doesn't matter): fetch('/create-speech', … -
An issue with OTP verification while using python-social-auth
I am attempting to implement a third-party login flow that redirects to an OTP verification screen before redirecting to a dashboard screen. It seems that after completing the OTP verification, when you use the command return redirect(reverse('social:complete', args=(backend_name,))), an 'AuthMissingParameter' error occurs with the message 'Missing needed parameter state'. I am not sure what's wrong with my code, any tips/suggestions are greatly appreciated. setting.py django_settings.SOCIAL_AUTH_PIPELINE = [ 'common.djangoapps.third_party_auth.pipeline.parse_query_params', 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'common.djangoapps.third_party_auth.pipeline.show_otp_form', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ] pipeline.py @partial.partial def show_otp_form(strategy, details, backend, request, *args, **kwargs): is_pass_otp = strategy.session_get("is_pass_otp", None) if not is_pass_otp: request.session['backend_name'] = request.backend.name return redirect('otp') views.py def otp_form(request): if request.method == 'POST': ....logic verify code OTP........ request.session['is_pass_otp'] = True backend_name =request.session['backend_name'] return redirect(reverse('social:complete', args=(backend_name,))) return TemplateResponse(request, 'otp/otp.html', {}) -
Django HTTPS on EC2 without a domain name?
I have a Django app working on HTTP with an EC2 instance running Amazon Linux 2. I was hoping to get HTTPS working without a domain name. How would I get a self signed certificate to work with the public IPv4 address assigned to my EC2 instance and then launch the django app on EC2 with HTTPS? Is it even possible? I have tried making a certificate using openssl and running the django app using django-extensions and Werkzeug using python manage.py runserver_plus but the app crashes on ec2 (works fine locally). I have tried a few other python packages with the same results. Any help is appreciated. -
Why coming this error: UnicodeDecodeError at /api/image/
My goal is to show the image's URL in response but it's not working. I getting errors. Here actually is it possible to return request.data.get('img')? Can you please give me a solution? serializer.py: class ImageSerializer(serializers.Serializer): img = serializers.ImageField(required=False) views.py: class ImageView(APIView): def post(self, request): serializer = ImageSerializer(data=request.data) return Response( { "processed_image_data": request.data.get('img') }, status=status.HTTP_200_OK ) errors: UnicodeDecodeError at /api/image/ 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Request Method: POST Request URL: http://127.0.0.1:8000/api/image/ Django Version: 4.2 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Exception Location: D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\rest_framework\utils\encoders.py, line 50, in default Raised during: app.views.ImageView Python Executable: D:\23_Spondon-Bhai\2_Image-Process\venv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\23_Spondon-Bhai\\2_Image-Process', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\23_Spondon-Bhai\\2_Image-Process\\venv', 'D:\\23_Spondon-Bhai\\2_Image-Process\\venv\\lib\\site-packages'] Server time: Wed, 19 Apr 2023 17:23:42 +0000 Unicode error hint The string that could not be encoded/decoded was: ���� Traceback Switch to copy-and-paste view D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\django\core\handlers\exception.py, line 55, in inner return inner else: @wraps(get_response) def inner(request): try: response = get_response(request) … except Exception as exc: response = response_for_exception(request, exc) return response return inner Local vars D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\django\core\handlers\base.py, line 220, in _get_response self.check_response( response, middleware_method, name="%s.process_template_response" % (middleware_method.__self__.__class__.__name__,), ) try: response = response.render() … except Exception as e: response = … -
Cannot Configure (Error While) Django setting in nginx
My server cannot find the files, it says no files found . I have following configuration user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; } http { sendfile on; tcp_nopush off; tcp_nodelay off; keepalive_timeout 265; types_hash_max_size 2000; and Server is server { listen 8000; server_name joshna.co www.joshna.co joshna.net www.joshna.net; location = /favicon.ico { access_log off; log_not_found off; } location /static/{ autoindex on; alias /home/bsyal/mysite/mypro/static; } location /media/{ autoindex on; alias /home/bsyal/mysite/mypro-project/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Server cannot find file, I have gone thhrough others solution but could not figured out -
Rest API create class based view using a mixin
I have a view inheriting from APIView and another custom mixin. None of the APIView methods is defined in the view but it is used only for declaring it as view. I need the url from only the mixin. But the mixin's url is never found django.urls.exceptions.NoReverseMatch. I am not sure how exactly to explain the problem therefore, I will provide the code: class TypeAPI(TwoFieldListMixin, APIView): queryset = Type.objects.all() permission_classes = [IsAuthenticated] class TwoFieldListMixin: query_field: str = "id" name_field: str = "name" @action(detail=False, methods=["GET"], url_name="id_code_list") def id_code_list(self, request: Request, *args: None, **kwargs: Any) -> Response: self.query_field = ( request.query_params.get("query_field", None) or self.query_field ) self.name_field = ( request.query_params.get("name_field", None) or self.name_field ) queryset: QuerySet[Any] = self.filter_queryset(self.get_queryset()).values( self.query_field, self.name_field ) serializer: ICListSerializer = ICListSerializer(queryset, many=True) return Response(serializer.data) url.py urlpatterns = [ path("types/", TypeAPI.as_view(), name="types"), ] + router.urls Test that I am writing: def test_pt_detail_api(self)->None: res = self.client.get(f"/api/v1/na/types/id_code_list/") res = self.client.get(url) assert res.status_code == 200 Here is the error: /usr/local/lib/python3.10/site-packages/django/urls/resolvers.py:802: NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'types-id_code_lis... Or applying some variations give an error: 'request_path': '/api/v1/na/types/id_code_list/', 'exception': 'Resolver404'} Question is how can I achieve creating a simple view which inherits from a mixin and does nothing else. -
Can anyone help me figure out what's happening with this html
So i am making this ecommerce for fun and got this weird bug That is html for new-skincare.html page. But then i have this perfumes page which is exactly the same as skincare page i just changed filter options in html so instead {% for skincare_item in skincare %} i used {% for perfume in perfumes %} . This is skincare.html {% extends 'base.html' %} {% block new_products%} {% load static %} {% load item_sizes %} <section class="page-header"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="content"> <h1 class="page-name">New Arrivals</h1> <ol class="breadcrumb"> <li><a href="{% url 'product-list'%}">Home</a></li> <li class="active">new skincare</li> </ol> </div> </div> </div> </div> </section> <section class="products section"> <div class="container"> <div class="row"> <div class="col-md-3"> {% block widget %}{% include 'widget.html'%}{% endblock widget%} </div> <div class="col-md-9"> <div class="row"> {% for item in skincare %} {% if item.is_new %} <div class="col-md-4"> <div class="product-item"> <div class="product-thumb"> <!-- TODO: CHANGE PRICE IF SALE --> {% if item.sale %} <span class="bage">Sale</span> {% endif %} {% if item.is_new %} <span class="new">New</span> {% endif %} {% load display_image %} {% static 'base/static/catalog/sku/'|add_str:item.front_image|add_str:'.webp' as front_image %} <img class="img-responsive" src="{{front_image}}" alt="product-img" /> {% comment %} {% endfor %} {% endcomment %} <div class="preview-meta"> <ul> <li> <span data-toggle="modal" data-target="#itemModal{{forloop.counter}}"> <i class="tf-ion-ios-search-strong"></i> … -
Dict in Django TemplateView throws Server Error 500, ListView helps for DetailView
I'm attempting to utilise the dictionary prices to retrieve the stock prices from yahoo finance. And the Django database is where I get my stock tickers. In HTML, I am unable to utilise dict. Please review the code samples I've included below. If the datatype for the variable "prices" is likewise a dict, Django produces a 500 server error. I need to pull stock prices from yahoo finance and show stock tickers from the Django database in HTML. How can I fix it? Please give me some advice on how to show my coins using ListView. In order to assist me with DetailView, which is crucial to my online application. I want to say thank you. Model: class Coin(models.Model): ticker = models.CharField(max_length=10) def __str__(self): return self.ticker View: class BucketView(LoginRequiredMixin, TemplateView): template_name = 'coinbucket/bucket.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) symbols = [symbol.ticker for symbol in Coin.objects.all()] prices = {} for symbol in symbols: ticker = yf.Ticker(symbol) price = ticker.history(period='1d')['Close'][0] prices[symbol] = f'$ {price:.6f}' context["prices"] = prices return context Template: {% for coin in coins %} <div class="col-12 col-md-8 my-2"> <div class="card"> <div class="card-body"> <div class="row"> <div class="col">{{ coin }}</div> <div class="col">{{ prices[coin] }}</div> </div> </div> </div> </div> {% endfor %} …