Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django show TypeError'>' not supported between instances of 'NoneType' and 'float'
I try to compare value from get with value in database. First, I get input from url as f1, f2. Then, if alert_field = 1 set f1 as f , if alert_field = 2 set f2 as f . Then, if alert_symbol = 1 compare f with alert_value using = ,if alert_symbol = 2 compare f with alert_value using >. def test(request): key = request.GET.get('key') f1 = request.GET.get('f1') f2 = request.GET.get('f2') f1 = float(f1) if f1 is not None and is_float(f1) else None f2 = float(f2) if f2 is not None and is_float(f2) else None if Key.objects.filter(api_key=key).exists(): # Alert dv = Device.objects.filter(api_key=dv_key) for dv in dv: # get all condition # Check if alert_field=1 then use f1 value to compare, if alert_field=2 then use f2 value to compare if(dv.alert_field==1): f = f1 fname = rcv_set.field1_name elif(dv.alert_field==2): f = f2 fname = rcv_set.field2_name if(dv.alert_symbol==1): # Check if alert_symbol=1 then compare with = if(f==dv.alert_value): msg = "=" lineAlert(dv_key.line_api, msg) elif(dv.alert_symbol==2): # Check if alert_symbol=2 then compare with > if(f>dv.alert_value): msg = ">" lineAlert(dv_key.line_api, msg) In database I set alert_symbol=2. I send data to get is 50 it show error like this. '>' not supported between instances of 'NoneType' and 'float' Error at … -
Django migrations - opertions to perfrom
i am building a django project and i migrate i get this message: Operations to perform: Apply all migrations: app1, app2, admin, app3, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. when i see thae tables in the admin page i can see the changes i am doing but i dont understand how the changes are made but im getting the messgae Operations to perform if someone can please explain to me that would be halpful thanks -
Django migrations - opertions to perfrom
i am building a django project and i migrate i get this message: Operations to perform: Apply all migrations: app1, app2, admin, app3, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. when i see thae tables in the admin page i can see the changes i am doing but i dont understand how the changes are made but im getting the messgae Operations to perform if someone can please explain to me that would be halpful thanks -
TemplateDoesNotExist at /app/search_flights/ in Django
I'm making a web app that lets a user login, logout, search a flight, book a flight and view the bookings made. For some reason the 'search_flights/html' is not being rendered or Django's not being able to find it. I spent a lot of time trying to debug it but with no luck. Project directory (I've included search_flights.html both in the root templates folder as well as the app templates folder as of now to see if changing anything will work, but it didn't) flight └─ flight_booking ├─ app │ ├─ admin.py │ ├─ apps.py │ ├─ migrations │ │ ├─ 0001_initial.py │ │ ├─ __init__.py │ │ └─ __pycache__ │ │ ├─ 0001_initial.cpython-39.pyc │ │ └─ __init__.cpython-39.pyc │ ├─ models.py │ ├─ templates │ │ ├─ app │ │ │ ├─ book_flight.html │ │ │ └─ search_fights.html │ │ └─ base.html │ ├─ tests.py │ ├─ urls.py │ ├─ views.py │ ├─ __init__.py │ └─ __pycache__ │ ├─ admin.cpython-39.pyc │ ├─ apps.cpython-39.pyc │ ├─ forms.cpython-39.pyc │ ├─ models.cpython-39.pyc │ ├─ urls.cpython-39.pyc │ ├─ views.cpython-39.pyc │ └─ __init__.cpython-39.pyc ├─ db.sqlite3 ├─ flight_booking │ ├─ asgi.py │ ├─ settings.py │ ├─ urls.py │ ├─ views.py │ ├─ wsgi.py │ ├─ __init__.py … -
Uploading file in django but in data base it just save its nome and didnot found any file in media folder
I am new in Django I am working on a project where user will able to add file name and its file file can be **doc, img, pdf, csv ** i want that to be saved but when i upload them they didn't get saved here is my code **model.py** class Resources(models.Model): resource_name = models.CharField(max_length=255) rec_file = models.FileField(upload_to = "resources/", max_length=10000, null=True, default=None) created_at = models.DateField(auto_now=True) **view.py** def add_resources(request): title="Add Resources" requesturl = request.get_full_path title = 'Create Clinic' if request.method == "POST": resource_name = request.POST.get('resource_name') resource_file = request.POST.get('resource_file') resource_instances = Resources.objects.create( resource_name = resource_name, rec_file = resource_file ) resource_instances.save() return render(request, 'add_resources.html',{'title':title, 'requesturl':requesturl}) **setting.py** MEDIA_ROOT = BASE_DIR/"media" MEDIA_URL = "/media/" **url.py** from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns+=static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) when i upload the file it just save the file name and nothing is saved in the media folder please help thank you -
How to count row from backref in template?
I have a question. I need to count MemePositiveRating for Meme in template. I try meme.memeratingpositive|length but not working. There is any idea to do it with Abstract layer in models ? home.html <a class="mr-2" href="#">{{ meme.memeratingpositive|length }}</a> models.py class Meme(models.Model): title = models.CharField(max_length=100) meme = models.ImageField(upload_to='memes') creation_date = models.DateField(default=timezone.now) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return f'Meme id: {self.id}' class MemeRating(models.Model): meme = models.ForeignKey(Meme, on_delete=models.CASCADE, related_name = 'ratings', blank = True, null = True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) class Meta: abstract: True class MemeRatingPositive(MemeRating): pass class MemeRatingNegative(MemeRating): pass views.py class HomeView(ListView): template_name = 'meme/home.html' model = Meme context_object_name = 'memes' def get_queryset(self): return Meme.objects.filter(memestatus__is_in_moderating_room=False, memestatus__is_in_waiting_room=False) -
SELECT app_product.id FROM app_product left JOIN app_order ON app_product.id = app_order.product_id GROUP BY app_product.id
this is sql quary how to convert in django orm please given this problem solution -
how to merge excel file with python django
i use google translation I am making a website using Django. I am trying to upload 4 excel files so that one excel file can be downloaded. After defining the views.py function for each file, modifying the Excel file and then defining a function that merges the files into one, implements the download function. Excel editing for each file is possible, but the merge function is not implemented, so I ask a question. Current code is below(ignore the korean) views.py import pandas as pd from django.shortcuts import render, HttpResponse, redirect from io import BytesIO def index(request): return render(request, "index.html") def health_upload(request): if request.method == "POST": file = request.FILES.get("health_input") 건강2 = pd.read_excel(file) 건강2.rename(columns= {"성명" : "근로자명"} , inplace=True) 건강2.rename(columns= {"주민등록번호" : "생년월일"} , inplace=True) 건강2["생년월일"] = 건강2["생년월일"].str[: -8] 건강2 = 건강2.set_index(["근로자명", "생년월일"]) 건강기본 = 건강2.iloc[: , -1 : ].copy() 건강기본["개인부담금"] = 건강기본.가입자총납부할보험료 건강기본["사업주부담금"] = 건강기본.가입자총납부할보험료 건강기본.drop(columns = ["가입자총납부할보험료"], inplace=True) return render(request, "index.html") def national_upload(request): if request.method == "POST": file2 = request.FILES.get("national_input") aaa = pd.read_excel(file2) aaa.rename(mapper = {"가입자명" : "근로자명"}, axis="columns", inplace=True) aaa.rename(mapper = {"주민번호" : "생년월일"}, axis="columns", inplace=True) aaa["생년월일"] = aaa["생년월일"].str[: -8] 국민기본 = aaa.set_index(["근로자명", "생년월일"]) 국민기본 = 국민기본.iloc[: , -1 : ].copy() 국민기본["개인부담금"] = 국민기본.결정보험료/2 국민기본["사업주부담금"] = 국민기본.결정보험료/2 국민기본.drop(columns = … -
django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') in Django
It is my first time encountered this error, I've implemented it multiple times on my different projects and migrated to database it works fine , but just this one returns me an error, when I tried to migrate my models.py it says: django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') Now I have UserDetails class which linked to the AuthUser of Django migration I tried it multiple times in previous projects but this one has an error, I don't know the real issue here. class AuthUser(models.Model): //comes from the command : python manage.py inspectdb > models.py password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class UserDetails(models.Model): user_id = models.OneToOneField(AuthUser, on_delete=models.CASCADE) middle_name = models.CharField(max_length=128, blank=True, null=True) birthdate = models.DateField(blank=True, null=True) sex = models.CharField(max_length=128, blank=True, null=True) address = models.CharField(max_length=128, blank=True, null=True) position = models.CharField(max_length=128, blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'user_details' -
Reactjs - Axios instance - withCredentials not working
I made a view in ReactJS to edit the user profile, and started to use axios like this: //profile.js axios.post("/api/user/update/",{ withCredentials: true, username: newUsername, email: newEmail, lang: "", }).then... This is working perfectly well as the credentials are sent with the request, however when making an axios instance like that: //axiosInstance.js const API = axios.create({ withCredentials: true, baseURL: django_base_url + "/api/", }) export default API; //profile.js API.post("user/update/", { username: newUsername, email: newEmail, lang: "", }).then... The credentials are not sent with the request and I get a 403 from my django backend that says that it's missing the CSRF_TOKEN. React and Django are not running on the same url (:8000 django :3000 React), I already set the proxy to :8000 in my package.json. I also tried to force the credentials this way API.defaults.withCredentials = true; but without any success either. I am confused on why the instance doesn't work when it does without it? I'm just trying to force the credentials on every axios request. -
Quiz django. Can't get answers to the questions
I'm new to django and I don't understand why the answers to the questions are not displayed on the screen (although the questions themselves are displayed). Everything is also empty in the source code of the page. Help please model.py from django.utils.translation import gettext as _ class people(models.Model): CHOICES_TEST_ID = (('0', 'КСС'), ('1', 'Золотые правила'), ('2', 'MWD'), ('3', 'DD')) firstname = models.CharField(max_length=50, null=False) lastname = models.CharField(max_length=50, null=False) surname = models.CharField(max_length=50, null=False) test_id = models.CharField(max_length=10, choices=CHOICES_TEST_ID, default=0, blank=False) date_of_passage = models.DateField(_('Date'), auto_now_add=True) correct_answer = models.IntegerField(default=0) done = models.BooleanField('Тест сдан', default=False) def number_correct_answer(self): self.correct_answer += 1 class questions(models.Model): question = models.CharField('Вопрос', max_length=500, null=False) test_id = models.CharField('Идентификационный номер теста', max_length=2, null=False) def __str__(self): return self.question class Meta: verbose_name_plural = 'Вопросы' class answers(models.Model): answer = models.CharField('Ответ', max_length=200, null=False) true_answer = models.BooleanField('Правильный ответ', default=False) question = models.ForeignKey(questions, on_delete=models.CASCADE) def __str__(self): return self.answer class Meta: verbose_name_plural = 'Ответы' forms.py from .models import people, answers from django.forms import ModelForm, TextInput, RadioSelect class PeopleForm(ModelForm): class Meta: model = people fields = ['firstname', 'lastname', 'surname', 'test_id'] widgets = {'firstname': TextInput(attrs={'class': 'firstname', 'placeholder': 'Ввод'}), 'lastname': TextInput(attrs={'class': 'lastname', 'placeholder': 'Ввод'}), 'surname': TextInput(attrs={'class': 'surname', 'placeholder': 'Ввод'}), 'test_id': RadioSelect()} class AnswersForm(ModelForm): class Meta: model = answers fields = ['answer', 'true_answer', 'question'] widgets = … -
How can I add CKeditot in django ? Can anyone explain step by step?
When I tried to run python manage.py collectstatic it was now working.enter image description here I just expecting that how to add Richtexteditor in in static files -
Admin login page using Django
I'm stuck writing a login function (in the views.py file) that redirects the user to his homepage. I have created one single interface for all the users (doctor, receptionist, patient and the admin). It works for all the users except for the admin, as I'm a beginner in Django I don't know how to resolve this and I don't want to create a separate login page for the admin as well as a separate login function for him, I want to combine it all in one single function, is it possible ? Thank you for your help. This is the login function that worked for patients, doctors and receptionists: def loginpage(request): error = "" page = "" if request.method == 'POST': u = request.POST['email'] p = request.POST['password'] user = authenticate(username=u,password=p) try: if user is not None: login(request,user) error = "no" g = request.user.groups.all()[0].name if g == 'Doctor': page = "Doctor" d = {'error': error,'page':page} return render(request,'homepageDoctor.html',d) elif g == 'Receptionist': page = "Receptionist" d = {'error': error,'page':page} return render(request,'homepageReceptionist.html',d) elif g == 'Patient': page = "Patient" d = {'error': error,'page':page} return render(request,'homepagePatient.html',d) else: error = "yes" except Exception as e: error = "yes" return render(request,'login.html') This is the login function … -
What are u use in project with django.contrib.auth.models user
I wanna ask what u do when wanna create more than just name passwod and password_confirm . Like "from django.contrib.auth.models import Abstractuser class name model(Abstractuser):" and add fields what u need or use "user = models.OneToOneField(User, on_delete=models. CASCADE) " in other model,and if u can pls explain which method and why.Cause i cant find this on documentation(if u can just send me link with this topic) i dont know which method better and dont understand difference -
Django: How to also migrate the name of a Primary Key `id_seq` in PSQL database
I am using Postgres 12 with Django 4.0.x and I have a Django App named Polls with a model named Foo in polls/models.py: class Foo(models.Model): ... From the command line, I can inspect my PSQL database: python manage.py dbshell => \d List of relations Schema | Name | Type | Owner --------+-----------------------------------+----------+------- public | auth_group | table | username ... public | polls_foo | table | username public | polls_foo_id_seq | sequence | username (21 rows) Notice the polls_foo_id_seq sequence for my polls_foo table. Now I want to refactor and rename the Foo class to Bar. But I also want to change all database table and sequence names to remove the old name foo and change it to bar. So first I change my Python code in polls/models.py to: class Bar(models.Model): ... From the command line, I run: $ python manage.py makemigrations; Was the model polls.Foo renamed to Bar? [y/N] y Migrations for 'polls': polls/migrations/0002_rename_foo_bar.py - Rename model Foo to Bar $ python manage.py migrate; Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0002_rename_foo_bar... OK The migration runs smoothly. Now I want to inspect the change in PSQL, so I run: $ python manage.py … -
Is learning Django Worth it? [closed]
What is the current and projected demand for **Django ****developers **in the job market in 2023 and the next 2-3 years? Also, what is the usage and demand for Django in the industry, and is it still worth learning **Django **as a web development framework? descriptive answers -
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())