Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
<script src="https://js.stripe.com/v3/"></script> stripe submit button not working in django
html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ transaction_id }} Payments setup</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} <style> .bill-details-container { height: fit-content; padding: 1rm; } tr { border-bottom: 1px solid gray; } </style> <script src="https://js.stripe.com/v3/"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12 text-center"> <h1>Order details</h1> <hr> </div> <div class="col text-center mt-3"> <div class="row"> <div class="col"> <h5 class="fw-bold" style="color: #404145;">{{ package_name }}</h5> </div> <div class="col"> <h5 class="fw-ligh" style="color: #404145;">₹{{ actual_price }}</h5> </div> <div class="col-md-12"> <p>{{ package_discription }}</p> </div> </div> <div class="row"> <div class="col" style="background-color: #f5f5f5;"> <center> <div class="bill-details-container col"> <table width="100%"> <tr> <td style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Service fee</td> <td style="text-align: left; padding-top: 10px; padding-bottom: 10px;"> {{ service_fee }}</td> </tr> <tr> <td style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Package payment</td> <td style="text-align: left; padding-top: 10px; padding-bottom: 10px;">{{ actual_price }}</td> </tr> <tr> <td class="fw-bold" style="text-align: center; padding-top: 10px; padding-bottom: 10px;">Total payment</td> <td class="fw-bold" style="text-align: left; padding-top: 10px; padding-bottom: 10px;"> {{ actual_price_fee_added }} </td> </tr> </table> </div> </center> </div> <div class="col-md-12 mt-3"> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-6"> <div class="card"> <div class="card-header"> Payment Information </div> <div class="card-body"> <form action="{% url 'success' transaction_id request.user.username %}" id="payment-form"> <div id="card-element"> </div> <script> … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect:VSCode Terminal Python Interpretter - Miniconda environment
I am on Windows 10 OS, using VSCode, Miniconda environment with python 3.10 and django 4.1. I encountered the following error after installing an VSCode extension to view .xlsx files in VSCode. I uninstalled it since it did not work. The problems started after this. The following error displays in VSCode Python Interpreter virtual environment enabled terminal after typing in command: conda env list Also, no other 'conda' commands work without '--no-plugins' option. The highlighted text in below block is the error message: ERROR REPORT <<<<<<<<<<<<<<<<<<<<<< Traceback (most recent call last): File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\exception_handler.py", line 17, in __call__ return func(*args, **kwargs) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\main.py", line 54, in main_subshell parser = generate_parser(add_help=True) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\conda_argparse.py", line 127, in generate_parser configure_parser_plugins(sub_parsers) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\conda_argparse.py", line 354, in configure_parser_plugins else set(find_commands()).difference(plugin_subcommands) File "C:\Users\jkcod\miniconda3\lib\site-packages\conda\cli\find_commands.py", line 71, in find_commands for entry in os.scandir(dir_path): **> OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\jkcod\\AppData\\Local\\Programs\\Microsoft VS Code\\binC:\\Program Files\\Python310\\Scripts\\'** C:\Users\jkcod\miniconda3\Scripts\conda-script.py env list` environment variables: CIO_TEST=<not set> CONDA_DEFAULT_ENV=base CONDA_EXE=C:\Users\jkcod\miniconda3\condabin\..\Scripts\conda.exe CONDA_EXES="C:\Users\jkcod\miniconda3\condabin\..\Scripts\conda.exe" CONDA_PREFIX=C:\Users\jkcod\miniconda3 CONDA_PROMPT_MODIFIER=(base) CONDA_PYTHON_EXE=C:\Users\jkcod\miniconda3\python.exe CONDA_ROOT=C:\Users\jkcod\miniconda3 CONDA_SHLVL=1 CURL_CA_BUNDLE=<not set> HOMEPATH=\Users\jkcod LD_PRELOAD=<not set> PATH=C:\Users\jkcod\miniconda3;C:\Users\jkcod\miniconda3\Library\mingw- w64\bin;C:\Users\jkcod\miniconda3\Library\usr\bin;C:\Users\jkcod\minic onda3\Library\bin;C:\Users\jkcod\miniconda3\Scripts;C:\Users\jkcod\min iconda3\bin;C:\Users\jkcod\miniconda3\condabin;C:\Program Files\Python310\Scripts;C:\Program Files\Python310;C:\Program Files\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows ;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C :\Windows\System32\OpenSSH;C:\Program Files\Java\jdk-17.0.1\bin;C:\Program Files\Git\cmd;C:\Users\jkcod\AppD ata\Local\Microsoft\WindowsApps;C:\Users\jkcod\AppData\Local\Programs\ Microsoft VS Code\binC:\Program Files\Python310\Scripts\;C:\Program Files\Python310\;C:\Program Files\Common Files\Oracle\Java\javapath;C: \Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\Syste m32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;%JAVA_HOME%\b in;C:\Program Files\Git\cmd;C:\Users\jkcod\AppData\Local\Microsoft\Win dowsApps;C:\Users\jkcod\AppData\Local\Programs\Microsoft VS Code\bin PSMODULEPATH=C:\Program … -
Why when view returns a list of objects from db html file didn't pick the value
def index(request): context = get_all_tasks() return render(request, 'sentixplorerapp/index.html',context) above is my view function when I return this to below html code snippet it return the accepted outcome. {% extends 'sentixplorerapp/base.html' %} {% block content %} <table border="1" style="width: 80%;" class="table table-striped"> <thead> <tr> <th>Id</th> <th>Task Name</th> <th>File Path</th> <th>Result</th> </tr> </thead> <tbody> {% for task in tasks %} <tr> <td>{{ task.id }}</td> <td>{{ task.taskName }}</td> <td>{{ task.filepath }}</td> <td>{{ task.result }}</td> </tr> {% endfor %} <!-- You can add more rows as needed --> </tbody> </table> {% endblock %} but when I change my view function as below It didn't get any values to html view. Can you help me to understand why? def index(request): context = {'tasks': get_all_tasks()} return render(request, 'sentixplorerapp/index.html',context) I'm expecting to get table data that return from get_all_task() view in html when it look like this, def index(request): context = {'tasks': get_all_tasks()} return render(request, 'sentixplorerapp/index.html',context) -
How to make Django tree view
html {% for acc in accs %} <ul class="tree" id="tree"> <li> <details> <summary>{{acc.acc_id1}} {{acc.E_name1}} </summary> <ul> <details> <summary> {{acc.acc_id2}} {{acc.E_name2}}</summary> <ul> <details> <summary>{{acc.acc_id3}} {{acc.E_name3}}</summary> <ul> <li>{{acc.acc_id4}} {{acc.E_name4}}</li> </ul> </details> </ul> </details> </ul> </details> </li> </ul> {% endfor %} models.py from django.db import models class Mainacc (models.Model): acc_id1 = models.IntegerField(unique=True) E_name1 = models.CharField(max_length=10) A_name1 = models.CharField(max_length=10) def __str__(self): return f'{self.acc_id1} {self.E_name1}' class Aacc (models.Model): acc_id1 = models.ForeignKey(Mainacc, on_delete = models.CASCADE) acc_id2 = models.IntegerField( db_index=True, unique=True) E_name2 = models.CharField(max_length=50) A_name2 = models.CharField(max_length=50) def __str__(self): return f' {self.acc_id2} {self.E_name2}' class Bacc (models.Model): acc_id2 = models.ForeignKey(Aacc, on_delete =models.CASCADE) acc_id3 = models.IntegerField( db_index=True, unique=True) E_name3 = models.CharField(max_length=100) A_name3 = models.CharField(max_length=100) def __str__(self): return f' {self.acc_id3} {self.E_name3}' class Cacc (models.Model): acc_id3 = models.ForeignKey(Bacc, on_delete=models.CASCADE) acc_id4 = models.BigIntegerField( db_index=True, unique=True) E_name4 = models.CharField(max_length=100) A_name4 = models.CharField(max_length=100) def __str__(self): return f' {self.acc_id4} {self.E_name4}' views.py def Acc(request): mainacc_list = Mainacc.objects.all() aacc_list = Aacc.objects.all() bacc_list = Bacc.objects.all() cacc_list = Cacc.objects.all() acc_list = list(chain(mainacc_list, aacc_list,bacc_list,cacc_list)) return render (request,'templates\\acc\\acc.html',{'accs':acc_list}) -
Deploy Django with TailwindCSS on Elastic Beanstalk
Good day, I recently deployed a Django project to Elastic Beanstalk using the following tutorial: https://testdriven.io/blog/django-elastic-beanstalk/ This is the website: http://gmoonline4-dev.us-east-1.elasticbeanstalk.com/ The website works fine, including the admin and database, except for the CSS, which gives an error This template loads properly in development, but you can see the end product after deployment. I tried including the container_command "python3 manage.py tailwind start", but this fails the deployment. Can anyone assist me with this? I am not sure if this is an error in my django application or my EB configuration. Thanks! If you need any code, I'll post it here -
why i get None instead of the model id in django ImageField path
When attempting to add a new event through the Django admin panel, the image is incorrectly being stored at the path "media/events/None/poster/file.png" instead of the intended path "media/events/{instance.id}/poster/file.png." I have added a print(...) statement to the get_poster_image_path function for testing purposes. : def get_poster_image_path(instance, filename): print(f""" from get_poster_image_path ==================\n type :{type(instance)}\n instance :{instance}\n instance.id :{instance.id}\n instance.name :{instance.name} """) return f'events/{instance.id}/poster/{filename}' class Event(models.Model): name = models.CharField(max_length=50) poster = models.ImageField(upload_to=get_poster_image_path,null=True,blank=True) .... the result: from get_poster_image_path ============================= type :<class 'events.models.Event'> instance :myevent instance.id :None instance.name :myevent -
Custom Session backend for Django using firestore
We are tryng to create a custom backend session engine using firestore. The autentication methodology is FireBase Auth. We have created the following code for the custom session and while we are abl to create collections in Firestore , data with session_key and uid is not being written to docs in the collection. We are hoping to eliminate the use of SQLite or any other sql for production -
python: can't open file '/Users/hillarytembo/Desktop/studybudy/manage.py': [Errno 2] No such file or directory
I made this command “python manage.py runserver” I got this error “ python: can't open file '/Users/hillarytembo/Desktop/studybudy/manage.py': [Errno 2] No such file or directory” how can i fix this I tried to check if the file was there and I found the file was there -
get_absolute_url does not work in my django app
in my django app, i have used get_absolute_url in model. from django.db import models from django.urls import reverse class nm(models.Model): name = models.CharField(max_length=50) no = models.IntegerField() def __str__(self): return f"\n{self.name}|{self.no}\n" def get_absolute_url(self): return reverse("number-str-url", args=[self.name]) but in django template when i want to link that, it does not work {% extends "base.html" %} {% block title %}Numbers{% endblock title %} {% block content %} <ul> {% for number in numbers %} <li><a href="{{number.get_absolute_url}}">{{number|title}}</a></li> {% endfor %} </ul> {% endblock content %} i want to show list of numbers one, two, three, four and five. when user clicks on one of them, the link navigate user to dedicated page of the number. something like this: One Two Three Four Five -
Django Python+Ajax : how to update variable from frontend to back end? My ajax function isn't working
When the user submits this form I want to save the rgb color code as a variable to be stored on the back end (using django), so whenever the card is loaded (the colour picked on this page) will be loaded. I asked GPT, which suggested using ajax (I've never used it before). This is a snippet from my js : function updateSetColor(color) { console.log(color); $.ajax({ type: "POST", url: "/Flashcard/", beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken")); }, data: { color: color }, error: function(error) { console.log("Error updating color"); }, cache: false, }); } This is a snippet from my view that uses the color variable sent from the data : def flashcard(request): form = Flashcard_verif(request.POST) if request.method == "POST" and form.is_valid() and request.accepts('main/Flashcard.html'): print(request.POST) color = request.POST.get("color") # Get the color from the AJAX request print(color) As you can see I've got the console to output the color picked by the user and on the backend I've got the server to output the color that should've been recieved. The output from the console is correct but the output from the server is 'None'. I suspect its due to the ajax function. Any help would be appreciated or new ways of … -
Django Serializer with Many To Many fileld returns empty list, How to fix it?
I have two models Product and Lessons. I join them in one Product serializer. But I get empty list in lesson fileld. This is what I am getting now: { "id": 1, "name": "Python", "owner": 1, "lessons": [] # here should be lessons }, my modelds.py class Product(models.Model): name = models.CharField(max_length=250) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Lesson(models.Model): name = models.CharField(max_length=255) video_link = models.URLField() duration = models.PositiveIntegerField() products = models.ManyToManyField(Product, related_name='lessons') My serializers.py class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ('id', 'name', 'video_link', 'duration') class ProductSerializer(serializers.ModelSerializer): lessons = LessonSerializer(read_only=True, many=True) class Meta: model = Product fields = ['id', 'name', 'owner', 'lessons'] And my view.py class LessonListView(ListAPIView): serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): lesson_view = Product.objects.all() return products_view I can see many topics in the internet about that but I it is not working for me at all. How can I resolve it and get my data that I have for lessons field ? -
Django: How to enable app usage for different societies
I have a django project that has many apps. There is a core app that has all the main models that other secondary apps will use. One model in the core app is called SocietyEntity: class SocietyEntity(models.Model): id = models.AutoField(primary_key=True) referenceName = models.CharField(max_length=200, verbose_name="Nombre") members = models.ManyToManyField(get_user_model()) administrator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name="Administrator") As shown, the societies can have one o more users as members. What I want to achieve is some kind of relation between societies and the other secondary apps of the project, that enable that society to make use of the app. Something like a manytomany kind of relation between SocietyEntity and app names? I'm not sure but I think I need some way to relate societies to apps, if that is even possible. If a society doesn't have permission to use an app, this shouldn't be listed in the admin interface for example. Any suggestion is well received! Thanks -
Django Table2 reverse ManyTomany
Here is my models : class Appellation(models.Model): name = models.CharField(db_index=True, max_length=255) region = models.ForeignKey(Region, on_delete=models.CASCADE) class Ranking(models.Model): name = models.CharField(db_index=True, max_length=200) initials = models.CharField(db_index=True, max_length=10, blank=True, null=True) appellation = models.ManyToManyField(Appellation) In the Ranking Table, i arrived to have a column with all the appellation of a ranking : appellation = tables.ManyToManyColumn(lambda obj: format_html('<span class="badge py-3 px-4 fs-7 badge-light-primary">{}</span>', str(obj)), separator=' ') It's OK. No, i would like to have in the Appellation Table, a column with all the rankings of the appellation. Thanks you for your help. Regards -
Csrf token verification failing for admin form after using AbstractUser class in Deployement?
I am using Abstract User class for authentication in Django. Works fine on Localhost but when deployed the admin route is redirecting and csrf verification is failing with 403 Error. https://rallys.azurewebsites.net/admin/login/?next=/admin/ ALLOWED_HOSTS = ['*'] CSRF_TRUSTED_ORIGINS = ['https://rallys.azurewebsites.net'] AUTH_USER_MODEL = 'home.User' I have looked at modifying the Authenticate_user_model but the error persists. I noticed that the passwords field is no longer hashed in the admin panel on local host except for the SuperUser I created using CLI. -
How can I see the values of a ManyToMany field based on a Foreign key value in Django Admin Panel?
I am making a Django app for multiple choice question-answer exam. I have created a Subject, Question and Exam model as below. class Subject(models.Model): subject_name = models.CharField(max_length=200, blank=False) subject_code = models.IntegerField(blank=False) class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) question_name = models.CharField(max_length=200,null=True) class Exam(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) questions = models.ManyToManyField(Question) date_of_exam = models.DateField(blank=False) users = models.ManyToManyField(CustomUser) Here in Question I am connecting subject by Foreign Key relation. In Exam I have subject as Foreign key and questions as ManyToMany relation from Question model. I want to create exam from admin panel. I want that when I select a subject only the questions of that subject should be displayed in the manytomany field to select from (As questions have foreign key of subject I think it should be possible). (I want to do this from admin panel only and not from a template.) How can I achieve this? Any suggetion is very much appreciated. Thanks in advance for the suggestions!! :) -
What should I know before shifting from Django to Wagtail
I am python programmer ,I know how django works but I'm trying to move to Wagtail. I seem not to understand about how Wagtail works , it mixes Models with templates and I also find out that it doesn't use any views ,this goes against how django works. Can you please explain to me what is a Wagtail Page exactly. I know its sort of a model but I don't seem to understand how it works. I would also like to know how do I get to use Wagtail Pages to render different data depending on data in the database lets say images of Users in the database. Also ,do I have to create a Page for everything eg If I want to create a User Model or Profile Model ,does it have to be a Page also. Please Help. I tried to actually to use Wagtail docs to create a web app but I don't seem to be in control .Wagtail doesn't have an views so i don't know how i can handle the requests in my own way then send the response of my own ,lets say JSON data. -
FastAPI Endpoint List as parameter not working
I I want to create an endpoint that receives a list of strings, which will be called and used as assets in the endpoint function. The endpoint http://localhost:8000/api/v1/equipments works correctly. Debugging I have verified that enters in and executes perfectly the function. @equipments_router.get("/equipments", summary="Equipments data") def get_equipments(assets: List[str] = None, Authorization: str = Header(None)): However, I have seen that if I make a GET to http://localhost:8000/api/v1/equipments?assets=first&assets=second, the value of assets is None. I'm pretty sure that Authorization has no role to play in the problem. -
Sending Django Channels message from inside async_task
I am using Django-Q for some moderately long tasks and would like to send a message from within the task to an websocket connection that I have established with Django channels. I am able to send the message if the task is run synchronously, ie, by calling the function, or passing sync=True to async_task. I am relatively new to this, and was not able to find out why the message is never sent, when the task is being run asynchronously. Is this not possible to achieve, or what is it that I am missing? I am aware that I could use Celery for this, though I would prefer not to unless this cannot be done with Django-Q. Here is the setup: #views.py def testview(request, uuid): task_id = async_task(dummy_task, uuid) event_triger(uuid, task_id) # This message shows up. def event_triger(uuid, message): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( uuid, { 'type': 'send_message_to_frontend', 'message': message } ) def dummy_task(uuid): for i in range(3): event_triger(uuid, "") time.sleep(3) The consumers.py file has the following: class NotificationConsumer(WebsocketConsumer): def connect(self): self.uuid = self.scope["url_route"]["kwargs"]["uuid"] async_to_sync(self.channel_layer.group_add)( self.uuid, self.channel_name ) self.accept() self.send(text_data = json.dumps({ "type": "est", "msg": self.uuid, "channel": self.channel_name })) def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.uuid, self.channel_name ) print("DISCONNECED CODE: ",code) def send_message_to_frontend(self,event): … -
How to Set Responses Media Type to application/octet-stream in drf-spectacular?
I am currently using drf-spectacular for schema generation in my Django project. I need to set the media type of the responses to application/octet-stream in the @extend_schema decorator, but I am not sure how to do this. Could anyone provide guidance or examples on how to achieve this? Thank you in advance! paths: /file-download: get: summary: Download a file description: This API endpoint allows users to download a binary file. responses: '200': description: File downloaded successfully content: application/octet-stream: schema: type: string format: binary description: Binary file Looks like this -
Relation does not exist error when overriding get_queryset method of models.Manager
I have a model for storing music and it has last_queried_at field that is used for deleting the music object if not queried for a month. class CustomManager(models.Manager): use_in_migrations = True def get_queryset(self): queryset = super().get_queryset() queryset.update(last_queried_at=timezone.now()) return queryset class Music(models.Model): file = models.FileField(upload_to="music/") created_at = models.DateTimeField(auto_now_add=True) last_queried_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( User, models.SET_NULL, null=True, blank=True, related_name="music", ) objects = CustomManager() When I try to make migrations it throws an error django.db.utils.ProgrammingError: relation "app_music" does not exist LINE 1: UPDATE "app_music" SET "last_queried_at" = '2... I would appreciate if anyone could help me figure out how to solve this problem I tried to use django's makemigrations command and threw an error. I was expecting it to create migrations. -
Django - Site requested, but not rendered
I tied to create something with Django, but I currently suffer from a problem with the return statement. It doesn't work. Here is my code: ` def acc_settings(request): if request.method == "POST": # Extract JSON dictionary from request dict = json.loads(request.body.decode("utf-8")) if dict["request"] == "user_data_change": request.user.first_name = dict["firstname"] request.user.last_name = dict["lastname"] request.user.username = dict["email"] request.user.email = dict["email"] request.user.save() return redirect("/") if dict["request"] == "delete_account": print("Account deletion requested!") try: # Delete all models assigned to this user bgmodel = dashModels.diabetesData.objects.filter(user=helpers.key) profilemodel = models.userProfile.objects.filter(user=helpers.key) usermodel = User.objects.get(username = request.user.email) bgmodel.delete() profilemodel.delete() logout(request) usermodel.delete() return redirect("/") except: return redirect("/") if dict["request"] == "renew_keyfile": print("Keyfile will be renewed!") # Generate a new private key for the user key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096) uid = pgpy.PGPUID.new('{} {}'.format(request.user.first_name, request.user.last_name), email=request.user.email) key.add_uid(uid, usage={KeyFlags.Sign}, hashes=[HashAlgorithm.SHA256], ciphers=[SymmetricKeyAlgorithm.AES256], compression=[CompressionAlgorithm.Uncompressed], ) profilemodel = models.userProfile.objects.get(user=helpers.key) bgmodel = dashModels.diabetesData.objects.get(user=helpers.key) bgmodel.user = key profilemodel.user = key bgmodel.save() profilemodel.save() response = HttpResponse(key, content_type='multipart/signed') response['Content-Disposition'] = 'attachment; filename="new_key.asc"' logout(request) return response context = { "hostname": helpers.hostname, "firstname": request.user.first_name, "lastname": request.user.last_name, "email": request.user.email, } template = TemplateResponse(request, "settings.html", context) return template.render()` So, the 'return redirect("/")' does work, in the console I can see the request for my index site. But the index site is not rendered! Do you … -
there is error occur when i work with SQL
"The row in table 'flights_flight' with primary key '1' has an invalid foreign key: flights_flight.origin_id contains a value 'New York' that does not have a corresponding value in flights_airport.id. " how to solve this problem i try to migrate the table but does't work -
on Django admin panal DetailsView can I do CRUD Operation?
I have django admin panal custom page. where I am displaying report of models. I want to apply crud on the report itself, but I don't know how. class StudentView(DetailView): template_name = 'admin/Student/student/details.html' model = Student def get_context_data(self, **kwargs): student = super().get_context_data(**kwargs)['object'] address_details = AddressDetails.objects.filter(student=student) educations = Education.objects.filter(student=student) kwargs['educations'] = educations print(self.request) if self.request.method == "POST": action = self.request.POST.get('action', '') student_form = StudentUpdateForm(self.request.POST, instance=student) if student_form.is_valid(): student_form.save() return HttpResponseRedirect(reverse('student_detail', args=[student.pk])) return { **super().get_context_data(**kwargs), **admin.site.each_context(self.request), "opts": self.model._meta, } I tried this but it return 405 status code. -
SMTPServerDisconnected("Connection unexpectedly closed") on django
In my Django application, I'm trying to send emails via SMTP. This is my configuration in the settings: EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'your_email@gmail.com' EMAIL_HOST_PASSWORD = 'your_password' DEFAULT_FROM_EMAIL = 'your_email@gmail.com' However, I'm encountering an exception that says SMTPServerDisconnected("Connection unexpectedly closed"), and I'm not sure why. I've tried changing the backend and the port, but it still doesn't work. What could be causing this issue, and how can I resolve it? -
There is always that one celery worker process, can't use kill command because the PID is constantly changing
I'm in the process of developing a project and I'm working on implementing background tasks and notifications for user feedback. I'm using Django in conjunction with Celery for task management and Redis as a message broker. Currently, I can successfully execute background tasks, but I've encountered an issue when attempting to gracefully stop the Celery worker and exit Redis. Here's my terminal output: ps aux | grep 'celery worker' aysegul 2577 0.0 0.0 408102576 1072 s001 R+ 11:35AM 0:00.00 grep celery worker Then; sudo kill -9 2577 Password: kill: 2577: No such process Then I tried: celery -A request_handler.celery control shutdown Last command gave me connection errors caused by multiple sources: redis.exceptions.ConnectionError: Error 61 connecting to localhost:6379. Connection refused. I came across this command but it didn't work neither: ps auxww | grep 'celery worker' | awk '{print $2}' | xargs kill -9 kill: 2713: No such process I'm somewhat puzzled by this situation and wonder if this lingering process is necessary. I've even restarted my computer, yet the issue persists since yesterday. Could you kindly provide insight into the purpose of this lingering process and whether it's a matter that requires attention? Thank you.