Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to add created_at with nulls for old records?
I'm trying to add created_at field to a table with millions of records, and I don't want to add value to the previous records. I have tried the following: created_at = models.DateTimeField(auto_now_add=True) OR created_at = models.DateTimeField(auto_now_add=True, null=True) Still, it set the value to all records, not only to new ones. How can I keep the old with nulls? My database is postgresql -
celery in django project unable to connect to dockerized RabbitMQ in local development
everything runs on mac - i have an django project with celery running. I configured (as always) RabbitMQ as Broker and Redis as Result Backend. When i start the worker i get [2022-11-18 11:53:56,256: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: Server unexpectedly closed connection. Trying again in 18.00 seconds... (9/100) celery settings CELERY_TIMEZONE = TIME_ZONE CELERY_RESULT_BACKEND = "redis://localhost" CELERY_BROKER_URL = "amqp://localhost" docker-compose.yaml version: "3.8" services: db: image: postgres:14 ports: - "5432:5432" environment: - POSTGRES_DB=local - POSTGRES_USER=test_user - POSTGRES_PASSWORD=test_test1! volumes: - db-data:/var/lib/postgresql/data redis: image: redis ports: - "6379:6379" volumes: - redis-data:/data rabbitmq: image: rabbitmq:management ports: - "5672:5762" - "15672:15672" volumes: db-data: redis-data: Connecting to the Management panel with base guest:guest works fine, but celery can't connect. Expecting that celery can connect to rabbitmq and no connection gets closed -
Passing variable to href django template
I have some problem and maybe I can give an example of two views below what I want to achieve. class SomeViewOne(TemplateView): model = None template_name = 'app/template1.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # The downloads view contains a list of countries eg France, Poland, Germany # This returns to context and lists these countries in template1 class ItemDetail(TemplateView): model = None template_name = 'app/template2.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) countries_name = kwargs.get('str') The view should get the passed "x" with the name of the country where I described it below. Then on the page I have a list of these countries. After clicking on the selected country, a new tab should open and show a list of cities in the selected country. So I am using in loop template1.html as below {% for x in list_countries %} <li> <a href="{% url 'some-name-url' '{{x}}' %}" class="target='_blank'">{{ x }}</a><br> </li> {% endfor %} I can't pass "x" this way. Why? The url for the next view looks like this path('some/countries/<str:x>/',views.ItemDetail.as_view(), name='some-name-url'), And I can't get that 'x' given in the template in the href -
How to add trix.css when it is removed after pruning?
After pruning with the command "docker system prune -a" nodejs wont build anymore beacuse trix.css is missing. I am assuming this was probably deleted while pruning. How can I resolve this error (see the error below)? Why is it not created again while building the container again since the file is in the docker file. Required path doesn't exist: /code/bower_components/trix/dist/trix.css trix [13:57:39] 'vendorcss' errored after 1.63 ms [13:57:39] Error: Promise rejected without Error at Domain.onError (/usr/local/lib/node_modules/gulp/node_modules/async-done/index.js:49:15) at Object.onceWrapper (events.js:315:30) at emitOne (events.js:116:13) at Domain.emit (events.js:211:7) at Domain._errorHandler (domain.js:134:21) at process._fatalException (bootstrap_node.js:375:33) [13:57:39] 'staging' errored after 41 ms ERROR: Service 'nodejs' failed to build: The command '/bin/sh -c gulp staging' returned a non- zero code: 1 Usually I use this command : "sudo docker-compose -f docker-compose-staging.yml build nodejs" when I want to build the container again. I am very new to this and would be greatfull for some help. -
Error: Apps aren't loaded yet. when fork subprocess in django views
I want to fork subprocess in django view def subprocess_setup(): if not settings.configured: settings.configure() django.setup() class ABView(CustomModelViewSet): def _query_facebook_balance(self, query_record_id): ... @action(methods=['get'], url_path='account-balance', detail=True) def query_account_balance(self, request, *args, **kwargs): with ProcessPoolExecutor(max_workers=3, initializer=subprocess_setup) as pe: process_list = [] future = pe.submit(VSSign()._query_facebook_balance, query_record_id) process_list.append(future) for future in as_completed(process_list): future.result() ... return Response(self.response_no_http_error(data=ret)) but it always failed like below. Process SpawnProcess-1: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/concurrent/futures/process.py", line 240, in _process_worker call_item = call_queue.get(block=True) File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/queues.py", line 122, in get return _ForkingPickler.loads(res) File "/Users/apple/Develop/bv_crm/api/sign/views.py", line 19, in <module> from rest_framework.decorators import action File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/decorators.py", line 13, in <module> from rest_framework.views import APIView File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/views.py", line 17, in <module> from rest_framework.schemas import DefaultSchema File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/schemas/__init__.py", line 33, in <module> authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES, File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/settings.py", line 220, in __getattr__ val = perform_import(val, attr) File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/settings.py", line 168, in perform_import return [import_from_string(item, setting_name) for item in val] File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/settings.py", line 168, in <listcomp> return [import_from_string(item, setting_name) for item in val] File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/rest_framework/settings.py", line 177, in import_from_string return import_string(val) File "/Users/apple/Develop/bv_crm/venv3.9/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/Cellar/python@3.9/3.9.13_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/Users/apple/Develop/bv_crm/utils/middleware.py", line 10, in … -
is it possble to split saving data automatically?
i have created 2 table, A and B. is it possible to split the data by choice? I mean like while creating data when i pick a from load_type it auto save my data to table A or if i pick b it save to table B.and while i was in B when i change the load_type to a it moves my data to A. is it possible? models.py ` class LoadType(models.Model): load = [ ('a','typeA'), ('b','typeB') ] load_type = models.CharField(max_length=10,choices=load) class A(models.Model): code = models.AutoField(primary_key=True) load_type = models.ForeignKey(LoadType,on_delete=models.DO_NOTHING) load_no = models.CharField(max_length=255,blank=True,null=True) material_no = models.CharField(max_length=255,blank=True,null=True) quantity = models.IntegerField() move_type = models.CharField(max_length=255,blank=True,null=True) start_area = models.CharField(max_length=255,blank=True,null=True) start_point = models.CharField(max_length=255,blank=True,null=True) end_area = models.CharField(max_length=255,blank=True,null=True) end_point = models.CharField(max_length=255,blank=True,null=True) priority = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) class B(models.Model): code = models.AutoField(primary_key=True) load_type = models.ForeignKey(LoadType,on_delete=models.DO_NOTHING) load_no = models.CharField(max_length=255,blank=True,null=True) material_no = models.CharField(max_length=255,blank=True,null=True) quantity = models.IntegerField() move_type = models.CharField(max_length=255,blank=True,null=True) start_area = models.CharField(max_length=255,blank=True,null=True) start_point = models.CharField(max_length=255,blank=True,null=True) swap_area = models.CharField(max_length=255,blank=True,null=True) swap_point = models.CharField(max_length=255,blank=True,null=True) end_area = models.CharField(max_length=255,blank=True,null=True) end_point = models.CharField(max_length=255,blank=True,null=True) priority = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) ` Not sure if i need to add a new form or add some function ? -
Translate django admin log entry messages
I've a small django mezzanine application in https://github.com/miettinj/mezzanine It translates admin interface correctly, but it also should translate the page history to understandable form. (I guess it comes directly from django_admin_log in database) Now the admin log looks like this: { "model": "admin.logentry", "pk": 2, "fields": { "action_time": "2022-11-18T08:34:03.136Z", "user": 1, "content_type": 18, "object_id": "1", "object_repr": "janes post", "action_flag": 2, "change_message": "[{\"changed\": {\"fields\": [\"Content\", \"Keywords\"]}}]" } } How can I change it so that it translates the action 'changed', remains the field names unchanged and totally removes the unuserfrienly characters: ("[{\) ? -
Implement HTTP methods in different APIView class in django
I have an API with 2 routes some_resource/ and some_resource/<id> and I would like to implement the normal CRUD actions (list, retrieve, create, update, delete). However, I don't want to use ViewSet because I want to have 1 class for each view. Thus I need to set up the route manually for clarity. : class SomeResourceRetrieveView(APIView): def get(self, request, pk, *args, **kwargs): ... class SomeResourceListView(APIView): def get(self, request, *args, **kwargs): ... class SomeResourceCreateView(APIView): def post(self, request, *args, **kwargs): ... So in urls.py it looks like this url_patterns = [ path("some_resource/", InvitationTeamAccessListAPI.as_view(), name="some-resource-list"), path("some_resource/", InvitationTeamAccessCreateAPI.as_view(), name="some-resource-create"), path("some_resource/<int:pk>", InvitationTeamAccessRetrieveAPI.as_view(), name="some-resource-retrieve"), ] However when I use POST on some_resource/, I get a 405. I think django stops at the first matched route and doesn't find an implementation for post. Is there a way to plug all my views to the same pattern but keep them as separate classes? -
Add angular dist folder to Django project
I am doing the following project: https://github.com/ivandmn/Angular-Django In which I make a simple api with django and use angular as frontend, I have already done the ng build of the angular project where I have the "frontend/static" folder with all the static files. My question is how to add the angular files in django, if someone can explain the structure and the code of how to do it, and then how to manage the angular routes together with the Django ones. PS: I have never put an app into production and it is being very complicated for me, if you can help me I would appreciate it Thank you! -
Getting id number (int) from from a model
I'm working with django and i'm trying to retrieve on id number from my profile model class Profile(Model): user = OneToOneField(User, on_delete=CASCADE) image = ImageField(upload_to='accounts/static/images', blank=True, null=True) gender = CharField(max_length=6, choices=GENDER, default='Male', blank=True) biography = HTMLField(blank=True) def __str__(self): return f"{self.user.username} Profile" and in my views i want to get the @login_required def home(request): return HttpResponseRedirect( reverse('profile_view', args=[request.user.objects.id])) when profile id and user id have the same value, every thing is okay. If i delete a profile and then use this view, the pk's won't match. Hot to 'request' it from the profile for a given user ? As above, but this will not work when user and profile have different pk. -
Why is my docker image not running when using docker run (image), but i can run containers generated by docker-compose up?
My docker-compose creates 3 containers - django, celery and rabbitmq. When i run the following commands -> docker-compose build and docker-compose up, the containers run successfully. However I am having issues with deploying the image. The image generated has an image ID of 24d7638e2aff. For whatever reason however, if I just run the command below, nothing happens with an exit 0. Both the django and celery applications have the same image id. docker run 24d7638e2aff This is not good, as I am unable to deploy this image on kubernetes. My only thought is that the dockerfile has been configured wrongly, but i cannot figure out what is the cause docker-compose.yaml version: "3.9" services: django: container_name: testapp_django build: context: . args: build_env: production ports: - "8000:8000" command: > sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code links: - rabbitmq - celery rabbitmq: container_name: testapp_rabbitmq restart: always image: rabbitmq:3.10-management ports: - "5672:5672" # specifies port of queue - "15672:15672" # specifies port of management plugin celery: container_name: testapp_celery restart: always build: context: . args: build_env: production command: celery -A testapp worker -l INFO -c 4 depends_on: - rabbitmq Dockerfile ARG PYTHON_VERSION=3.9-slim-buster # define an alias for the … -
Django Initial Usage for getting latest id to print to form
I wanna make patient register form and i want each new patient start with initial number. So this is my form. I did these views.py codes but, on the screen nothing. How can i fix this. And then my real goal is start patient register with a default=0 id and then each new patient id must be +1 extra. How can i do this. Thanks for help. Here are my codes. Models.py class Patient(models.Model): GENDER_CHOICES = ( ("M", "Male"), ("F", "Female"), ("O", "Other") ) """ aadhaarId = models.AutoField(primary_key=True ) """ aadhaarId = models.CharField(primary_key=True, max_length=6, help_text= "12 digit aadhar no" ) name = models.CharField(max_length=20) date_of_birth = models.DateField(max_length=8, help_text="YYYY-MM-DD") gender = models.CharField(choices=GENDER_CHOICES, max_length=1) # Patients will be sorted using this field last_updated_on = models.DateTimeField(auto_now=True) class Meta: verbose_name = "patient" verbose_name_plural = "patients" ordering = ["-last_updated_on"] def __str__(self): return self.name + '-' + self.aadhaarId views.py @login_required() def patientCreate(request): if request.method == "POST": intaial_data = { 'aadhaarId': '999088'} form = PatientForm(request.POST, initial=intaial_data) id = request.POST['aadhaarId'] if form.is_valid(): try: form.save() messages.success(request, 'New Patient is successfully added.!') model = form.instance return redirect('/patient-detail/{}'.format(id)) except: messages.error(request, 'failed to add patient') else: form = PatientForm() return render( request, 'patient_records/patient-create.html', {'form': form} ) -
Django - how to filter a model in a foreign key field?
I have two models for categories: list of categories for all users (each unique) and list of connections between user and category. category/models.py class CategoryList(models.Model): name = models.TextField(unique=True, max_length=60, verbose_name='Category name') def __str__(self): return f'{self.name}' class UserCategories(models.Model): category = models.ForeignKey(CategoryList, on_delete=models.deletion.CASCADE, verbose_name='User's categories') user = models.ForeignKey(User, on_delete=models.deletion.CASCADE, verbose_name='User') def __str__(self): return f'{self.category.name}' Also i have transactions: transactions/models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.deletion.CASCADE, verbose_name='Transaction from') payment_amount = models.DecimalField(default=0, decimal_places=2, max_digits=20, verbose_name='Payment amount') date = models.DateField(auto_now=True, verbose_name='Date') time = models.TimeField(auto_now=True, verbose_name='Time') category = models.ForeignKey(UserCategories, null=True, on_delete=models.deletion.SET_NULL, verbose_name='Category') organization = models.TextField(max_length=60, verbose_name='Organization') description = models.TextField(max_length=300, null=True, blank=True, verbose_name='Transaction discription') I have the next issue: i'm using DRF to do CRUD operations with transactions and when i'm trying to add transaction (it select's current authorized user) or update it - i get all the categories in field category = models.ForeignKey(UserCategories...) and that's not what i want. As i understand selecting a model in foreign key is something like models.ForeignKey(UserCategories.objects.all()), but that's not what i want... I need smth like filtration, while creating/updating transaction it have to show me only list of categories for my current user, not for all! I need final result like category = models.ForeignKey(UserCategories.objects.filter(user=user)) but i don't know (and even … -
Django DRF: "Positional argument follows keyword argument unpacking" when trying to add current user
I'm trying to add the currently logged in user into the "user" foreign key field in the "LeadFacilityAssign" model, everytime a leadfacility object gets created. But I'm getting this: "Positional argument follows keyword argument unpacking" models.py class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) agent = models.ForeignKey("User", null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f"{self.first_name} {self.last_name}" class LeadFacilityAssign(models.Model): assigned_facilities = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='leadfacility', null=True, blank=True) lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='leadfacility', null=True, blank=True) datetime = models.DateTimeField(null=True, blank=True) user = models.ForeignKey('User', on_delete=models.CASCADE, null=True, blank=True, related_name='owner') serializers.py class AssignedFacilitySerializer(serializers.ModelSerializer): class Meta: model = LeadFacilityAssign fields = ('assigned_facilities', 'datetime', 'user') class LeadUpdateAssignedSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = AssignedFacilitySerializer(required=False, many=True, allow_null=True) class Meta: model = Lead fields = ( "id", "agent", "is_owner", "assigned_facilities", ) read_only_fields = ("id", "agent", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user def update(self, instance, validated_data): assigned_facilities = validated_data.pop("assigned_facilities", []) user = self.context["request"].user instance = instance for item in assigned_facilities: instance.leadfacility.create(**item, user) return instance -
I need to make regular working Queue when its not empty in Django
PROJECT: I am making a web app, where users send a ZIP file, it saves to the folder. There is a VM continuously looking for that folder where the zip gets extracted. Note that VM is only 1. So I have to extract, sleep for 20 seconds and remove the files from that folder, VM generates the results, then my Django app generates a CSV from those files, and return to user as downloadable. This is the flow. Problem: MultiUsers: I am using a file, like below def Uplaoder(request): file=takenFromPost() #lets assume this works. with open('busy.txt', 'r') as f: if "false" in f: with open('busy.csv', 'w') as f: f.write('true') #here I made it true so that if its true, the request doesn't disturb it as single VM f.close() finalcsv=workFurther() #here is the whole process lets say. with open('busy.csv', 'w') as f: f.write('false') f.close() return render(request, 'worked.html', {'finalcsv':finalcsv}) elif "true" in f: Uploader(request) #here I send this request again to this so that the user keeps waiting and when the #files gets generated for the second user, he gets the response. Here is the example logic, same as my code works. Problem: Logic seemed me well but the browser doesn't wait … -
User accessible in views but not in template
I am trying to use {% if user.is_authenticated %} in a template, but the user actually doesn't exist. If I try to output {{ user }}, there is nothing. In my settings I have those options for TEMPLATES: "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", I developed an authentication backend class to use the credentials of the active directory and added the class to AUTHENTICATION_BACKENDS in settings.py. class CustomAuthenticationBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): """ Authenticate user from active directory If user is not found, create it """ # Get user from database try: user = User.objects.get(username=username) # If user does not exist, create it except User.DoesNotExist: user = User(username=username) user.displayed_name = kwargs['display_name'] user.email = kwargs['email'] user.save() return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None I added the authenticate logic and the login logic to a django Form: def authenticate_and_login(self, request) -> bool: """ Method to authenticate the user and login return True if user is authenticated and logged in or False and fill the form with errors """ is_logged = False # Init active directory service ad_service = ActiveDirectoryService() # Get username and password username = self.cleaned_data['username'] password = self.cleaned_data['password'] # Get authorized user from … -
How to store mathematical symbols and formulas in column sqlalchemy Postgres as DB
I have two questions: What I want to do is to be able to store a mathematical question with special symbols, formulas that are part of the text. What column should I define in SQLAlchemy so that I can get back the equation without any issue. Second part involves in data entry, I want to upload questions in bulk, now the special symbols cannot be defined/written as text in excel, I was able to do it in MSWord. Is there any specific rules that I can define so I can read the equation in that rule and transform it into mathematical equation. For Ex. similar to latex, if we type [\sqrt{x^2+1}], we see the math format in pdf. That way I can provide a input text where they can write equations in that format and it automatically converts it into math formulae and display it as such. Now is there any intelligent way to achieve this? I'm using Fastapi with SQLAlchemy and for database, I'm using Postgres. If you could point me to relevant resources, that would have great help. -
Django with mysql, faced 'table doesn't exist' error randomly at different times of the day
I'm currently using Django version 2.2.28 with mysql innodb engine version 5.7, before some days i faced a crazy issue, here: (MySQLdb._exceptions.ProgrammingError) (1146, "Table 'db_name.table_name' doesn't exist") What's driving me crazy is that they happen on different tables at different times (not always). I couldn't even get a specific pattern. i can confirm no change in the code happened from along o week and no release happened, The problem started happening 3 days ago and randomly, same table is currently working fine and a minute later the same exception is returned and then back to working fine. i used RDS from AWS, and have different DBs under of it, the issue happening only on one of these DBs. i also checked logs file from mysql and i don't fond any thing useful, i just found errors like this [ERROR] InnoDB: MySQL is freeing a thd though trx->n_mysql_tables_in_use is 2 and trx->mysql_n_tables_locked is 654 and i think it's irrelevant. I make sure about all permissions for the user too. and i did a failover for the whole RDS and nothing working. I don't think it has to do with django's migration command, because this problem always happened randomly. can any one … -
Static files apply on all pages except index.html and base.html
I have an issue about static files. i uploaded the code on pyanywhere all good, it runs, i linked the static urls in pyanywhere>web page corectly. the issue is that my static does not load on the index and base.html but on the other pages (where i have base.html extend it applies). Can you give me some support please? how it looks python anywhere url STATIC_URL = 'static/' STATIC_ROOT = "home/Tsh2Dns/businessplaner/static/" #i tried to give root from pythonanywhere. still same response STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATICFILES_DIR = [ os.path.join(str(BASE_DIR.joinpath('static')),) ] folders: -
How to use a custom ModelForm in User admin
I'm trying to limit standard user possibilities in the User application Django's admin, to avoid the possibility of privileges escalation. I've tried the approach mentioned in docs: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form class UserAdmin(BaseUserAdmin): form = UserForm inlines = (UserProfileInline,) def get_form(self, request, obj=None, **kwargs): if request.user.is_superuser: kwargs["form"] = SuperUserForm return super().get_form(request, obj, **kwargs) class UserForm(ModelForm): class Meta: model = User exclude = ("is_superuser",) # it is just an example class SuperUserForm(ModelForm): class Meta: model = User fields = "__all__ Unfortunately, this results in such an error: "Key 'is_superuser' not found in 'UserForm'. Choices are: date_joined, email, first_name, groups, is_active, is_staff, last_login, last_name, password, user_permissions, username." If I would decide to exclude "groups": "Key 'groups' not found in 'UserForm'. Choices are: date_joined, email, first_name, is_active, is_staff, is_superuser, last_login, last_name, password, user_permissions, username." -
Django html css
I hava a problem with a background image, I can't load the picture on the page, I don't know what the problem is Here is my code: <style> body { background-image: url("../img/mountains.jpg"); } </style> enter image description here -
SMTPSenderRefused at /contacts
I am using Django. I want to send email via html contact form. And I am facing this error: SMTPSenderRefused at /contacts (530, b'5.7.0 Must issue a STARTTLS command first. p6-20020a1c5446000000b003b47e75b401sm7708347wmi.37 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: http://127.0.0.1:8000/contacts Django Version: 4.1.2 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Must issue a STARTTLS command first. p6-20020a1c5446000000b003b47e75b401sm7708347wmi.37 - gsmtp', 'webmaster@localhost') Here is my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TSL = True EMAIL_HOST_USER = 'email@gmail.com' EMAIL_PASSWORD = 'Key' EMAIL_PORT = 587 EMAIL_USE_SSL = False Here is my view.py def contacts(request): selected = "contact" if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('comments') data = { 'name':name, 'email': email, 'subject': subject, 'message': message } message = ''' New Message : {} From : {} '''.format(data['message'], data['email']) send_mail(data['subject'], message,'' ,['qweaverinfo@gmail.com']) return render(request, 'layouts/auth-signup-success.html', locals()) return render(request, 'layouts/contact.html', locals()) I don't understand how to fix the STARTTLS. Is anyone here to help me? I tried to use the SSL, I met the same problem. I want to the Django documentation, I did not find anything about the STARTTLS command. I was expecting to send email via a html template using Django. -
What is the diffenrence between psycopg2 vs psycopg3
please give me short explanation what is the difference between https://pypi.org/project/psycopg/ and https://pypi.org/project/psycopg2/ If i have Django3.2 what i have to use? Any advantages? In official manual i didn't see any remarks about psycopg. There is only psycopg2 https://docs.djangoproject.com/en/3.2/ref/settings/#std-setting-DATABASES I tried to migrate my project from sqlite to postgres 9 -
Django Creation View Doesn't save any data
My creation view redirect to blog main page well after creation but i can't find any post's been created in the posts or admin page posts, can anyone help please here is my view @login_required def add_post(request): if request.method == 'POST': post_form = PostForm(request.POST, request.FILES, instance=request.user) snippet_form = SnippetForm(request.POST) if post_form.is_valid() and snippet_form.is_valid(): post = post_form.save(commit=False) snpt = snippet_form.save(commit=False) post.creator = request.user snpt.id = post.id post.save() and snpt.save() return redirect('blog:index') else: post_form = PostForm() snippet_form = SnippetForm() return render(request, 'blog/add_post.html', {'post': post_form, 'snpt': snippet_form}) what's wrong in this view cause i been able to save new post from admin add new post but from client it doesn't save anything Do I need to use model create() method here or what? *Any required snippet i will provide but the problem is in this snippet any help is really appreciable -
Multiple models and multiple serializer in single response in DRF
I'm creating a search functionality that returns all model fields like - users, posts, hashtags, images, and videos. I'm trying to create multiple queryset with their multiple serializers to return in a single response. this is my expected response result. { searchresults{ posts[ ],images[ ],videos[ ],user[ ] } } I tried many methods to do this, but the response was unsuccessful. I also tried that one but that required relationship. class HashTagResponseSerializer(serializers.ModelSerializer): class Meta: model = HashtagName fields = ["hashtag",] def get_hashtag(self, obj): ... class UserFollowSerializer(serializers.ModelSerializer): hashtag = HashTagResponseSerializer(many=True, read_only=True) class Meta: model = User fields = ['user_uuid', 'post_language', "username", "display_name", "profile_picture", "hashtag "]