Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In my django project I added this in my allowed host but still getting this error I am using zappa for uploading into AWS Lambda [closed]
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'xyz.ap-south-1.amazonaws.com'. You may need to add '.xyzamazonaws.com' to ALLOWED_HOSTS. [1717411490792] [ERROR] 2024-06-03T10:44:50.778Z c139cd72-2799-426b-8699-df103ac5ec01 Invalid HTTP_HOST header: 'xyz.ap-south-1.amazonaws.com'. You may need to add 'xyz.amazonaws.com' to ALLOWED_HOSTS. -
Validating fields with PrimaryKeyRelatedField
I am working with a DRF serializer which includes a field with the PrimaryKeyRealtedField. import stripe from rest_framework import serializers from subscriptions.models.subscription_product import SubscriptionProduct class SubscriptionCheckoutSessionSerializer(serializers.Serializer): url = serializers.CharField(read_only=True) success_url = serializers.CharField(write_only=True, required=False) cancel_url = serializers.CharField(write_only=True, required=False) subscription_product = serializers.PrimaryKeyRelatedField( queryset=SubscriptionProduct.objects.all() ) def create(self, validated_data): print(validated_data) subscription_product = validated_data["subscription_product"] print(subscription_product) stripe_price = subscription_product.stripe_price print(stripe_price) print(stripe_price.stripe_id) session = stripe.checkout.Session.create( success_url=validated_data.get("success_url", None), cancel_url=validated_data.get("cancel_url", None), mode="subscription", line_items=[ { "price": stripe_price.stripe_id, "quantity": 1, } ], ) print(session) return session The print statements all print their expected output and the created session is a valid one. However, I get a 500 status code with the following error: KeyError: "Got KeyError when attempting to get a value for field subscription_product on serializer SubscriptionCheckoutSessionSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the Session instance.\nOriginal exception text was: 'subscription_product'." Does anyone know what this error actually means and how to solve it? I don't understand how it's possible that the print statements work as expected but I still get a key error. -
not able to quit django server on windows pc
I installed Django just 10 minutes back on my Windows 11 PC and I was trying out this command from a tutorial in a virtual environment i created using anaconda python manage.py runserver and this is what i got Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. June 03, 2024 - 16:21:24 Django version 4.2.13, using settings 'chaiaurDjango.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. now my keyboard doesn't have the break key and I am trying both ctrl+c and ctrl +z but the server wont quit, and neither the command prompt is taking any inputs its just stuck there whatever I type doesn't show on the command prompt, How do i quit the server -
django.db.utils.OperationalError: no such column: media_mediamodule.article_pill
I had decide to add a new views to my Django model name MediaModule. Previously, and as per procedure, you add a new field, give is a default value to it can populate the new field with a value for all existing objects in your Model. However Django is telling me that my new field does not exist: django.db.utils.OperationalError: no such column: media_mediamodule.article_pill This takes place when I run py manage.py makemigrations I thought it was a migrations issue, so I deleted all migration files from the migrations folder and deleted everything except for the __init__.py file. I commented out the relevant field & it has no issue. I checked the database schema and it returned the following result: ('CREATE TABLE "media_mediamodule" ("uuid" char(32) NOT NULL PRIMARY KEY, "article_headline" varchar(100) NOT NULL, "article_body" text NOT NULL, "article_synopsis" text NULL, "article_journalist" varchar(20) NOT NULL, "article_date" datetime NOT NULL, "article_image" varchar(100) NOT NULL, "article_image_summary" text NULL, "article_identifier" varchar(50) NOT NULL UNIQUE)',) >>> But it wouldn't include the new field because it would not allow me to further diagnose the issue until I removed it. Why is this happening? I have cleared the cache, I have cleared the migration history and initiated a … -
Django Session And Cookie
I need a usage example of django session and cookies. Not about Django's interval use of cookies for authentication purposes. request.session.set() request.session.get() request.cokkie how to do all these things??! How to set a session variable properly? How to get that variable in different view? And in client side (frontend) with js? And so for cookies.. -
"django.db.utils.OperationalError: no such column: media_mediamodule.article_new_field" umm... duh?
Yet, another stupid, pointless message from the wonderful Django. Why am I getting the following message when I run the makemigrations command: django.db.utils.OperationalError: no such column: media_mediamodule.article_new_field Is this not a "Duh" moment? I'm trying to add a new bloody category and it's telling me that the column does not exist. Well it would bloody exist if you stopped faffing with silly, pointless "error" messages, and let me add the bloody column. It's like going into a supermarket for a pack of sugar and the store tells you that you don't have a pack of sugar. Um duh - that's why I'm going to the supermarket. from django.db import models import uuid, random, string def generate_unique_id(charlimit): '''This will generate a random set of numbers and letters which will be used to generate a unique URL for each object in the model. ''' random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=charlimit)) # Generates a random string return f"{random_string}" def generate_unique_uuid(): '''This will generate a random set of numbers and letters which are to be derrived from the UUID methodology, which will be used to generate a unique URL for each object in the model. ''' return str(uuid.uuid4())[:8] # Create your models here. class … -
What should I learn after python? [closed]
I'm a beginner programmer. I started with Python, and it's been a month and some since I finished the full Python tutorial. I've also worked on some projects on my own, and not only that, I've modified some projects from other ideas as well. So, what should I learn next? Although I'm not quitting Python, my friend suggested that I should learn Django, but I'm not really into web development. Maybe I'm interested in A.I. or machine learning. So, for that, what should I learn next? My bachelor's in computer science will be held next August. Should I learn other languages like Java or C++, or should I stick with one and focus on related studies? What's your opinion? What should I learn next in programming after completing a Python tutorial if I'm interested in AI and machine learning? -
Numbering 1-4 in django template
I want to increase the number 1 to 4 in django template. How will I do it? enter image description here <span class="number">1</span> I thought it was a work of For Loop, but I couldn't with that. I need help. -
Is there a way to limit the default number of items shown in the Django admin UI to not show all?
I have filters for year_record, age_category, and malnutrition_category. I want the default data shown in my Django admin UI list to correspond to the first value in each filter list. Additional data should only appear when filters are applied or when searching class ProvincialLevelAdmin(ImportExportModelAdmin): resource_classes = [ProvincialLevelResource] list_display = ( 'id', 'province_name', 'percentage', 'forcast_accuracy', 'malnutrition_category', 'year_record', 'age_category', 'level_category', 'provincial_level_coordinate', 'prevalence_category', ) list_filter = ('year_record', 'age_category',,'malnutrition_category') search_fields = ('province_name',) list_per_page = 25 actions = [duplicate_model] My goal is to limit the default data shown in my list because I have a large dataset, and it becomes slow when I am in the ProvincialLevelAdmin list -
Stripe Checkout Session: No session_id Provided in Request After Successful Payment in Django
I'm working on a Django project where users can purchase subscriptions to various packages using Stripe Checkout. However, after a successful payment, I'm encountering an issue where the session_id is not being provided in the request when redirected to the payment_success view. here are the models.py: class Package(models.Model): name = models.CharField(max_length=255) description = models.TextField() price_monthly = models.DecimalField(max_digits=10, decimal_places=2) price_annually = models.DecimalField(max_digits=10, decimal_places=2) tax_percentage = models.DecimalField(max_digits=5, decimal_places=2, default=0) def __str__(self): return self.name class Subscription(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=255) stripe_subscription_id = models.CharField(max_length=255) package = models.ForeignKey(Package, on_delete=models.CASCADE) interval = models.CharField(max_length=10) # 'monthly' or 'annual' active = models.BooleanField(default=True) Here are the relevant views: def package_list(request): packages = Package.objects.all() return render(request, 'subscriptions/package_list.html', {'packages': packages}) def create_checkout_session(request, package_id, interval): package = get_object_or_404(Package, id=package_id) if interval not in ['monthly', 'annually']: return redirect('package_list') if interval == 'monthly': price = package.price_monthly_including_tax() stripe_interval = 'month' else: price = package.price_annually_including_tax() stripe_interval = 'year' session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'cad', 'product_data': { 'name': package.name, }, 'unit_amount': int(price * 100), # Stripe expects the amount in cents 'recurring': { 'interval': stripe_interval, }, }, 'quantity': 1, }], mode='subscription', success_url=request.build_absolute_uri('/subscriptions/payment-success/?session_id={{CHECKOUT_SESSION_ID}}'), cancel_url=request.build_absolute_uri('/subscriptions/packages/'), customer_email=request.user.email if request.user.is_authenticated else None, ) return redirect(session.url, code=303) def payment_success(request): session_id = request.GET.get('session_id') if not session_id: logger.error("No … -
Print hello world in your root folder to know your web server supports python?
How to pint hello wold in python on a web server ? i'm new to pyhon and i want to see a python file running on my web server . This problem can be for any starters and can help many users to identify with their web servers if they can run python scripts. -
How to enter a Hatch shell development environment in the VS Code debugger launch profile when debugging django
I need to run the command 'hatch shell' to enter my hatch development environment before running the server command 'py manage.py runserver'. I can't find out how to do this using the VS code debugger profile specified in the launch.json file below. { "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/testproject/manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true } ] } I tried to run 'hatch shell' as a preLaunchTask but that runserver command did not run in the shell environment. -
Django: How to undo ModuleNotFoundErrors due to multiple site-packages locations
When I run my Django project, why does it check for site packages in a folder other than where my project is located? The correct location where the project and package files are located is: C:\Users\mattk\Box\WeConsent But in the error thread below, it seems to be searching in two separate locations for my library files: C:\PythonProjects\VoterSay7\venv\Scripts\python.exe # my packages are not located here C:\Users\mattk\Box\WeConsent\manage.py runserver localhost:8000 # my packages are located here. Where in PyCharm can I specify to ignore this location: C:\PythonProjects\VoterSay7\venv\Scripts\python.exe when loading my packages? from traceback in Terminal: C:\PythonProjects\VoterSay7\venv\Scripts\python.exe C:\Users\mattk\Box\WeConsent\manage.py runserver localhost:8000 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\mattk\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\mattk\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\core\management\commands\runserver.py", in inner_run autoreload.raise_last_exception() File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\mattk\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in … -
NumPy Error will appear and uninstalling and reinstalling is the only way to fix it
I currently have a Django app and I will randomly run into this below error. The app will run fine, sometimes when I make a change to the code, the below error will show, even if the changes weren't related to NumPy or Pandas. If I uninstall and then reinstall Pandas and NumPy, it'll fix the error. ImportError: Unable to import required dependencies: numpy: Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python interpreter from there. I am using a virtual environment Django 4.2.5 and tried pretty much every recent version of NumPy and Pandas -
Django can not render the result
i have created the feedback app on learning system however i can not render the feedback page that return feedback details when i click the feedback link it does not return anything as shown below. enter image description here Below is the view.py # feedback/views.py from django.shortcuts import render, redirect from django.contrib import messages from accounts.models import User def feedback_view(request): feedback_data = User.objects.filter(username=request.user) context = { "feedback_data": feedback_data } return render(request, "feedback/feedback.html", context) @property def feedback_save(request): if request.method != "POST": messages.error(request, "Invalid Method.") return redirect('feedback') else: feedback = request.POST.get('feedback_message') feedback_data = User.objects.get(username=request.user.id) try: add_feedback = FeedBack(username=feedback_data, feedback=feedback, feedback_reply="") add_feedback.save() messages.success(request, "Feedback Sent.") return redirect('feedback') except: messages.error(request, "Failed to Send Feedback.") return redirect('feedback') model.py from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class FeedbackMessage(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) feedback = models.TextField() feedback_reply = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() feedback.html {% extends 'base.html' %} {% block page_title %} Feedback Message {% endblock page_title %} {% load static %} {% block main_content %} this is a test <section class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Leave a Feedback Message</h3> </div> <!-- … -
OSError at /en/reset_password/ [Errno 101] Network is unreachable
So I am making a django project on Google Cloud, I have added a forgot password feature from Django's built-in feature and I already tried it locally. But when I tried it on the cloud it gave me this error.... OSError at /en/reset_password/ [Errno 101] Network is unreachable Request Method: POST Request URL: http://34.128.98.45:8000/en/reset_password/ Django Version: 5.0.3 Exception Type: OSError Exception Value: [Errno 101] Network is unreachable Exception Location: /usr/lib/python3.10/socket.py, line 833, in create_connection Raised during: django.contrib.auth.views.PasswordResetView Python Executable: /home/rsa-key-20240516/env/SlangID/bin/python Python Version: 3.10.12 Python Path: ['/var/www/html/SlangID/src', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/rsa-key-20240516/env/SlangID/lib/python3.10/site-packages'] Server time: Sun, 02 Jun 2024 11:55:50 +0000 I really don't understand what to do I already tried adding a firewall rule to allow smtp connections like this image.... Even after that it still gave me the same error, chatGPT (I was desperate) reccomended to try ping IP 8.8.8.8. When I tried pinging it works well.... :~$ ping 8.8.8.8 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=122 time=1.91 ms 64 bytes from 8.8.8.8: icmp_seq=2 ttl=122 time=0.552 ms Then I tried pinging telnet smtp, like this... ~$ telnet smtp.gmail.com 587 Trying 74.125.130.108... Connected to smtp.gmail.com. Escape character is '^]'. 220 smtp.gmail.com ESMTP d9443c01a7336-1f632356aa0sm47645545ad.74 - gsmtp which … -
getting an empty folder in django new project
I created a virtual environment than I installed Django successfully but when I try to create a project with Django-admin start-project project-name Django create an empty folder? I'm expecting a folder with file with manage.py in the folder -
how do I run python code and opencv in the views file django?
#My views file in django from django.shortcuts import render from .forms import ImageForm from .models import Image def image_upload_view(request): """Process images uploaded by users""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # Get the current instance object to display in the template img_obj = form.instance #at this point, I want to pass to the function a photo that has just been sent to the ######form return render(request, 'polling/pool.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'polling/pool.html', {'form': form}) Python code def scan_photo(group, name_photo): '''Сканирует карточки на фото''' global answers, input_field, label_entry_get answers = [] #label_entry_get['text'] = f'{input_field.get()}' #name = str(str(name_photo) + ".jpg") frame = cv2.imread(name_photo, cv2.IMREAD_COLOR) cv2.imshow('gfgfgg', frame) for identification, answer in recognizes_cards(frame, group): if identification <= len(group): answers.append((identification, answer)) print('Сканирование завершено') print('Результаты:') for identification, answer in answers: print(f'Студент: {group[identification - 1]["name"]} {group[identification - 1]["surname"]}, Ответ: {answer}') print(answers) -
How to properly dockerize Celery with Django?
I am having a little trouble dockerizing Celery alongside my Django project. Recently I had the need to add Celery to my projects, and I have worked with it prior, but not in a Docker environment. I am looking for a proper way to dockerize my Celery worker that works alongside my configuration. This is my django dockerfile: FROM python:3.9.13-slim CMD ["mkdir", "app/backend/"] WORKDIR /app/backend/ COPY ./backend/ . ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip && \ pip install -r requirements.txt && \ python manage.py collectstatic --noinput && \ chmod +x scripts/entrypoint.sh CMD ["scripts/entrypoint.sh"] This is my entrypoint script (all it does is start the gunicorn server): #!/bin/bash APP_PORT=${PORT:-8000} gunicorn project.wsgi:application --reload --bind "0.0.0.0:${APP_PORT}" This is my docker-compose: version: '3.8' services: backend: container_name: project-backend build: context: . dockerfile: docker/backend/Dockerfile volumes: - static:/app/backend/static ports: - "8000:8000" depends_on: - database redis: container_name: project-redis image: redis:alpine database: image: postgres:15 container_name: project-postgres volumes: - postgres_data:/var/lib/postgresql/data env_file: - ./backend/project/.env ports: - "8001:5432" frontend-nginx: container_name: project-frontend-nginx build: context: . dockerfile: docker/frontend-nginx/Dockerfile volumes: - node_modules:/app/frontend/node_modules - static:/app/backend/static ports: - "80:80" depends_on: - backend - database volumes: static: postgres_data: node_modules: Ignore the other services in the docker-compose, this is all the other stuff needed for my project … -
Method \"POST\" not allowed. django rest framework
I dont know, after a certain moment the part of my api stopped working. So i have my apiview written and it has post function, but when i knock on an endpoing i get error that post method is not allowed, but other parts of api work fine so i definetely have something wrong with postview project.urls `from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt import views as jwt_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/', include('authentification.urls')), path('api/v1/', include('posts.urls')), # This includes the posts app URLs path('api/v1/payments/', include('payments.urls')), path('api/v1/support/', include('support.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` posts.urls from django.urls import path from .views import Lenta_View, Post_View, Profile_View, Settings_View, Like_View, Posts_search, Bookmark_View, Separated_lenta urlpatterns = [ path('', Lenta_View.as_view(), name='lenta'), path('<slug:filter>/', Separated_lenta.as_view(), name='lenta'), path('posts/', Post_View.as_view(), name='post_list_create'), path('posts/<int:id>/', Post_View.as_view(), name='post_detail'), path('profile/', Profile_View.as_view(), name='profile_mine'), path('profile/<slug:username>/', Profile_View.as_view(), name='profile_other'), path('settings/', Settings_View.as_view(), name='settings'), path('like/', Like_View.as_view(), name='like_all'), path('like/<int:id>/', Like_View.as_view(), name='like_add'), path('search', Posts_search.as_view(), name='search'), path('bookmarks/', Bookmark_View.as_view(), name='bookmark_list'), path('bookmarks/<int:id>/', Bookmark_View.as_view(), name='bookmark_add'), ] Post_View class Post_View(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def get(self, request, *args, **kwargs): id = kwargs.get("id") user = request.user if id is None: return Response({'message': "You haven't provided an … -
Django test case is showing errors because of moesif
I do not want to push actual api key. When I replaced the actual key on code base this error is generated E vcr.errors.CannotOverwriteExistingCassetteException: Can't overwrite existing cassette ('/app/armor_backend/users/tests/recordings/test_user_with_empty_code.yaml') in your current record mode ('once'). E No match for the request (<Request (GET) https://api.moesif.net/v1/config>) was found. E Found 1 similar requests with 0 different matcher(s) : E E 1 - (<Request (GET) https://api.moesif.net/v1/config>). E Matchers succeeded : ['uri', 'method'] E Matchers failed : /usr/local/lib/python3.10/site-packages/vcr/stubs/__init__.py:231: CannotOverwriteExistingCassetteException ----------------------------- Captured stdout call ----------------------------- Unauthorized access getting application configuration. Please check your Appplication Id. ------------------------------ Captured log call ------------------------------- ERROR moesifapi.controllers.base_controller:base_controller.py:41 HTTP Response not ok [response status: 401 | header: {'Connection': 'keep-alive', 'Content-Length': '153', 'Content-Type': 'application/json', 'Date': 'Wed, 09 Feb 2022 06:18:37 GMT', 'content-encoding': 'gzip', 'vary': 'Origin,Accept-Encoding'} | raw_body: {"moesif_error":{"code":"auth_error","msg":"X-Moesif-Application-Id request header is invalid. Please get a valid Moesif Collector Application Id from your Moesif account"}}] I skipped all outgoing and incoming calls from logging for testing. But still moesif is being called somehow. Here is my test case @vcr.use_cassette def test_user_with_invalid_code( self, client, use_invalid_code ): response = client.post( self.endpoint, content_type="application/json", data=json.dumps(use_invalid_code), ) assert response.status_code == status.HTTP_400_BAD_REQUEST I tried to skip logging all the incoming and outgoing calls but no luck -
Best way to share audio files on my website
I am developing a music-sharing app using Django and React. My problem is that on the home page, I could very well have up to 100 different songs, with each audio file being around 40 MB. This of course causes performance issues, and I don't know how to solve them. At the moment I am using Google Cloud storage for hosting audio files, should I switch to something else? Is the issue even in Google Cloud? I am new to handling a growing amount of data on the website so all suggestions are welcome. Thank you! -
Data not being saved to the Profile model
When attempting to register a new user through the registration form, the phone number (phone_number) and library ID (library_id) fields are not being saved to the database. Despite these fields being included in the registration form and rendered correctly, the submitted values are not written the database. views.py def user_register(request): userIsAuthenticated = False if request.user.is_authenticated: username1 = request.user.username userIsAuthenticated = True else: username1 = "N/A" userIsAuthenticated = False if request.method == 'GET': form = RegisterForm() return render(request, "register.html", {"form":form, "username": username1, "userIsAuthenticated": userIsAuthenticated}) if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() login(request, user) return render(request, "register-success.html") else: return render(request, 'register.html', {"form":form, "username": username1, "userIsAuthenticated": userIsAuthenticated}) forms.py class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) library_id = forms.CharField(max_length=100) phone_number = forms.CharField(max_length=100) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] def save(self, commit=True): user = super().save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: Profile.objects.create( user=user, phone_number=self.cleaned_data['phone_number'], library_id=self.cleaned_data['library_id'] ) user.save() return user models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=100) library_id = models.CharField(max_length=100) def __str__(self): return self.user.username signals.py @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() More details … -
How to Write a Code When Software are Close In One Year
kaise hum apne software ko diye gye time line me bnd kr skte hai kya coding hogi and kya process hoga ?? kaise coding and impliment krna hoga ki hum apna software one year me bnd kr ske python and django faremwork ko code likhna hai -
How to set image size in megabytes for "factroy.django.ImageField" ? e.g "my_img = ImageField(size=30)"
I have model Shop class Shop(models.Model): logo = models.ImageField("Logo", upload_to="logos/", blank=True, null=True) def save(self, *args, **kwargs): # condense logo if it's more than 30mb if self.logo: # instance = super().save(*args, **kwargs) logo_path = self.logo.path logo = Image.open(logo_path) logo_size = os.path.getsize(logo_path) # in bytes thirty_mb = 30 * 1024 * 1024 while logo_size > thirty_mb: logo = logo.convert("RGB") logo.save( logo_path, quality=60, optimize=True, format="JPEG", ) return instance And I have this factory for Shop model import factory from api.v1.apps.shops.models.shops import Shop from factory.django import DjangoModelFactory, ImageField class ShopModelFactory(DjangoModelFactory): class Meta: model = Shop logo = ImageField() # what I have logo = ImageField(size_in_megabytes=30) # what I want what I exactly want to do is tell to ImageField generate img with given size I looked at documentaino but find nothing https://factoryboy.readthedocs.io/en/stable/orms.html#factory.django.ImageField