Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django code work on local machine but dose not work on heroku
my Django code works on my computer but when I pushed it onto Heroku, it shows and error, but whene I run the program on my machine, it works fine. can anyone help me please. The error : 2022-02-11T17:26:36.187430+00:00 app[web.1]: <QueryDict: {'csrfmiddlewaretoken': ['bB8ABomINOKodDyyfQbC8ykkl9Rmormxv9D3X7kVJpyeHeJDKaFeqSPFhZJiThzC'], 'colors': [''], 'size': ['270'], 'colors_ca': [''], 'blurriness': ['4'], 'edges': ['with edges'], 'points': ['5000'], 'back_color': ['#191919'], 'letters': ['$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,"^`\'. '], 'blur': ['71'], 'style': ['cartooning']}> 2022-02-11T17:26:36.191835+00:00 app[web.1]: user>>> admin 2022-02-11T17:26:36.194190+00:00 app[web.1]: media\img\20\866E71D6-7AA1-4429-AB3F-99823DDF29B0.jpeg 2022-02-11T17:26:36.194192+00:00 app[web.1]: path is up 2022-02-11T17:26:36.226445+00:00 app[web.1]: Internal Server Error: /home_f/cartoonify_f/ 2022-02-11T17:26:36.226446+00:00 app[web.1]: Traceback (most recent call last): 2022-02-11T17:26:36.226447+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner 2022-02-11T17:26:36.226447+00:00 app[web.1]: response = get_response(request) 2022-02-11T17:26:36.226455+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response 2022-02-11T17:26:36.226456+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2022-02-11T17:26:36.226456+00:00 app[web.1]: File "/app/app/views/views.py", line 273, in cartoonify 2022-02-11T17:26:36.226457+00:00 app[web.1]: cartoon, total_color = cartooning(path, request) 2022-02-11T17:26:36.226457+00:00 app[web.1]: File "/app/app/views/views_filters_func.py", line 606, in cartooning 2022-02-11T17:26:36.226457+00:00 app[web.1]: print('befor resizing -- origainal 50px small image: ', img.shape) 2022-02-11T17:26:36.226458+00:00 app[web.1]: AttributeError: 'NoneType' object has no attribute 'shape' 2022-02-11T17:26:36.227187+00:00 app[web.1]: 10.1.13.21 - - [11/Feb/2022:17:26:36 +0000] "POST /home_f/cartoonify_f/ HTTP/1.1" 500 64458 "https://pixelifier.herokuapp.com/home_f/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" 2022-02-11T17:26:36.227822+00:00 heroku[router]: at=info method=POST path="/home_f/cartoonify_f/" host=pixelifier.herokuapp.com request_id=9121505b-0838-4c88-bc0f-67cbf633667d fwd="37.239.124.11" dyno=web.1 connect=0ms service=10399ms status=500 bytes=64759 … -
How can I migrate a Wordpress website to Django
I currently have a fully functional Wordpress website that is mostly static. It is a marketing website that mainly displays static webpages. My client would however want to add new features such as accounts functionality and others using the Django web framework. I am well versed in Django, but I would like to know what the best approach is to migrate the Wordpress site into a Django project. Or if there is a better way. Thank you. -
DRF: Updating a model in another models serializer or view
so I have a User and schools model which are related as an Owens(ManyToMany), student, and staff, if an owner registers and creates a school, I would like to perform a partial update to the Owens field of the request.user from having a null/blank or previously created schools to adding the newly created school serializers.py class SchoolSerializerBase(serializers.ModelSerializer): ... class Meta: model = School fields = ... def validate(self, attrs): ... return attrs def create(self, validated_data): instance = School.objects.create( ... ) instance.save() return instance and i have a simple view for it class CreateSchoolView(generics.CreateAPIView): queryset = School.objects.all() permission_classes = [IsSchoolOwner, ] serializer_class = SchoolSerializerBase My question: how do I update the request.user.ownes field and add the school instance to it?? -
django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key
Created first project model and populated it with some data, then tried to add profile model to it (no data there) through foreign key and while trying to do a migration for linking profile model with projects model getting an error: django.db.utils.IntegrityError: The row in table 'main_page_projects' with primary key '1' has an invalid foreign key: main_page_projects.profile_id contains a value '1' that does not have a corresponding value in main_page_profile.id. Value nr 1 was picked during the makemigration: It is impossible to add a non-nullable field 'profile' to projects without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. I googled around and looked also stackoverflow, probably if I delete migration files and sqlite3 database then migrations should work, but I would like to know how to make it to work without deleting migration files and database. If populate profile then migration also works, but why it won't create a link with default values? What should I do differently or where … -
Django Image not showing up in django when using template tags
When i try calling an image like this {{ profile.image.url }} it works in the profile page, but in the home page when i do {{ post.user.profile.image.url }} nothing shows up and that is not what i expect. i have also tried checking if the image url work and yes it's working. NOTE: It working fine as expected in the profile page but in index.html it seems like nothing is showing up. index.html {% for post in post_items %} <a href="{{post.user.profile.image.url}}" class="post__avatar"> <img src="{{post.user.profile.image.url}}" alt="User Picture"> </a> <a href=""{{ post.user.username }}</a> models.py class Profile(models.Model): user = models.ForeignKey(User, related_name='profile', on_delete=models.CASCADE) image = models.ImageField(upload_to="profile_pciture", null=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return f'{self.user.username} - Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) -
Django (dj-rest-auth) Custom user registration with a ForeignKey
I have created a custome user in my App, and points to a timezone record, in the TimeRegion Model. model.py class TimeRegion(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,) tz_key=models.CharField(max_length=200,) class CustomUser(AbstractUser): id=models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,) user_timezone=models.ForeignKey(TimeRegion,verbose_name="Time Zone",on_delete=models.DO_NOTHING, blank=True, null=True) Extended the API call to include the custom field. serializers.py class CustomRegisterSerializer(RegisterSerializer): first_name = serializers.CharField() last_name = serializers.CharField() statement_agreement = serializers.BooleanField() user_timezone = serializers.UUIDField() #Tried CharField() and PrimaryKeyField() def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'password2': self.validated_data.get('password2', ''), 'email': self.validated_data.get('email', ''), 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'user_timezone': self.validated_data.get('user_timezone', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.user_timezone = self.cleaned_data.get('user_timezone') user.save() return user setting.py REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'api.serializers.CustomRegisterSerializer' } However whenever I run an API test to check that I am able to register a new user, get the following error message: test code # Get the timezone record url_timezone = 'http://127.0.0.1:8000/api/v1/timezonelist/' response_timezone = self.client.get(url_timezone, content_type='application/json') #Register the user to the first timezone: url_signup = 'http://127.0.0.1:8000/api/v1/dj-rest-auth/registration/' params_signup={ 'first_name': 'John', 'last_name': 'Tester', 'email':'testuser@email.com', 'password1':'pwdktudchJsuec123', 'password2':'pwdktudchJsuec123', 'user_timezone': response_timezone.data[0]['id'], } response_signup = self.client.post(url_signup, data=json.dumps(params_signup), content_type='application/json') responce: Traceback (most recent call last): File "/code/api/tests.py", line 45, in test_from_start response_signup = self.client.post(url_signup, data=json.dumps(params_signup), content_type='application/json') File "/usr/local/lib/python3.9/site-packages/rest_framework/test.py", … -
How To Decrypt Content In The Backend Then Pass It To The Frontend With Other Attributes
I'm building a Django social media, that focuses on privacy and anonymity, and I'm trying to build E2EE functionality, but I can't add any JavaScript in the project, so the decryption of the messages, notes is done locally and is stored in a temporary method like a dictionary or a list, then passed to the frontend, my problem is how to pass other attributes to the frontend? like messages are made like this: class Message(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False) msg = models.BinaryField(null=False, blank=False) date = models.DateTimeField(default=timezone.now) to = models.ForeignKey(User, related_name='received', on_delete=models.CASCADE, blank=False, null=False) res = models.CharField(max_length=5, blank=False, null=False) author = models.ForeignKey(User, blank=False, null=False, related_name='sent', on_delete=models.CASCADE) so the msg that is the content of every message is the encrypted field, and when the messages view is loaded the messages are decrypted with the users private key class messages(LoginRequiredMixin, View): def get(self, request, touser, *args, **kwargs): if User.objects.filter(username=touser).exists(): user = User.objects.get(username=touser) msgs = Message.objects.filter(Q(to=request.user)|Q(author=request.user)) try: key = request.COOKIES['key'] except: return redirect('set-key') private_key = serialization.load_pem_private_key(request.user.profile.privatekey, password=key.encode('utf-8'),) messagescontent = [] for mess in msgs: plaintext = private_key.decrypt(mess.msg, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) messagescontent.append(plaintext.decode()) context = {'msgs': messagescontent,} else: messages.warning(request, 'User Doesn\'t Exist') return redirect('messages-list') return render(request, 'posts/messages.html', context) so … -
Django ModuleNotFoundError: No module named 'core'
I was working on a blog. The static files are in a bucket on aws and the website is being hosted on heroku. Each time i try to edit a blog post ie(http://127.0.0.1:8000/admin/blog/post/1/change/) I keep getting this error: File "C:\Users\Hp\AppData\Local\Programs\Python\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 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 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 'core' Here is my settings.py: """ Django settings for proton project. Generated by 'django-admin startproject' using Django 4.0.2. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret key' # SECURITY WARNING: don't run with debug turned on in production! … -
django error using if statement with or condtion
I am if using if statement with or condition if batch == (None or 0): raise error and also if batch is not None and farm ==(None or 0): raise error -
django.core.exceptions.ImproperlyConfigured: Set the EMAIL_HOST environment variable
I'm tyring to deploy my app to heroku. after successfully running git push heroku main i'm tyring to run the command heroku run python manage.py makemigrations and i'm getting this error File "/app/.heroku/python/lib/python3.10/site-packages/environ/environ.py", line 367, in get_value value = self.ENVIRON[var] File "/app/.heroku/python/lib/python3.10/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'EMAIL_HOST' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 35, in check_url_namespaces_unique if not getattr(settings, 'ROOT_URLCONF', None): File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, … -
Django Plotly Dash Scatter chart loses interactivity when DataTable added
I am using the django-plotly-dash utility to embed Dash apps into a Django page. If I have a Plotly Scatter chart on the same app as a Dash DataTable then the chart loses it's interactivity. -
Django loading data from fixture fails after schema migration
I have recently came across a problem while trying to reload fixtures to my database after a schema migration. I applied a schema migration which added a new field to my model. The database schema is indeed updated with the new field. However I can't reload fixtures: python manage.py loaddata data.json gives the following error "django.db.utils.OperationalError: Problem installing fixture '/../data.json': Could not load app.CheckupType(pk=1): no such column: name_de" The file data.json contains the same existing data in the database with the new field name_de. When I check the SQL database (or with python manage.py inspectdb), the field name_de exists. But when I run python manage.py dumpdata, there is no such field name_de. I tried to manually add the missing field in python manage.py shell, but I get the following error : "OperationalError: no such column: app_checkuptype.name_de" How can I synchronize my database model to my django model to have my fixtures updated with my new field? I tested the same procedure on another machine and it runs without any issues... -
mssql isn't an available database backend or couldn't be imported
I'm following this guide. Mssql-django and I have Django version 3.2.12 I already installed mssql-django 1.1.1 modified my settings.py to have 'ENGINE': 'mssql', But im still receving this error django.core.exceptions.ImproperlyConfigured: 'mssql' 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 convert external API data into a queryset without actually interacting with local database
In my Django project im fetching data from an external API. It is possible to convert the API data into a django model or class. The resulting data shell be used in a view form which is using django-filter to filter the information by user input. The django-filter instance expects a queryset as input. How do i turn the external API data into a queryset without interacting with the local database in any form? -
Django ORM join a Raw Query
I want to join a fairly complex subquery to a Django ORM queryset: The resulting query should be like: select id from webshop_product left outer join ( select product_id, count(extra_col) as quantity from ( select product_id, col1 as extra_col from xyz where x = 123 and y = 456 union select product_id, col2 as extra_col from abc where a = 234 and y = 534 ) as t1 ) as t2 on t2.product_id = webshop_product.id The subquery in the left outer join clause is quite complex, it involves aggregating from a union from different tables, and I can not write it in the ORM. I tried writing it in the ORM, but I could not achieve the UNION on different tables.... so I want to join it as raw subquery, and annotate the quantity column. Something like: Product.objects.all().join("my complex raw subquery") Is this possible in the Django ORM? -
How can create mega drop down in django?
Anyone can tell me how to create mega menu drop down in django I create but i want if 5 random category and 3 subcategory of every category i am able to display category but not able to display subcategory so how I can display sub category by category -
GraphQL request made from React page to Django App blocked in the response
I am currently working on a personnal project which currently creates a GraphQL request in a react application and sends it to a Python django app in order to get the Response. The problem is when I ask for a GraphQL request from a react page, I get this anwser in the console.log : Access to fetch at 'http://localhost:8000/graphql/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Here are my settings.py files which contains the apps : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', 'myapp', 'corsheaders' ] CORS_ORIGIN_WHITELIST = [ "http://localhost:3000",#React page "http://127.0.0.1:3000" #React page with an IP address ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), } } … -
Django how to include all columns from one table, but a only subset of columns in a different table, using tbl.only?
I want to join a child table to the parent table, and return all columns from the child table (child.*), but only specific columns from a parent table (parent.foo, parent.bar), using only but not defer. Is there any syntax to issue a SQL similar to the following: select child.*, parent.foo, parent.bar from child join parent on child.parent_id = parent.id I do not want to use defer, because the parent table has even more columns than the child table. I currently have to spell out every column that I want using only: Child.objects.select_related('parent').only( 'id', 'name', 'creation_date', 'parent__foo', 'parent__bar' ).all() But I would like to include all the columns from Child. -
How to make view that uses a web scraper load faster
I have a view that outputs destination city results on a page. As part of the view, a web scraper searches for flight prices from the user's area to the destination city. After adding the web scraper to the view it now takes about 8 seconds to load. I was wondering how I can make the view load quicker, maybe with threading or another alternative. views.py def results(request, result1, result2, result3, result4, result5, result6, broad_variable1, broad_variable2, broad_variable3, specific_variable_dictionary, user_city): result1 = City.objects.filter(city=result1).first() result2 = City.objects.filter(city=result2).first() result3 = City.objects.filter(city=result3).first() result4 = City.objects.filter(city=result4).first() result5 = City.objects.filter(city=result5).first() result6 = City.objects.filter(city=result6).first() # get the first user selected specific variable value for each result result1_value1 = City.objects.filter(city=result1.city).values(broad_variable1)[0][broad_variable1] result2_value1 = City.objects.filter(city=result2.city).values(broad_variable1)[0][broad_variable1] result3_value1 = City.objects.filter(city=result3.city).values(broad_variable1)[0][broad_variable1] result4_value1 = City.objects.filter(city=result4.city).values(broad_variable1)[0][broad_variable1] result5_value1 = City.objects.filter(city=result5.city).values(broad_variable1)[0][broad_variable1] result6_value1 = City.objects.filter(city=result6.city).values(broad_variable1)[0][broad_variable1] # assign variables before referencing them result1_value2 = None result2_value2 = None result3_value2 = None result4_value2 = None result5_value2 = None result6_value2 = None # check if the user chose a second variable # get the second user selected specific variable value for each result if broad_variable2 != "Nothing": result1_value2 = City.objects.filter(city=result1.city).values(broad_variable2)[0][broad_variable2] result2_value2 = City.objects.filter(city=result2.city).values(broad_variable2)[0][broad_variable2] result3_value2 = City.objects.filter(city=result3.city).values(broad_variable2)[0][broad_variable2] result4_value2 = City.objects.filter(city=result4.city).values(broad_variable2)[0][broad_variable2] result5_value2 = City.objects.filter(city=result5.city).values(broad_variable2)[0][broad_variable2] result6_value2 = City.objects.filter(city=result6.city).values(broad_variable2)[0][broad_variable2] # assign variables before referencing them … -
filtering annotated-aggregated columns with django_filters
Assume I have a Customer Model which is related to an Order Model. I want to list customers and the Sum(or Count) of their orders between a date range. if there was no order in the given range for any customer the annotated column would be 0. if I use django_filters FilterSet it changes the main WHERE clause of the query so the row with no order wouldn't be displayed, but I want something like: .annotate( order_count=Count( 'customer_orders', filter=Q( customer_orders__create_time__gte=query_params.get('order_after') ) & Q( customer_orders__create_time__lte=query_params.get('order_before') ) ) ) is there a neat way to achieve this using django_filters FilterSet? -
Django serializer.is_valid() makes a call to different custom serializer method
I have a django test server. i want to POST user data and return Response with 'username' and 'Token' after successfull registration. In the following view, I also check if request.data['email'] already exists in Users model because i want it to behave as unique=True and it gives me unexpected results. I know this code is just a noob implementation all around and it doesnt bother me for now, but the more important thing for me is to understand WHY my code is giving these results. I believe a detailed answer will help me understand python so much better. Here is the View function inside views.py : @api_view(['POST']) @permission_classes((AllowAny,)) def Register(request): r={"username": "JohnDoeyy", "password": "Thisisapassword60!", "email": "test@test.com", "age": "50"} #r = request.data if not (r.get("username") and r.get("password") and r.get("email")): return Response("empty fields") serializer = UserSerializer(data=r) print("debug1") if request.method == 'POST': print("debug2") if serializer.is_valid() and serializer.validate_email(r.get("email")): #User.objects.filter(email=r.get("email")).exists(): print("is_valid:", serializer.is_valid()) try: print("debug3 before .save") serializer.save() #This does NOT work. print("debug3 after .save") token, created = Token.objects.get_or_create(user=serializer.instance) return Response({"user": serializer.validated_data['username'], "token": token.key}, status=status.HTTP_200_OK) except Exception as e: print("debugException" , e) return Response(str(e)) else: print("3") return Response("fail") Here is the serializer.py . Possible culprit the validate_email method. class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): … -
Django: Can't set up custom django User model
I want to set up my own django User model because I need additional fields, but I am getting the error. I read a lot of posts but I didn't find solution. What is the problem? Code models.py: class User(AbstractBaseUser): username = models.CharField(max_length=30, unique=True), email = models.EmailField(max_length=50, unique=True), city = models.TextField(max_length=30, blank=True), friends = models.ManyToManyField("Account", blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username'] Code admin.py admin.site.register(User) Code admin settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig' ] AUTH_USER_MODEL = 'users.User' Error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 608, in get_field return self.fields_map[field_name] KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\checks.py", line 55, in check_user_model if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any( File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 610, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: User has no field named 'username' -
skip an iteration of the for loop in python
I need a hand, I don't understand how to fix it. Look at the photo to better understand my speech, where the new field is populated the value of new is subtracted from the total and I don't want it to be subtracted immediately but the next round. How can I do? def UserAndamentoListView(request): giorni = [] mese = [] new_user = [] tot_user = [] tot = User.objects.all().count() for day in range(5): giorni.append(datetime.datetime.now() - datetime.timedelta(days=day)) new = User.objects.filter(date_joined__contains = giorni[day].date()) new_user.append(new) tot -= new.count() tot_user.append(tot) context = {'giorni': giorni, 'new_user':new_user, 'tot_user': tot_user} return render(request, 'andamento.html', context) -
Can't see the address when nginx processes the port and outputs 502 Bad Gateway
I encountered a problem when learning nginx. I have 2 servers on 2 different ports. I want a page with information stored on port 8000 to be returned when accessing "http://localhost/api/v1/clients/". Now I get error 502 Bad Gateway. В консоли: connect() failed (111: Connection refused) while connecting to upstream, client: 111.11.0.1, server: localhost, request: "GET /api/v1/clients/ HTTP/1.1", upstream: "http://111.11.0.2:80/api/v1/clients/", host: "localhost" If I go to the address: "http://localhost:8000/api/v1/clients/", everything is fine. What's my mistake? nginx: upstream backend { server 127.0.0.1:8000; server 127.0.0.1:3000; } server { listen 80; server_name localhost; location /api/v1/clients/ { proxy_pass http://backend_client/api/v1/clients/; } } docker: services: backend_client: build: ./Client volumes: - ./Client/:/app ports: - "8000:8000" restart: always command: "gunicorn --bind=0.0.0.0:8000 django_app.wsgi" nginx: image: nginx:1.17 container_name: ngx ports: - "80:80" volumes: - ./nginx:/etc/nginx/conf.d depends_on: - backend_client -
How to validate and return access and refresh tokens after user.save()
I'm verifying the user OTP to change password and after change password I'm unable to create access and refresh token using JWT , Normally when user get log in I use following method MyTokenObtainPairView which return both access and refresh token with all other stuff to UserSerializerWithToken. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) serializer = UserSerializerWithToken(self.user).data for k, v in serializer.items(): data[k] = v return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer I coppied similar appraoch to return UserSerializerWithToken after set_password and user.save() UserSerializerWithToken is class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = CustomUser fields = ['id', 'isAdmin', 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) and the problematic function is @api_view(['PUT']) def reset_password(request): data = request.data email = data['email'] otp_to_verify = data['otp'] new_password = data['password'] user = CustomUser.objects.get(email=email) serializer = UserSerializerWithToken(user, many=False) if CustomUser.objects.filter(email=email).exists(): otp_to_verify == user.otp if new_password != '': user.set_password(new_password) user.save() # here password gets changed return Response(serializer.data) # else: message = { 'detail': 'Password cant be empty'} return Response(message, status=status.HTTP_400_BAD_REQUEST) else: message = { 'detail': 'Something went wrong'} return Response(message, status=status.HTTP_400_BAD_REQUEST) I receive the toke but not getting access and refresh toke to use it to login next time. I'm assuming user.save() dosnt …