Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model method isn't returning when called from one HTML template
class Food(models.Model): fdc_id = models.PositiveIntegerField(primary_key=True) def get_absolute_url(self): return reverse('food-detail', args=[str(self.fdc_id)]) models.py from django.urls import path from . import views, urls from django.urls import include urlpatterns = [ path('', views.index, name='index'), path('foods/', views.FoodListView.as_view(), name='foods'), path('foods/<int:pk>', views.FoodDetailView.as_view(), name='food-detail'), ] urlpatterns += [ path('myfoods/',views.FoodsEatenByUser.as_view(), name='my-eaten'), ] urls.py {% extends "base_generic.html" %} {% block content %} <h1>Food List</h1> {% if food_list %} <ul> {% for food in food_list %} <li> <a href="{{ food.get_absolute_url }}">{{ food.name }}</a> ({{food.fdc_id}}) </li> {% endfor %} <ul> {% else %} <p>There are no foods in the database</p> {% endif %} {% endblock %} food_list.html The food_list page appears how I expect it to but the url returned by get_absolute_url is /catalog/foods However, if I enter the url manually it will take me to the detail page for the object, where the method does return the correct url. {% extends 'base_generic.html' %} {% block content %} <h1>Food View</h1> <a href="{{ food.get_absolute_url }}">{{ food.name }}</a> ({{food.fdc_id}}) <p>{{ food.name}}</p> {% for f,v in food.get_fields %} <p> {{ f }}: {{ v }} </p> {% endfor %} {% endblock %} food_detail.html In food_detail, the url returned is /catalog/foods/<fdc_id> Also, the links on the list page did go to the correct detail page at … -
Why is the page I am testing returning a 301 response instead of a 200 response?
I am writing tests for class-based views in the django project I am writing as part of a course. Currently, I am stuck trying trying to test a view that directs to an edit page that requires a user to be logged in. The item being edited must also have been created by that user in the first place, of course. In the test itself, I instantiate a model and a user, and then log the user in, before trying to get the edit page. I expect the response to have a status code of 200, but it keeps coming back as a 301. Code below: urls.py - path for the edit page: path('edit/<slug:slug>/', views.EditBulletin.as_view(), name='edit'), models.py - the model being instantiated: class Bulletin(models.Model): title = models.CharField(max_length=40, unique=True) slug = models.SlugField(max_length=40, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bulletins') content = models.TextField() link = models.URLField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='bulletin_likes') edited = models.BooleanField(default=False) updated_on = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() views.py - the get method in the view for the edit page: class EditBulletin(View): def get(self, request, slug, *args, **kwargs): queryset = Bulletin.objects.filter(status=1) bulletin = get_object_or_404(queryset, slug=slug, … -
Django field ends up blank after save() AND code that prevents it from reverting to a blank value
A POST request hits one of my django GenericViewSet endpoint that find a matching instance and sets a value on it: obj = models.CarObj.objects.get(id=self.request.data['id']) if self.request.data.get('field_value',False): obj.field = self.request.data['field_value'] obj.save() this works like 95% of the time but occasionally I will catch an obj that has a blank field value after I KNOW that end point was hit correctly. So I changed my code to this: obj = models.CarObj.objects.get(id=self.request.data['id']) if self.request.data.get('field_value',False): obj.field = self.request.data['field_value'] obj.save() obj2 = models.CarObj.objects.get(id=obj.id) print("Mem: {} | DB: {}".format(obj.field, obj2.field)) if obj2.field == '' or len(obj2.field) == 0: raise ValueError("Mem does not match DB") The print always shows the same CORRECT values between the memory instance and the newest fetch from the DB. The ValueError is never raised. Yet sometimes field is still blank. So I went through the ModelViewSet of CarObj and made sure all the POST/ PATCH/ PUT all have: self.request.data.pop('field_value') before their respective serializers are populated with the self.request.data. Yet sometimes field is still blank. I have added a pre_save signal: @receiver(pre_save, sender=models.CarObj) def carobj_pre_save(sender, **kwargs): instance = kwargs.get('instance') if 'field' in instance.get_dirty_fields(check_relationship=True): field_new_value = getattr(instance,'field','') if field_new_value == '' or len(field_new_value) == 0: try: old_instance = models.CarObj.objects.get(id=instance.id) setattr(instance, 'field', getattr(old_instance, 'field', '')) … -
Permission api viewset for pub sub messages in Django
I want to create an action for this viewset that only can be triggered by our Google Cloud Pub Sub. class ObjectViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet, ): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] We have a separate endpoint that authorizes a request for only pub sub bearer_token = request.headers.get('Authorization') token = bearer_token.split(' ')[1] claim = id_token.verify_oauth2_token(token, transport.requests.Request(), audience=CLOUDRUN_SERVICE_URL) How can I add this logic to a Permissions class for a PATCH request? -
Making a follower count system in Python
I successfully made a post counter on my bassicly knock off twitter website i am building but I cant get the follower count to work. def get_context_data(self, **kwargs): user = self.get_object() context = super().get_context_data(**kwargs) context['total_posts'] = Post.objects.filter(author=user).count() context['total_followers'] = Follower.objects.filter(followed_by=id).count() if self.request.user.is_authenticated: context['you_follow'] = Follower.objects.filter(following=user, followed_by=self.request.user).exists() return context -
White spaces being added to text
I'm currently using a django char field in a model to store a url and then in the templates I do this: {% block url %} {% if object.url== '' %} {{ object.old_url}} {% else %} {{ object.url.strip }} {% endif %} {% end block url %} When i check it using inspect in chrome dev tools there are trailing and leading whitespaces for some reason even thought the "url" we enter has no whitespaces starting out? is their anyway to fix this? -
only get newest item of a type from queryset
Two models: class University(models.Model): name = models.CharField("name", max_length = 48) city = models.ForeignKey(City, on_delete = models.CASCADE) class Course(models.Model): name = models.CharField("course name", max_length = 48) university = models.ForeignKey(University, on_delete = models.CASCADE) students = models.ManyToManyField(Student, related_name = "%(class)s_name", related_query_name = "student_course_qs", blank = True) online = models.BooleanField("online course", default = False) semester = models.PositiveIntegerField("choose 1-6", default = 1, choices = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]) time_update = models.DateTimeField("last info update", auto_now = True) Restriction: If a Course has students, it cannot be online and vice versa. How would I obtain a list of all Courses on all Universities of a given city where the latest entry on Course has students and the Course is held in the 3rd semester? I tried it with a loop over the different groups of University but this results in a massive amount of queries: universities = University.objects.filter(city = City.objects.first()) wanted = [] for univ in universities: c = Course.objects.filter(university = univ).order_by("time_update").last() if c.semester == 3 and not c.online: wanted.append(c.id) selected_courses = Courses.objects.filter(id__in = wanted) The problem I see here is, that I create too many queries and just after the filter for universities they would already be grouped … -
login system issue not redirecting from register page to login page
i am creating a login system when a person create an account i want to redirect them to the login page but the user is still on the register page after they create their account my views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import * from .forms import OrderForm, CreateUserForm from .filters import OrderFilter def registerPage(request): if request.user.is_authenticated: return redirect('home') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form':form} return render(request, 'accounts/register.html', context) def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'accounts/login.html', context) **my urls.py** path('register/', views.register, name='register'), path('login/', views.login, name='login'),` i tried the redirect but it didn't worked -
How to Reduce Queries while Querying/Filtering GenericRelated Field Object
I have a Like model whose code looks like this: class Like(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) liked_on = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: unique_together = ('customer', 'content_type', 'object_id') indexes = [ models.Index(fields=["content_type", "object_id"]), ] def __str__(self): return f'{self.customer.user} likes {self.content_object}' This generic relation enables me to reuse the likes model for the CampusAD and PropertyAD models which both have a GenericRelation to the Likes model. In the PropertyADSerializer which feeds the endpoints, /api/properties and /api/properties/{property_id}, I have a SerializerMethodField which provides a boolean telling the front-end which properties have been liked by the current authenticated user (useful for showing a like icon on the page for users). The SerializerMethodField is defined as thus: def get_liked_by_authenticated_user(self, obj): request = self.context.get('request') if request and request.user.is_authenticated: customer = Customer.objects.get(user_id=request.user.id) content_type = ContentType.objects.get_for_model(PropertyAD) likes = Like.objects.filter( customer=customer, content_type=content_type, object_id=obj.id) return likes.exists() return False Now, the issue with this approach is that it makes calls to the Customer and ContentType tables to fetch the required Customer and PropertyAD objects before using them for filtering, and this happens for each PropertyAD on the page resulting in hundreds of calls to the database as shown in the debug toolbar … -
Order Lists in alphabetical order (OrderFilter) with condition that the entries with the values '' were at the end of the list DRF
Good afternoon Please tell me how to sort the data in alphabetical order in ascending order! But with the condition that the entries with the values "" were at the end of the list. Here is the part of the code that conveys the meaning - def order_by_custom_fields(self, ordering: list): result = [] request_status_empty_first = Case( When(request_status__exact='', then=0), default=1 ) for field in ('field'): if field in ordering: result.append(request_status_empty_first) return result def get_ordering(self, request, queryset, view): params = request.query_params.get(self.ordering_param) if params: fields = [param.strip() for param in params.split(',')] ordering = self.remove_invalid_fields(queryset, fields, view, request) else: ordering = [] ordering.extend(self.order_by_custom_fields(ordering)) return tuple( self.filters_custom_ordering(ordering) ) def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: return queryset.order_by(*ordering) return queryset This option displays records with '' at the very end, but the order is not alphabetical But it's necessary -
"The request's session was deleted before the request completed" on heavier requests
In my Django project I am frequently coming across the error: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. This happens across a number of views and because of a number of different processes within my website. I have noticed that this error occurs on heavier requests for my local server to process, such as loading more images or returning more data from the database when calling the view associated with the current page the user is requesting. This issue does get resolved when configuring the session engine in settings.py: SESSION_ENGINE = "django.contrib.sessions.backends.cache" but this causes the users session to be cleared on server refresh which is a pain during development, so another option would be needed. I primarily use pythons sqlite3 package to execute most queries which could be a possible factor contributing to this error. sqlite3 connection settings connection = sqlite3.connect(r"C:\Users\logan..\....\db.sqlite3", check_same_thread=False) django database settings in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } perhaps using a different session engine would resolve this issue, or some other configuration in settings.py -
Custom Django JSON field with additional API information
I want to implement a custom json field that would take in the id and put it in json together with other API information. Let's say you receive an id of 2, so you want to put it together in the database like this: { "id": 2, "API": "path-to-api", "additional-info": ... } The additional info, API and other keys added to the json are known at the field declaration time, and they are always the same for the given column. I used Django's get_prep_value to change the value inserted into the DB. I am also using django rest framework ModelSerializer and generics for the views. When I create a new entry, the POST response doesn't have the correct JSON, just the id I sent it. However, if I look into the database, I can see that the value is saved in the correct way and if I list the values using the default generics ListCreateAPIView, I receive the correct JSON. So the question is: Can I do this kind of functionality somehow on the field level? -
Filter queryset based on related object's field value
I have two models: class PartUse(models.Model): ... imported = models.BooleanField() class PartReturn(models.Model): partuse = models.ForeignKey(PartUse) ... imported = models.BooleanField() class PartUseListView(ListView): model = PartUse def get_queryset(self): if self.request.GET.get('show_imported', None): qs = self.model.objects.all() else: qs = self.model.objects.filter(imported=False) // including related return qs I want to filter QuerySet for PartUse to return all PartUse instances that have imported == False for either model. What's the best way to achieve that? -
LookupError: No installed app with label '—'
I'm trying to deploy my django project by following this link however i have done everything that blog specified and im getting error in its last step. While restarting supervisorctl (venv) ubuntu@ip-:~/UNIQUETRADE$ sudo supervisorctl restart django-demo django-demo: stopped django-demo: ERROR (spawn error) While running manage.py runserver I'm not getting any error. But when running python manage.py check — deploy I'm getting below error. (venv) ubuntu@ip-:~/UNIQUETRADE$ python manage.py check — deploy Traceback (most recent call last): File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/apps/registry.py", line 158, in get_app_config return self.app_configs[app_label] KeyError: '—' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/UNIQUETRADE/manage.py", line 22, in <module> main() File "/home/ubuntu/UNIQUETRADE/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/commands/check.py", line 56, in handle app_configs = [apps.get_app_config(app_label) for app_label in app_labels] File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/core/management/commands/check.py", line 56, in <listcomp> app_configs = [apps.get_app_config(app_label) for app_label in app_labels] File "/home/ubuntu/UNIQUETRADE/venv/lib/python3.10/site-packages/django/apps/registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label '—'. Here is my error log recorded from /var/log/gunicorn_supervisor.log: [2023-03-13 17:40:58 +0000] [7464] [INFO] Starting … -
How can i deploy Django app in a local network
I have a local network with 10 computers. How can i run a django app locally, so that each of the 10 computers can access the app? -
Apache2 + Django permission
Yea i know, another same problem. But no, every solutions does end work. I take old laptop, and install on it Ubuntu Server 22.04. Next i install Apache2, run server and it works on local IP and public. I setup a DNS SSL and everything works fine. But i want something more then html. So i try to add Django to my server, and make an cool website. Again: physical laptop, no virtual machine I found tutorials on Google and start to make a Django. Everything looks cool, but at the end i every time have error to connect to website with Django. Only Django on virtual env and local net works. Ony i have problem when i 'connect' it do Apache2 Every time i have errors "The server encountered an internal error or misconfiguration and was unable to complete your request." or "You don't have permission to access this resource." On local and public IP I try to find answer to my errors, i move all project to /opt, i try to edit 000-default.conf, apache2.conf, (try to) make permission with 'chmod', 'chmod o+x', i remove and replace index.html. Nothing works. Same erros. Help me :( -
Django does not create a multi-language sitemap
According to the documentation I made a site map, the site is multilingual, but instead of a normal map it displays a list of url without spaces. And it does not create a version of the page for each language. sitemap.py from django.contrib.sitemaps import Sitemap from movies.models import Movies class DynamicViewSitemap(Sitemap): changefreq = 'weekly' i18n = True languages = ["en", "ru", "de", "es","pt", "fr"] alternates = True x_default = True def items(self): return Movies.objects.all() def location(self, item): return f'/movies/{item.slug}/' urls.py sitemaps = { 'dynamic': DynamicViewSitemap } urlpatterns = [ path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), Result: https://wherefilmed.org/sitemap.xml -
django administration : TabularInline as list
I looking for a simple way or a package for making my tabularinline works as a list with pagination, number of item per page, filter, research and multiple selection (for delete action). I have a model DiscountCode and DiscountCodeUsage and is possible that i have more than 1000 object DiscountCodeUsage for one DiscountCode and the standard tabularinline can't work for me. -
How to use URL patterns in a HTML file using Django?
I am creating a web application in Django, and I need to link to a webpage that creates a model and then redirects you back. I have already created this webpage, but I need to create a link to it. This is the URL pattern for it (yes, it is long and ugly): path('add_to_trip/<int:id>/<str:name>/<str:addr>/<str:rating>', add_to_trip, name="add_to_trip"), I am trying to use this link to redirect to it, but Django can't understand it. <a class="btn btn-primary" href="{% url 'add_to_trip/{{trip_id}}/{{place_results_name}}/{{place_results_addr}}/{{place_results_rating}}' %}" style="margin-top: 10px;">Add to trip</a> This is the error I am getting: NoReverseMatch at /plan/3/ Reverse for 'add_to_trip/{{trip_id}}/{{place_results_name}}/{{place_results_addr}}/{{place_results_rating}}' not found. 'add_to_trip/{{trip_id}}/{{place_results_name}}/{{place_results_addr}}/{{place_results_rating}}' is not a valid view function or pattern name. I don't know why Django isn't using the URl pattern I provided. -
In django, how do I pass in context to a view for a specific entry in my database?
I'm quite new to django and python so please bear with me. I'm trying to create a view inside my django project that will display one entry inside my database. I have a specific template for how I want the data in the entry to be displayed. I have an app inside my project called card_catalog. Inside this app I have a function based view. Here is the code from the views.py file. def flashcard_view(request): sentence = Flashcard.objects.values_list('sentence',flat=True) word_dict_form = Flashcard.objects.only('word_dict_form') ipa = Flashcard.objects.only('ipa') pos = Flashcard.objects.only('pos') word_trans = Flashcard.objects.only('word_trans') sent_trans = Flashcard.objects.only('sent_trans') context = { 'sentence':sentence, 'word_dict_form':word_dict_form, 'ipa':ipa, 'pos':pos, 'word_trans':word_trans, 'sent_trans':sent_trans } return render(request,'card_catalog/flashcard_view.html',context=context) Here is the code for the flashcard model in the models.py file: class Flashcard(models.Model): #Main fields sentence = models.CharField(max_length=250,null=True,blank=True) word_dict_form = models.CharField(max_length=50,null=True,blank=True) word_inflected_form = models.CharField(max_length=50,null=True,blank=True) ipa = models.CharField(max_length=50,null=True,blank=True) pos = models.CharField(max_length=50,null=True,blank=True) word_trans = models.CharField(max_length=50,null=True,blank=True) sent_trans = models.CharField(max_length=250,null=True,blank=True) # sound_word = # sound_sentence = # notes_visible # notes_not_visible # Card Activation fields activate_nw_card = models.BooleanField(default=True) activate_pic_word_card = models.BooleanField(default=True) activate_word_sent_card = models.BooleanField(default=True) activate_lr_card = models.BooleanField(default=False) activate_inflected_form_card = models.BooleanField(default=False) activate_pron_card = models.BooleanField(default=False) activate_spell_card = models.BooleanField(default=False) activate_trans_word_card = models.BooleanField(default=False) activate_sent_trans_card = models.BooleanField(default=False) # Image Links image_1_url = models.URLField(max_length=500,null=True,blank=True) image_1_overlay = models.URLField(max_length=500, null=True, blank=True) image_2_url = models.URLField(max_length=500, null=True, blank=True) image_2_overlay … -
I have Problem with GenericForeignKey in admin
I have photo model with GenericForeignKey filed for 3 other model(movie, show, episode) when i want to create a photo in admin i choose the content type but i can't use raw_id_fields on object_id class Photo(models.Model): def get_photo_filename(instance, filename): content_type_name = instance.content_type.model return f"{content_type_name.lower()}s/{instance.content_object.name}/photo/{filename}" title = models.CharField(max_length=30) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={"model__in": ('show', 'movie', 'episode')}) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to=get_photo_filename) Is there any module that fix my problem? -
How do I change a function written in for loop into a single query set?
I have some django query as bellow. There is a monthly_date column in Building model, and I have my custom function get_start_date to calculate the date from monthly_date. This code with for loop works well. target = [] for building in Building.objects.filter( contract_date=view.base_date, ): if building.payments.filter(scheduled_date__lte=get_start_date(building.monthly_date)): target.append(building) I'm trying to remove for loop to make it only one query. Building.objects.filter( contract_date=view.base_date, payments__scheduled_date__lte=get_start_date(F('monthly_date')) ) I tried with F but I got RecursionError . There is some while loop in get_start_date but it works well with for loop so I don't know why this error occur. date_map = {datetime.date(2023, 2, 19): datetime.date(2022, 11, 18)} Building.objects.filter( contract_date=view.base_date, payments__scheduled_date__lte=date_map[F('monthly_date')] ) I tried like this after calculated date_map first from monthly_date, but KeyError: F(monthly_date) occur this time. What should I do to make it one query? -
python error : from django.core.management import execute_from_command_line
This is my first question in Stack Overflow. And yes, I am quite of a beginner in coding. I have developed a web app with Django / Wagtail. I wanted to work from home and work. I bought a mac mini M2. At my other computer, everything works fine. No issues on the application running on local mode. However, when I installed my new computer with all packages, I came across the following error: Traceback (most recent call last): File "/Users/marcmini/Library/Mobile Documents/com~apple~CloudDocs/Documents/GitHub/Ellipsis-Web/manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' I have these versions: pyenv versions system 3.9.2 (set by /Users/marcmini/.pyenv/version) 3.10.10 3.11.2 And the Django version 4.1.7 ( I run inside my project PIP LIST and all packages appear - I won't list all because I suppose that's not a problem ) My files are in iCloud, so I am not sure if it is a path issue. marcmini@Mac-mini-de-Marc ellipsis-web % pip install django Requirement already satisfied: django in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (4.1.7) Requirement already satisfied: asgiref<4,>=3.5.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from django) (3.6.0) Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from django) (0.4.3) I have checked this solution but it doesn't work the one that gets 288 or … -
How to pass today date in requests params Django
I have celery function which sending every 5 mins request to api and get some json data I want to know how to pass today date in params to this request for example: Full data will be 15k lines but if i pass today date to param ill get only 1k lines tasks.py def create_presence_info(): payload = {'today_date': today} # this is an example idk what i should write there url = config('PRESENCE_INFO') response = requests.get(url, auth=UNICA_AUTH) -
sending emails from a gmail account using django
I have been trying to send an email using my Gmail account but the receiver is not getting anything, why that? views.py from django.shortcuts import render from django.core.mail import send_mail def index(request): if request.method == "POST": receiver = request.POST.get("receiver") from_email = "myemailaddress" recipient_list = [receiver] subject = "Just sending message" message = "If you are seeing this then this possibly worked" send_mail(subject, message, from_email, recipient_list, fail_silently=False) return render(request, 'index.html') settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemailaddress' EMAIL_HOST_PASSWORD = 'myemailpassword' How do i tackle this problem