Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my django web-app login form not working?
I've tried to add login form to my tasks web-app, but something goes wrong and I can't login to my created admin user. After click on the login button page just clearing up and my url changes to that. I have no idea how to fix it, help me please. urls.py urlpatterns = [ path('', TaskList.as_view(), name='tasks'), path('login/', CustomLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('task/<int:pk>', TaskDetail.as_view(), name='task'), path('task-create/', TaskCreate.as_view(), name='task-create'), path('task-edit/<int:pk>', TaskUpdate.as_view(), name='task-edit'), path('task-delete/<int:pk>', TaskDelete.as_view(), name='task-delete'), ] views.py class CustomLoginView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('tasks') login.html <h1>Login</h1> <form metrhod="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Login"> </form> -
Do I need cstf protection when backend and frontend have different domains?
I have: React app: https://myreact.com Django + DRF: https://mydjango.com React has a form that when submitted sends a POST request to mydjango.com/handle-form with all the cookies, because I speicfy withCredentials: true in my ajax request (thus all the cookies are sent). As I can see it, there's no way to perform csrf attack, because browser stores cookies only for myreact.com. And if an attacker creates a domain myreact2.com with the same exact form (that upon submitting sends POST request to mydjango.com/handle-form), cookies from myreact.com won't be sent, meaning there's no csrf attack. The questions: Am I right? Will browser store cookies only in myreact.com or in both domains, when I make an ajax request from myreact.com to mydjango.com and mydjango.com in response sends a Set-Cookie header? I understand how it would work, when both frontend and backend shared the same domain. CSRF attack could be very possible without csrf token or something else. But my case bothers me. -
Kindly advise me on how to go about this
I have an assignment from a bootcamp to build a price compare website api. As an advanced BACKEND developer, kindly advise me on how to go about it after getting jumia and ebay developer api's. Will I save their data into my database and query from there? If yes, how would their price change reflect in my database? Don't laugh please, I am just a begginer django. -
How do I add another field to my model without getting an error?
I added another field to my Listing() model called highest_bid. However, when I try to look at the listing model in the /admin page I get the OperationalError: no such column: auctions_listing.highest_bid After adding this field I tried using makemigrations, but it said that there were no changes and I also tried using migrate but that also said that there was nothing to migrate. I also tried removing null=True on the field but that did not change anything. How do I add this field without getting an error? models.py: class Listing(models.Model): ... highest_bid = models.FloatField() # highest_bid = models.FloatField(null=True) # they both returned the same error -
MongoDB connection with Django i am getting below error after configuration
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'django' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
django: How do i save form in django without the django forms?
I am trying to save a contact form, but i am not using the django form but instead the input field. I am getting the name, email address and message body from the html templates using input field like this <input type="text" id="name"> but the form doesn't get any data from the input field, it seems i am missing something but i cannot find out what is happening. I have tried passing in the name, email and message into id="name" id="email" id="message" but nothing still happends. This is my code index.html <form method="POST"> {% csrf_token %} <input type="text" id="name" value="" /> <input type="text" id="email" value="" /> <input type="text" id="address" value="" /> <button type="button">Let's Withdraw</button> </form> views.py if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") message= request.POST.get("message") print("Message Sent") return redirect("core:index") else: pass -
What to learn to make production ready Django apps after Django basics
I have learned Django and Sqlite and I'm pretty comfortable with it but I only know how to make a app run on my machine and nothing about production. I know i need to learn Nginx Guicorn Postgres and hosting but i don't know where to learn. I have watched some tutorials on youtube but that has only consfused me. Can you recommend some tutorials for deployment of Django projects and What other things or practices do i need to learn for making production grade webapps. -
I keep getting <WSGIRequest GET: '/create-link-token'>; trouble connecting django to plaid api
I'm trying to connect my Django backend to Plaid's API but I've been stuck on how to only return the body from the Object. This is the traceback I'm getting: Request Method: GET Request URL: http://127.0.0.1:8000/create-link-token Django Version: 4.0.6 Python Version: 3.9.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Daniel Tshibangu\Desktop\mukadi\plaid-integration\python\backend\app\views.py", line 82, in create_link_token response = client.link_token_create(request) File "C:\Python39\lib\site-packages\plaid\api_client.py", line 769, in __call__ return self.callable(self, *args, **kwargs) File "C:\Python39\lib\site-packages\plaid\api\plaid_api.py", line 7404, in __link_token_create return self.call_with_http_info(**kwargs) File "C:\Python39\lib\site-packages\plaid\api_client.py", line 831, in call_with_http_info return self.api_client.call_api( File "C:\Python39\lib\site-packages\plaid\api_client.py", line 406, in call_api return self.__call_api(resource_path, method, File "C:\Python39\lib\site-packages\plaid\api_client.py", line 193, in __call_api response_data = self.request( File "C:\Python39\lib\site-packages\plaid\api_client.py", line 452, in request return self.rest_client.POST(url, File "C:\Python39\lib\site-packages\plaid\rest.py", line 264, in POST return self.request("POST", url, File "C:\Python39\lib\site-packages\plaid\rest.py", line 150, in request r = self.pool_manager.request( File "C:\Python39\lib\site-packages\urllib3\request.py", line 78, in request return self.request_encode_body( File "C:\Python39\lib\site-packages\urllib3\request.py", line 170, in request_encode_body return self.urlopen(method, url, **extra_kw) File "C:\Python39\lib\site-packages\urllib3\poolmanager.py", line 376, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "C:\Python39\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen httplib_response … -
Style Django Form Field
I have a form which has one ChoiceField. I want to add 'form-control' class to this field.What i am doing is delivery_type = ChoiceField(choices=Student.DELIVERY_CHOICES, widget=Select(attrs={'class':'form-control'})) But I am getting this error TypeError: __init__() missing 1 required positional argument: 'master' Here is my models.py file: class Student(models.Model): DELIVERY_CHOICES = ( ('Normal', 'Normal (7 working days) (100 BDT Per Semester)'), ('Urgent', 'Urgent (3 working days) (200 BDT Per Semester)'), ) delivery_type = models.CharField(max_length=100, choices=DELIVERY_CHOICES) Can anyone help me with this? -
Querying a foreign key field in creation form django
i have 3 models, the first one is user a custom user model to handle permissions with two boolean fields, the second is lead with a foreign key of user , the third is event with date and customer foreign key fields, when creating an instance of event i want to see only leads related to the logged in user within the creation form. I tried some solutions like passing the query in the init function with user=None in parameters with an if user: condition, defining a function that returns the queryset that didn’t work it popped out the error« function object has no attribute » and this where i got with getting the error « View.init() takes 1 positional argument but 2 were given », any help will be appreciated #models class Lead(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,null=True, blank=True, on_delete=models.SET_NULL) class Event(models.Model): Lead = models.ForeignKey(Lead,null=True, on_delete=models.CASCADE) #views class EventCreateForUser(LoginRequiredMixin,CreateView): template_name = "leads/event_create.html" form_class = EventForm def get_form_kwargs(self): kwargs = super(EventForm, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def get_success_url(self): return reverse("leads:lead_list") def form_valid(self, form): event = form.save(commit=False) event.Lead.User = self.request.user form.save() messages.success(self.request, "You have successfully created a lead") return super(EventCreateForUser, self).form_valid(form) #forms class EventForm(ModelForm): class Meta: model = Event widgets = { … -
Script is not working in html for my django project
first of all. It's my first time asking a question here. So if I do sth wrong I'm sorry for that. As I am pretty new to programming I really don't get where the problem is with my html right now. Basically I want the Script to do aa new Textbox so that I can do more and more Questions. Kinda like in the image below. enter image description here The Code for my html right now looks like that. enter image description here I would be really grateful if somebody could help me because I really don't know why the script isn't working at all. -
Remote Access to Django's Internet Server
I have a remote (virtual) Ubuntu development station, on which I installed Django, and on which I'm running "manage runserver". Now, I need to browse my project's URLs, and debug their view functions line by line. But I fail to remotely use the web browser on the remote development station (there was time that I succeeded doing so, but it was horribly slow). I therefore would like to enable the web browser on my own laptop to connect the web server of Django that's running on the remote development station. Is there a way to do so? -
django test client returns 404, but works in the shell
This code works fine in the shell, but if you run it through python manage.py test it throws a 404 error, what could be the problem? test_urls.py from django.test import Client, TestCase class StaticURLTests(TestCase): def setUp(self): self.guest_client = Client() def test_homepage(self): response = self.guest_clientw.get("/") self.assertEqual(response.status_code, 200) error: ❯ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_homepage (posts.tests.test_urls.StaticURLTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/finegorko/Development/Yandex.Practicum/hw03_forms/yatube/posts/tests/test_urls.py", line 10, in test_homepage self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.003s FAILED (failures=1) Destroying test database for alias 'default'... -
age filter in django
I have products in my ecommerce. How can I group them in age groups like child, adult, senior? But one product can be on morethan one group. Example a cloth can be for both adult and senior. What method should I choose? -
Following error raised: TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist
I am trying to handle errors in my Django project and I keep receiving the following message: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 132, in __call__ response = self.get_response(request) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/base.py", line 140, in get_response response = self._middleware_chain(request) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/exception.py", line 57, in inner response = response_for_exception(request, exc) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/exception.py", line 139, in response_for_exception response = handle_uncaught_exception( File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/core/handlers/exception.py", line 184, in handle_uncaught_exception return callback(request) File "/Users/Tom/Desktop/squeasy /tasks/views.py", line 31, in handler500 response = render(request, template_name) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/Tom/.local/share/virtualenvs/squeasy_-djXBooHN/lib/python3.9/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: 500.html For my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR /'squeasy/tasks/templates/tasks'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I have also tried: 'DIRS': [], 'APP_DIRS': True, and 'DIRS': [os.path.join(BASE_DIR, 'templates')], and 'DIRS': [BASE_DIR/'templates'], I have no other errors when running templates normally, it is only when I force an error. I have the following views.py to handle 400, 403 and 404 error requests def handler400(request, exception, template_name = "400.html"): response = … -
an exception while running dockerized Django project locally which is hosted on google cloud run
I have cloned a dockerized GeoDjango project and want to run it locally which is hosted on google cloud run. I have also tried to run the project without docker by running python manage.py runserver but all in vain. This is the exception error which is occurring Exception: No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets were found. I created the image by using this command: docker build . -t your_image_name when I run this command: docker run -p 9090:8080 -e PORT=8080 my_image_name It gives the error traceback given below. Error traceback: [2022-07-24 08:16:45 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2022-07-24 08:16:45 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2022-07-24 08:16:45 +0000] [1] [INFO] Using worker: gthread [2022-07-24 08:16:45 +0000] [7] [INFO] Booting worker with pid: 7 [2022-07-24 08:16:49 +0000] [7] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.9/site-packages/gunicorn/util.py", line 359, … -
How can I use Serializer for logout?
I'm very new to Django and preparing for the DRF Session. I have to write code in Serializers.py and views.py for Logout function but I don't know what to do and where to start. Can you please help? Here's some code for register and login Serialzers.py from rest_framework import serializers from .models import * class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] def create(self, validated_data): user = User.objects.create( email=validated_data['email'], username=validated_data['username'],) user.set_password(validated_data['password']) user.save() return user class UserLoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=64) password = serializers.CharField(max_length=128, write_only=True) def validate(self, data): email = data.get("email", None) password = data.get("password", None) if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) if not user.check_password(password): raise serializers.ValidationError() else: return user else: raise serializers.ValidationError() class UserLogoutSerializer(serializers.Serializer): # I have to do this part views.py from django.shortcuts import get_object_or_404, render from .serializers import * from .models import * from rest_framework import views from rest_framework.response import Response class SignUpView(views.APIView): def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'message': 'Success', 'data': serializer.data}) return Response({'message': 'Fail', 'error': serializer.errors}) class LoginView(views.APIView): def post(self, request): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): return Response({'message': "Success", 'data': serializer.data}) return Response({'message': "Fail", 'data': serializer.errors}) class LogoutView(views.APIView): -
Redux store not being updated after dispatching action
Hi all I am new to react and have been working on a project the last week I have been trying to build this login for django rest framework using react and redux toolkit. As I understand it, redux action creators create actions which then get dispatched to reducers for changing global state. If this is the case, why is my action creator for login not saving the access and refresh tokens to the store!!!???!!?!?!?!??! Below is my code. --Login.js ---Where most of the login logic is happeneing and the action creator for login is being used. import { useState } from "react" import {useDispatch, useSelector} from "react-redux" import {login} from '../features/auth/authSlice' import axios from "axios" const Login = () => { const userToken = useSelector((state)=>state.auth) const [username, setUsername] = useState('') const [password, setPassword] = useState('') const dispatch = useDispatch() const authenticate = async ()=>{ // const resp = await axios.post('http://localhost:8000/auth/login', {formData}) const resp = await fetch('http://localhost:8000/auth/login', { method: 'POST', headers:{ 'Content-Type': 'application/json' }, body:JSON.stringify({username:username, password:password}) }) const data = await resp.json() console.log(data); dispatch(login({ accessToken: data.access, refreshToken: data.refresh })) return data } const handleSubmit = (e) =>{ e.preventDefault() console.log(username, password); // authenticate().then((data)=>{ }) authenticate() setTimeout(()=>{ console.log(userToken); }, 3000) console.log(userToken); } … -
ModelChoiceField fields are not saved, what should I do?
The site has the ability to create a post for a specific game. When you try to create a post, it is created but the ManyToManyField remain empty. How to fix it? **forms.py** class AddPost(forms.ModelForm): title = forms.CharField(label='Title', widget=forms.TextInput(attrs={'placeholder': 'Заголовок...'}), help_text='Максимум 100 символів.') games = forms.ModelChoiceField(queryset=Game.objects.filter(draft=False), widget=forms.Select, required=True) tags = forms.ModelMultipleChoiceField(queryset=Tags.objects.all(), widget=forms.SelectMultiple( attrs={'style': "padding: 10px; background:#edf2ff; border:none;"})) foreword_description = forms.CharField(label='Small Description', widget=forms.Textarea(attrs={'placeholder': 'Коротке описання...'}), help_text='Максимум 335 символів.') description = forms.CharField(label='Description', widget=CKEditorUploadingWidget()) rank = forms.FloatField(label='Rank', widget=forms.TextInput(attrs={'placeholder': 'Оцінка...'})) good = forms.ModelChoiceField(queryset=Good.objects.all(), widget=forms.Select( attrs={'style': "padding: 10px; background:#edf2ff; border:none;"})) bad = forms.ModelChoiceField(queryset=Bad.objects.all(), widget=forms.Select( attrs={'style': "padding: 10px; background:#edf2ff; border:none;"})) url = forms.SlugField(label='Title', widget=forms.TextInput(attrs={'placeholder': 'Унікальний ідентифікатор...'}), help_text='Максимум 255 символів.') premiere = forms.DateField(label='Date', widget=forms.SelectDateWidget(attrs=({'style': 'width: 10%; display: inline-block;'})), help_text='У форматі: 24.03.2022.') class Meta: model = Post fields = ( 'title', 'games', 'tags', "foreword_description", "description", "rank", "good", "bad", "url", "premiere",) **views.py** def addpost(request): if request.method == "POST": form = AddPost(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('../blogs/') else: form = AddPost() data = { 'form': form, 'add': True } return render(request, 'gamelibs/user-post-manager.html', {'form': form}) **models.py** class Game(models.Model): title = models.CharField("Назва", max_length=100) tagline = models.CharField("Слоган", max_length=500, default='') description = models.TextField("Описання") description_small = models.CharField("Описання коротко", max_length=100, null=True) poster = models.ImageField("Постер", upload_to="games/poster/") banner = models.ImageField("Банер", upload_to="games/banner/", null=True) treiler = models.CharField("Трейлер", … -
ImportError: cannot import name 'last_traceback' from 'sys' (unknown location)(django)
I'm new to Django and Ubuntu. (i didnt have these problems on windows) I follow these steps to make Project in Django: 1.pip3 install pipenv 2.mkdir projectname 3.pipenv install Django or pip install Django(i use both Command) 4.code . 5.pipenv shell 6.django-admin startproject projectname(if i enter [django admin startproject projectname ] i get the error that --> django: command not found) 7.pipenv --venv (i use this command to use python interpreter inside the virtual enviroment 8.python manage.py startapp appname(after enter this Command i get the error) Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/home/pariya/.local/share/virtualenvs/store-JV9N7EFe/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models self.models_module = import_module(models_module_name) 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 … -
invalid json type when GET request send python requests?
My code: def get_authenticate(): header = { "login": username, "password": password, "db": db, "content-type": "application/json" } h_data = json.dumps(header, indent=4) get_tokens = requests.get(url="https://someurl.com/api/auth/token/", headers=json.loads(h_data)) return get_tokens get_ = get_authenticate() print(get_) for i in get_: print(i) Output: <Response [400]> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 400 Bad Request Bad Request Invalid JSON data -
How can I group products based on their age in django?
I have a django ecommerce site where I have products for 3 age groups. i.e. Child, Adult, Senior. The issue is one product can be on more than one age group. How can I arrange that with the product model? I tried using booleans and use select option but when I change pages it gives "keywords must be strings" error because of the filter. Here is my code: Templates <li class="age"><Form action="{% url 'get_products' %}" method="get"> <select style="text-transform: uppercase;" name="age_group" onchange="submit()"> <option value="" selected disabled>Gifts by Age</option> <option value="infant">Infant</option> <option value="toddler">Toddler</option> <option value="child">Child</option> <option value="teen">Teenager</option> <option value="adult">Adult</option> </select> </Form></li> Views def get_products(request): # getting the age group you passed via form age_group = request.GET.get("age_group") products = Product.objects.filter(**{age_group: True}) paginator = Paginator(products, 1) page_number = request.GET.get('page') products = paginator.get_page(page_number) context = {'products': products } return render(request, "age.html", context) -
Django admin conditional inline
I have a question model which can have different types like SINGLE_ANSWER, MULTIPLE_ANSWER , CODE , ... MODELS.PY : class Question(BaseModel): class QuestionType(models.IntegerChoices): SINGLE_ANSWER = 1 MULTIPLE_ANSWER = 2 ESSAY = 3 CODE = 4 VIDEO = 5 UPLOAD = 6 class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 question_text = models.TextField() type = models.IntegerField(choices=QuestionType.choices) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) def get_absolute_url(self): self.get_type_display() def __str__(self): return truncatewords(self.question_text, 7) ADMIN : @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): inlines = [ OptionInline, CodeInline, TestCaseInline, ] By this code all inlines(OptionInline,CodeInline,TestCaseInline) will be shown in admin page like the picture bellow: question admin panel pic but i want the inlines appear whenever the user choose the type, for example the OptionInline shows when user choose multiple_answer or CodeInline shows when user choose CODE from type dropdownlist what i did for this purpose is overriding the get_inlines method ADMIN : def get_inlines(self, request, obj: Question): if obj: if obj.type in [Question.QuestionType.SINGLE_ANSWER, Question.QuestionType.MULTIPLE_ANSWER]: return [OptionInline] elif obj.type == Question.QuestionType.CODE: return [CodeInline, TestCaseInline] else: return [] else: return [] but i have a problem when i want to change the type after saving the question this error appears : (Hidden field INITIAL_FORMS) This field is required. ManagementForm … -
How can I make a Django application connect to a minio server when both are behind an nginx proxy and inside individual docker containers?
Goal Access minio server via subdomain from Django server in docker environment (both minio server and Django server are behind nginx proxy) Expected result: Django can access minio server using the subdomain specified in nginx. Problem Django service can't connect properly. Docker logs: api | Traceback (most recent call last): api | File "manage.py", line 22, in <module> api | main() api | File "manage.py", line 18, in main api | execute_from_command_line(sys.argv) api | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line api | utility.execute() api | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 386, in execute api | settings.INSTALLED_APPS api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ api | self._setup(name) api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup api | self._wrapped = Settings(settings_module) api | File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ api | mod = importlib.import_module(self.SETTINGS_MODULE) api | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module api | return _bootstrap._gcd_import(name[level:], package, level) api | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import api | File "<frozen importlib._bootstrap>", line 991, in _find_and_load api | File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked api | File "<frozen importlib._bootstrap>", line 671, in _load_unlocked api | File "<frozen importlib._bootstrap_external>", line 843, in exec_module api | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed api … -
Django cannot find path although it is not hardcoded
The background of this problem is that I am deploying a Django project on production server. Upon testing on production server I get the below error from my asgi.log 2022-07-24 07:03:12,962 ERROR Internal Server Error: /paymentWebhook Traceback (most recent call last): File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 482, in thread_handler raise exc_info[1] File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.10/asyncio/tasks.py", line 408, in wait_for return await fut File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/current_thread_executor.py", line 22, in run result = self.fn(*self.args, **self.kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/asgiref/sync.py", line 486, in thread_handler return func(*args, **kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/home/jianwu/DimsumBox_website/dimsumbox/./customer/views.py", line 124, in payment_webhook paymentHandle = handlePostPayment(request = request) File "/home/jianwu/DimsumBox_website/dimsumbox/./customer/views.py", line 165, in handlePostPayment pdfReceipt = webshopUtils.generateReceipt(session_id = customer.session_id) File "/home/jianwu/DimsumBox_website/dimsumbox/./dimsumbox/Modules/webshopUtils.py", line 484, in generateReceipt return pdf.pdf.output() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 2929, in output self.close() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 672, in close self._enddoc() # close document File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3672, in _enddoc self._putresources() # trace_size is performed inside File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3565, in _putresources self._putfonts() File "/home/jianwu/DimsumBox_website/env/lib/python3.10/site-packages/fpdf/fpdf.py", line 3205, in …