Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why obj.save() in django return 'none' even after data is saved in database
contact.save() is triggered and data is also saved in database ,but it return none after saving. Anyone explain. I just want display success or error message for the operation. As it return none it jumps to else block. You can see the output 'none' as i print the contact.save() object. -
python manage.py collect static not working. Raises a 'utf-8' codec can't decode byte 0xff issue
Hi guys so i have been trying to deploy my django application to heroku and i ran through a couple of issues. Below is some of the static setting that i have in my settings.py file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # this takes us to 'src/media/' not 'static/media' The 2 lines below generate the same error. python manage.py collectstatic heroku run python manage.py collectstatic The error for python manage.py collectstatic is (venv) nmj@pc-nm:~/PROJECTS/abc/b99/mysite/src$ python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /home/nmj/PROJECTS/abc/blueMust/mysite/src/staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "/home/nmj/PROJECTS/abc/blueMust/mysite/src/manage.py", line 22, in <module> main() File "/home/nmj/PROJECTS/abc/blueMust/mysite/src/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 128, in collect for original_path, processed_path, processed in processor: … -
How to give path for zip file to store at particular folder after done with zip in python3
zip file is storing directly into project directory, how to give the path. ZipFile = zipfile.ZipFile(f"{sentgroupid}.zip", "w" ) for zip_files in list_append: ZipFile.write(zip_files, compress_type=zipfile.ZIP_DEFLATED) ZipFile.close() -
Individual test function works, but chaining them get: "FOREIGN KEY constraint failed"
I can run individual test (by calling the function directly), but if I chain them, I've got an error when the Testing enters the next function (the first running fine). django.db.utils.IntegrityError: FOREIGN KEY constraint failed` (I can change the order of the functions, the error is still on the second one). tests.py class MainPage_testing(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(Text_read, cls).setUpClass() cls.pwd = 'selenium20!!!' cls.user_1 = UserFactory(password=cls.pwd) cls.selenium = WebDriver() cls.selenium.get('{}'.format(cls.live_server_url)) cls.find(By.NAME, 'login').send_keys(cls.user_1.username) cls.find(By.NAME, 'password').send_keys(cls.pwd) cls.find(By.CSS_SELECTOR, "button[type='submit']").click() def test_Create_a_post(self): text = TextsFactory(owner=self.user_1) ... def test_Create_a_comment(self): text2 = TextsFactory(owner=self.user_1) # <-- Triggers the error ... I can run test_Create_a_comment, but if I run the entire test class MainPage_testing, the error appears at the line: text2 = TextsFactory(owner=self.user_1) django.db.utils.IntegrityError: FOREIGN KEY constraint failed` -
How to make a text Bold in Django Administration
Is there a way to make a text bold or e.g. bold in Django Administration. Let's say I have a text field with this Lorum Ipsum text and i want the second word of the sentence to be bold and/or cursive (just like here): Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. -
MultiValueDictKeyError at /search/ when using post request in django
I am Unable to get query, which user is searching for from a POST request Template file <!-- search bar --> <form action="{% url 'search' %}" method="post">{% csrf_token %} <div class="container py-3 row"> <div class="col-md-8 offset-2"> <div class="input-group"> <input name="searchfieldText" type="text" class="form-control" placeholder="Search"> <button class="btn btn-danger" type="submit">Search</button> </div> </div> </div> </form> urls.py ...... path('search/', views.search,name='search'), ..... views.py def search(request): usr_qry= request.POST['searchfieldText'] print(usr_qry) # and some more code which is irrelavent to paste here ..... Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/search/?searchfieldText=window Django Version: 3.2.2 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App_wfi_Community', 'django.contrib.humanize', 'askQuestion', 'authentiCation'] Installed 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'] Traceback (most recent call last): File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('searchfieldText'), another exception occurred: File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\saurav\Documents\GitHub\WFI-Community\App_wfi_Community\decorators.py", line 7, in wrapper_func return func_arg(request, *args, **kwargs) File "C:\Users\saurav\Documents\GitHub\WFI-Community\App_wfi_Community\views.py", line 178, in search usr_qry= request.POST['searchfieldText'] File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /search/ Exception Value: 'searchfieldText' i want to get user search query or whatever user is searching for.. … -
" Your requirements.txt is invalid. Snapshot your logs for details" at eb deploy
I just update my local pip ver to 21 and then I resolved dependencies conflicts. Just after this when I run eb deploy it showed error Your requirements.txt is invalid. Snapshot your logs for details. File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. What can I do to fix this? -
With Django, how to display User friendly names in the template using grouper?
My model offers a choice list: class Interview(models.Model): class InterviewStatus(models.Model): PENDING = '1-PDG' XED = '0-XED' DONE = '2-DON' COMPLETE = '3-COM' ITW_STATUS = [ (PENDING, "Interview Planned"), (XED, "Interview Cancelled"), (DONE, "Interview Done"), (COMPLETE, "Interview Done and Assessed") ] which is implemented in the model fields: status = models.CharField(max_length=5, blank=False, null=False, default=InterviewStatus.PENDING, choices=InterviewStatus.ITW_STATUS, verbose_name="Statut de l'interview") When creating a new object, everything is OK. My template is written as such : {% regroup object_list by status as status_list %} <h1 id="topic-list">Interview List</h1> <ul> {% for status in status_list %} <li><h2>{{ status.grouper }}</h2></li> <ul> {% for interview in status.list %} <li><a href="{{ interview.get_absolute_url }}">{{ interview.official }}{{ interview.date_effective }} </a></li> {% endfor %} </ul> What I get as an outcome in my browser is: . 1-PDG item1 item2 etc. My Question is: How could I obtain the User friendly names instead of the values, which are supposed to be displayed exclusively in the html field: <option value="1-PDG" selected>Interview Planned</option> -
How can i send post request from one django project to another django project?
I have two different projects, inwhich i want to call post request and send the data from one django project to another django project. -
Need guidance on Django Rest API development
I have currently developed an application using Django Rest framework. React is chosen as the front-end for the app. The API endpoints developed needs to be checked/reviewed to ensure correctness before reaching out to the Front-end. Also, a code review is required to ensure a correct programming methodology. Thanks -
wrong URL configuration/pattern in django
In django template, to call url for a link this is what I have done {% for url in request.session.url %} <a href="{{url.linkfield}}" > {{url.name}} </a> {% endfor %} With the above when I load the page the links comes out very well as expected. e.g. www.url.com/ for home www.url.com/staff/firstpage for firstpage www.url.com/staff/secondpage for secondpage etc But when I click on any of the links it would extend the link of the existing page e.g. clicking on firstpage with link www.url.com/staff/firstpage result turns out to be e.g. www.url.com/staff/firstpage for home www.url.com/staff/firstpage/firstpage for firstpage www.url.com/staff/firstpage/secondpage for secondpage etc This is my url.py app_name="application_name" urlpatterns=[ url(r"^staff/",include('application_name.staff_url', namespace='staff')), url(r"^customer/",include('application_name.customer_url', namespace='customer')), ] my staff_url.py from application_name import views app_name="staff" urlpatterns=[ url(r"^customers/",views.customers, name='customers'), url(r"^orders/$", views.orders, name='orders'), url(r"^payments/$", views.payments, name='payments'), ] but when I use {% url %} i.e. instead of {{linkfield}} i am using {% url url.linkfield %} it is producing error in the console i.e. raise NoReverseMatch(msg) dango.urls.exceptions.NoReverseMatch: Reverse for 'whatever_linkname' not found. 'whatever_linkname' is not a valid view function or pattern name. This is my url.py app_name="application_name" urlpatterns=[ url(r"^staff/",include('application_name.staff_url', namespace='staff')), url(r"^customer/",include('application_name.customer_url', namespace='customer')), ] my staff_url.py from application_name import views app_name="staff" urlpatterns=[ url(r"^customers/",views.customers, name='customers'), url(r"^orders/$", views.orders, name='orders'), url(r"^payments/$", views.payments, name='payments'), ] my customer_url.py from … -
keep the data in the input box after submitting form in Django
I have used Django2 to develop a web app. After submitting the form, I want to keep the data in the the form in the frontend. HTML: <form id="myform" action="/content_checklist_name_url/" method="POST" onsubmit="return confirm('Do you want to confirm entries?');"> {% csrf_token %} <label> Discipline:</label> <select id="discipline" name="discipline"> <option value="" selected disabled hidden>--Select--</option> {% for discipline in query_results %} <option value="{{ discipline.id }}">{{ discipline.code }}</option> {% endfor %} </select><br> <label for="name_1"> Discipline Code(e.g. ACC): </label> <input type="text" id="name_1" name="name_1" onkeyup="this.value = this.value.toUpperCase();" ><br> <label for="name_2"> Course Code(e.g. 201): </label> <input type="text" id="name_2" name="course_code" onkeypress='validate(event)'><br> <label for="name_3"> Course Title: </label> <input type="text" id="name_3" name="course_title" ><br> <label> Postgraduate Course: </label> <select id="postgraduate_course" name="postgraduate_course"> <option value="">--Select--</option> <option value="Yes">Yes</option> <option value="No">No</option> </select><br> <label> First Presenting Semester: </label> <select id="semester" name="semester"> <option value="">--Select--</option> {% for semester in query_results_2 %} <option value="{{ semester.id }}">{{ semester.slug }}</option> {% endfor %} </select><br> <!--label> First Presenting Year: </label> <select id="year" > <option value="">--Select--</option> <option value="Dropdown_2021">2021</option> <option value="Dropdown_2022">2022</option> </select><br--> <label> Term: </label> <select id="term" > <option value="">--Select--</option> <option value="Dropdown_1">1</option> <option value="Dropdown_2">2</option> </select><br> <label> Presentation pattern: </label> <select id="Presentation_pattern" name="Presentation_pattern"> <option value="">--Select--</option> <option value="Every_Semester">EVERY SEMESTER</option> <option value="Every_January">EVERY JAN</option> <option value="Every_July">EVERY JUL</option> </select><br> <label> Course Type: </label> <!--select id="type" name="type" > <option value="">--Select--</option> {% … -
djagno use multiple widgets in form field
I'm trying to use two widgets (one to add custom class names, one for the choices) in one field, but not sure how.. there's no clear way specified in the official documentation to do this widget=forms.TextInput(attrs={'class': 'select is-medium'}) widget=forms.Select -
How to update a queryset to include User's full name
Currently in my project I use the following code to obtain a list of Users: all_manager = User.objects.filter(id__in=manager_list).values( "id", "first_name", "last_name" ) For the User model there is no field called 'full_name' or something similar. I read the official documentation and there is a method get_full_name() The question is: How can I modify the queryset to include a 'full_name' key with its value? Dummy Queryset: <QuerySet [{'id': 1, 'first_name': 'Steve', 'last_name': 'Jobs'}, {'id': 3, 'first_name': 'Tim', 'last_name': 'Cook'}]> Desired Queryset: <QuerySet [{'id': 1, 'first_name': 'Steve', 'last_name': 'Jobs', 'full_name': 'Steve Jobs'}, {'id': 3, 'first_name': 'Tim', 'last_name': 'Cook', 'full_name': 'Tim Cook'}]> -
want to show the specific data of opened Accordion in a modal for update operation using Django
here simply I just want to perform an update operation. the data (basically a set of questions from views.py ), and each question is shown in form of a bootstrap accordion. the scenario I want is when we open the accordion, there is a modal toggle button for update the data, and when the button pressed it opens the modal which contains the question of that particular opened accordion which allows the user to update that data. The problem is that in the current code when I click the model button of the 1st question it displays the 1st question data(means work fine) but when I click the 2nd accordion modal button (which contains different question) show the data of the 1st question means 1st accordion data. I can't figure out how to get the desired output means opening the model of a specific accordion should display the data of the particular accordion so that we can perform an update operation. here is my template file {% extends 'base.html' %} {% block title %}Add Questions{% endblock title %} {% block body %} <body> <label for=""><h4 style="color: indianred">Grade >> {{classname}} >> {{topicname}} >> {{subtopicnames}} </h4></label><br> <br> <br> <br> </div> </form> <div … -
Django Celery can't connect to Heroku Redis
Can someone help me to fixed this error, Im trying to used for the first time Django Celery + Heroku Redis but I got an error when I run " celery -A (project) worker -l info". Thank you Im using : redis==3.5.3, Django==2.1.7, python==3.7.7, celery==5.0.5 This is the error: ERROR/MainProcess] consumer: Cannot connect to redis://:**@ec2-3-213-108-16.compute-1.amazonaws.com:18480//: Error while reading from socket: (54, 'Connection reset by peer'). Trying again in 2.00 seconds... (1/100) Setting -
How to use prefetch_related and select_related at the same time in Django?
This is a part of models.py in my django app. class User(models.Model): user_id = models.AutoField(primary_key=True) uuid = models.CharField(max_length=32) name = models.CharField(max_length=10) phone = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class UserForm(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) access_info = models.CharField(max_length=250) etc_comment = models.CharField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class UserAddress(models.Model): user_address_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) address_name = models.CharField(max_length=100) address_name_detail = models.CharField(max_length=100) address_type = models.CharField(max_length=11) address_coord = models.PointField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I am using MySQL database and linked it to django database. My question is how to get all three data together just in a single query. As I know, I have to use django's prefetch_related or select_related method to get them together like this objs = User.objects.select_related('userform').get(user_id=1) But, what about getting them from three model classes? Please, let me know if you have any idea. -
Convert SQL Query to Django ORM
I am new to Django ORM and am struggling to convert the following query into ORM. Appreciate any help/guidance. The dates/times are not in a particular order. Thanks in advance SQL Query: ''' SELECT A.Person_id, A.Dept_id, A.score_date, A.score FROM borrowerdeptscore AS A INNER JOIN ( SELECT Person_id, Dept_id, MAX(score_date) AS Max_date FROM borrowerdeptscore GROUP BY Person_id, Dept_id ) AS B ON A.Person_id = B.Person_id AND A.Dept_id = B.Dept_id AND A.score_date = B.Max_date ''' The Django Class: ''' class BorrowerDeptScore (models.Model): Person= models.ForeignKey('Person') Dept= models.ForeignKey('Dept') score_date = models.DateTimeField()<br/> score = models.DecimalField()<br/> ''' The closest I got to an answer was the following, however I cannot add the "score" to the queryset. Not sure what I am missing or forgot here. latestscores = BorrowerDeptScore .objects.values('Person_id', 'Dept_id').annotate(max_date=Max('score_date')) -
Combined Returns in Python Function Based Views Django
I'm currently building a website with Django and I've gotten to a point where I need to print data on the screen(ListView) and update(UpdateView) data on the same page(template). From what I've found I cant do this easily with the Django generic views so I rewrote my view as a function-based view. This current piece of code updates what I need perfectly with some changes to the HTML. def DocPostNewView(request, pk): context = {} obj = get_object_or_404(DocPost, id=pk) form = GeeksForm(request.POST or None, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect("/" + id) context["form"] = form posts = DocPost.objects.all() return render(request, "my_app/use_template.html", context) ... And this following piece of code lists objects perfectly with some changes to the HTML. def DocPostNewView(request, pk): context = {} obj = get_object_or_404(DocPost, id=pk) form = GeeksForm(request.POST or None, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect("/" + id) context["form"] = form posts = DocPost.objects.all() return render(request, 'my_app/use_template.html', context={'posts': posts}) I just need to combine these and the only real difference is the return command at the bottom of both(the same) functions. HOW CAN I COMBINE THE RETURNS SO I CAN LIST DATA AND UPDATE DATA ON THE SAME PAGE??? Thanks -
How to escape MultipleObjectsReturned with django-import-export in django
Based on this here that was sufficiently answered and which helped me improve a lot, I have a problem getting the system to detect the streams in a particular klass. When I upload, if there are same stream names in different classes for the same school, the system returns MultipleObjectsReturned. When I reduce[edit] the streams so that it is 1 different stream name for every class, it works. How can I enable it to take in uploaded data whereby it is the same school with classes and the classes being 4 have the same name for their streams, i.e Form 1 has streams Eagle and Hawk, Form 2 has streams Eagle, Hawk, and same for Forms 3 and 4???? Any help will be highly appreciated. Here are the models, resources and views. Resources.py class KlassForeignKeyWidget(ForeignKeyWidget): def __init__(self,school_id,model = 'Klass',field="name",*args,**kwargs,): super().__init__(model=model, field=field, *args, **kwargs) self.school_id = school_id def get_queryset(self, value, row, *args, **kwargs): return Klass.objects.filter(school_id=self.school_id) class StreamForeignKeyWidget(ForeignKeyWidget): def __init__(self,school_id,model = 'Stream',field="name",*args,**kwargs,): super().__init__(model=model, field=field, *args, **kwargs) self.school_id = school_id def get_queryset(self, value, row, *args, **kwargs): return Stream.objects.filter(klass__school_id=self.school_id) class ImportStudentsResource(resources.ModelResource): def __init__(self, school_id,*args, **kwargs): super().__init__() self.school_id = school_id self.fields["klass"] = fields.Field(attribute="klass",column_name="class",widget=KlassForeignKeyWidget(school_id,),) self.fields["stream"] = fields.Field(attribute="stream",column_name="stream",widget=StreamForeignKeyWidget(school_id,),) def before_save_instance(self, instance, using_transactions, dry_run): instance.school_id = self.school_id class … -
Django 404 error even though I've created the path and view
I'm just beginning to learn Django. I've created a simple web sub-app called 'flavo' inside of another one called 'djangoTest' When I run http://127.0.0.1:8000/flavo it correctly displays Hello, World! then when I run http://127.0.0.1:8000/flavo/a it should show Hello, a! But instead I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/flavo/a Using the URLconf defined in testDjango.urls, Django tried these URL patterns, in this order: admin/ flavo [name='index0'] flavo a [name='a'] The current path, flavo/a, didn’t match any of these. in testDjango/hello/views.py I have from django.http import HttpResponse from django.shortcuts import render def index0(request): return HttpResponse("Hello, world!") def a(request): return HttpResponse("Hello, a!") In testDjango/flavo/url/py I have from django.urls import path from . import views urlpatterns = [ path("", views.index0, name="index0"), path("a", views.a, name="a"), ] The only other file I've changed is , testDjango/testDjango/urls.py" from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('flavo', include("flavo.urls")), ] I'm confused why I can't access http://127.0.0.1:8000/flavo/a -
Djano. Getting "ConnectionRefusedError: [Errno 111" when trying to send an email
Description I am trying to send an email using django.core.mail.send_email() and constantly getting the ConnectionRefusedError: [Errno 111] Connection refused with the following traceback: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/EmilKadermetov/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/EmilKadermetov/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/EmilKadermetov/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/EmilKadermetov/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.8/smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.8/socket.py", line 807, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused My SMTP configurations in the settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOSTS = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my_email@gmail.com' EMAIL_HOST_PASSWORD = 'my_passwod' Additional "Less security app access" in my google account is turned on. I can successfully connect to the smtp.gmail.com via telnet from the same machine. Using another smtp host changes nothing. I use: Django3.1.6 | Python 3.8.5 | Linux Mint 20.1 -
Sending Mail configuration in django
I am facing a problem when trying to test sending a message from the django app, but I get this error message : SMTPAuthenticationError at /accounts/contact_us (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f13sm16175910wrt.86 - gsmtp') And I looked for all the possible solutions like : Enable two-step verification , Enable less secure app access settings . But it was in vain and did not work successfully. Could anyone help please ? this is my settings : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myname@gmail.com' EMAIL_HOST_PASSWORD = '****************' EMAIL_USE_TLS = True EMAIL_PORT = '587' this is my views.py: def contact_us(requset): subject = requset.POST.get('subject', '') message = requset.POST.get('message', '') from_email = requset.POST.get('from_email', '') send_mail(subject, message, from_email, ['myname@gmail.com']) return render( requset , 'accounts/contact_us.html' ) this is my contact_us.html: <div class="contact_form"> <form name="contact_form" action="" method="POST"> {% csrf_token %} <p><input type="text" name="subject" class="name" placeholder="subject" required></p> <p><textarea name="message" class="message" placeholder="message" required></textare></p> <p><input type="text" name="from_email" class="email" placeholder="email" required></p> <p><input type="submit" value="sent" class="submit_btn"></p> </form> </div> -
How to return access token to frontend after socialAuth in django
I have implemented social auth using django social auth. Now I need to return the access token to frontend(react), so that I can pass it in further requests and identify the user. I tried modifying the LoginView, but it didn't work as expected. Can someone suggest a way for this? urls.py url(r'^login/$', auth_views.LoginView.as_view(), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^oauth/', include('social_django.urls', namespace='social')), path('', include('testapp.urls')), I have not made any changes to the social_auth pipeline. -
How do I reverse One To Many (ForeignKey) relation?
I have two models File and Shared, I want to add many collaborators to one File not one collaborators to many File, here are my models: class File(models.Model): slug = models.SlugField(primary_key=True) file = models.FileField(upload_to=upload_file_to) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) collaborators = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) class Shared(models.Model): file = models.ForeignKey('File', on_delete=models.CASCADE) code = models.CharField(max_length=15, unique=True)