Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Write JSON to a file in pretty print format in Django
I need to create some json files for exporting data from a Django system to Google Big Query. The problem is that Google BQ impose some characteristics in the json file, for example, that each object must be in a different line. json.dumps writes a stringify version of the json, so it is not useful for me. Django serializes writes better json, but it put all in one line. All the information I found about pretty printing is about json.dumps, that I cannot use. I will like to know if anyone knows a way to create a json file in the format required by Big Query -
why I can not in folder static inside app for project django
i can't access to folder static for project the project structure: -myproject --core --settings.py --myapp --static --------myapp ---- js ---- css --templates --static in settings.py STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR, "static"), ] print STATICFILES_DIRS ['/media/my_pc/Apps/my_project/static'] in main urls.py usethis: if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() now i do call file static js don't work -
Django postgis point is in polygon or on boundary
I have a PolygonField poly in my model. For a given point I want to filter all items that either lie within polygon, or lie on its boundary or the smallest distance between the point and polygon is x. .filter(poly__contains=point) checks only first. What about other two conditions? -
Django-Graphene - Relation to an object of the same type
I have defined a database model in which a task object has a relationship to the same task object. class Task(models.Model): id = models.AutoField(primary_key=True) status_id = models.ForeignKey(Status, null=True, on_delete=models.SET_NULL) parent_id = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=128) description = models.CharField(max_length=256) entry = models.IntegerField() In the Graphql API I made it possible to get a task object for myself. I would like to achieve the possibility of retrieving the entire object tree of the same type by calling a graphql query with one call to the object type task. Is it possible? class TaskType(graphene.ObjectType): id = graphene.NonNull(graphene.Int) parent_id = graphene.Field(graphene.Int) name = graphene.NonNull(graphene.String) description = graphene.NonNull(graphene.String) entry = graphene.NonNull(graphene.Int) parent = graphene.List(lambda: TaskType) @staticmethod def resolve_parent(task, _info): return Task.objects.filter(parent_id=task.id) I know I can return such a tree in JSONString type, but I'm looking for a different solution. -
Django query, finding the maximum object
I'm hitting my head on something that should be simple. I have a query like this: MyModel.objects.filter(...).aggregate(max_value=Max('value')) and this does, indeed, return a (dictionary) with key 'max_value' and value that maximum value. But what I want is the object that has that maximum value. -
Heroku issues when uploading pdf and jpg through admin panel | Django, Python
I have a simple project made with python/django and I upload pdfs and jpgs through admin panel. These files can be reached for a day or two, after that I think Heroku delete them. I use in setting whitenoise and I don't get why the server removes them. Settings MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Template for pdf <p>{{ IntroductionCv.paragraph }}</p> <a href="{{ IntroductionCv.pdf.url }}" class="btn btn-fill" target="_blank" download>Download my cv</a> Template for jpg <div class="row"> {% for project in Projects %} <div class="col-md-4 col-xs-6"> <div class="portfolio-item"> <img src="{{ project.image_project.url }}" class="img-res" alt=""> <div class="portfolio-item-info"> <h4>{{ project.title }}</h4> <a href="{{ project.github_link }}"><i class="fab fa-github-square" style="font-size: 5em;"></i></a> <a href="{{ project.site_link }}"><span class="glyphicon glyphicon-link" style="font-size: 4em;"></span></a> </div><!-- /.portfolio-item-info --> </div><!-- /.portfolio-item --> </div> {% endfor %} </div> Views def index(request): context = {'BackEndSkills': BackEndSkills.objects.all(), 'SoftSkills': SoftSkills.objects.all(), 'Services': Services.objects.all(), 'Projects': Projects.objects.all(), 'Counter': Counter.objects.all(), 'IntroductionCv': IntroductionCv.objects.latest('id'), 'title': 'Alexandru Aprodu'} return render(request, 'the_professional/index.html', context) Model for pdf class IntroductionCv(models.Model): paragraph = models.TextField() pdf = models.FileField(upload_to='media', verbose_name='PDF') def __str__(self): template = '{0.paragraph} {0.pdf}' return template.format(self) class Meta: verbose_name_plural = "Introduction Cv" Model for jpg class Projects(models.Model): … -
Create blank (null) profile with writable nested serializers DRF
so I am trying to have an empty profile be created whenever a new user signs up. The problem is the nested (null) serializers are not being created along with the other serializer and returns "education": [ "This field is required." ] Now if I add required=False than if will just return empty data without actually creating the blank education model { "id": #, "education": [], # I want this to be a null list "image": "null", "resume": null, "bio": null, "interests": null } Profile and Education model: from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_default.jpg', upload_to='profile_pics') # TALENT FIELDS resume = models.FileField(upload_to='resumes', null=True) bio = models.TextField("Bio", blank=True, null=True) interests = models.TextField("Interest", blank=True, null=True) class Education(models.Model): owner = models.ForeignKey(Profile, related_name='education', on_delete=models.CASCADE) # TODO: change delete type field = models.CharField(max_length=100, null=True) school = models.CharField(max_length=100, null=True) start_year = models.CharField(max_length=4, null=True) start_month = models.CharField(max_length=10, null=True) graduation_year = models.CharField(max_length=4, null=True) graduation_month = models.CharField(max_length=10, null=True) degree = models.CharField(max_length=100, null=True) gpa = models.CharField(max_length=10, null=True) awards = models.TextField(max_length=100, blank=True) Serializers: from rest_framework import serializers from .models import Profile, Education class EducationSerializer(serializers.ModelSerializer): class Meta: model = Education exclude = ['owner', ] class CreateProfileSerializer(serializers.ModelSerializer): education = EducationSerializer(many=True, … -
How to proper save documents in MongoDB using Djongo
I am facing a problem in which I cannot save documents inside MongoDB with Django. The error follows: AttributeError: 'NoneType' object has no attribute 'attname' With the help of the library Djongo I made these models: from djongo import models from django.utils import timezone class LatLng(models.Model): latitude = models.FloatField(null=False) longitude = models.FloatField(null=False,) def __init__(self,latitude, longitude): self.latitude = latitude self.longitude = longitude class Meta: abstract = True class Parameters(models.Model): cond1= models.IntegerField(null=False,) cond2= models.IntegerField(null=False,) cond3= models.IntegerField() class Meta: abstract = True class MyModel(models.Model): name = models.CharField(max_length=150, null=False) des= models.CharField(max_length=500) pub_date = models.DateTimeField(editable=False) mod_date = models.DateTimeField() parameters = models.EmbeddedField( model_container=Parameters ) wp= models.ArrayField( model_container=LatLng, null=False ) objects = models.DjongoManager() def __init__(self, name, parameters, wp,des=""): self.name = name self.parameters = parameters self.waypoints = waypoints def save(self, *args, **kwargs): ''' On save, update timestamps ''' if self.id is None: self.pub_date = timezone.now() self.mod_date = timezone.now() return super(MyModel, self).save(*args, **kwargs) def __str__(self): return self.name My API looks like: def get_wp(pls): wps = [] for pin pls: coord = LatLng(latitude=p['latitude'], longitude=p['longitude']) wps.append(coord) return wps @api_view(['POST']) def save(request): data = json.loads(request.body.decode('utf-8')) scores = Parameters(cond1=data['cond1'], cond2=data['cond2']) wps = get_wp(data['pls']) obj = MyModel(name=data['name'],parameters=scores, waypoints=wps) print("--> {}".format(obj.name)) #working fine itinerary.save() ## it dies here return JsonResponse({}) I don't know what I'm … -
Using DJ-Rest-Auth: Updating User Profile
I am struggling to figure out why I cant update my user profile I keep getting the below error. {'profile': {'email': [ErrorDetail(string='user with this email address already exists.', code='unique')]}} django.request:log.py:224 Bad Request: /api/students/cf6c35b7-0202-4465-add9-135c52c0bed6/ From my understanding is that the update is actually trying to create a another User. Which is not what I am trying to do. Here is the test code that is failing. def test_change_school(self): createResponse = client.post('/api/auth/reg/', { "email":"test@test.com", "password1":"10wer1232", "password2":"10wer1232", "first_name": "Blake", "last_name": "Alvernaz", "image": "No Image", "is_student": True, "is_teacher": False, "school": self.school1.id}, format="json") self.assertEqual(createResponse.status_code, 201) self.assertTrue(createResponse.data['key']) profile = client.get('/api/auth/user/') id = Student.objects.get(profile_id=profile.data['id']) editRes = client.put('/api/students/{}/'.format(id.id), {"gpa":1.0, "profile":{ "email":"test@test.com", "first_name": "Blake", "last_name": "Alvernaz", "image": "No Image"}, "school": self.school2.id}, format="json") print(editRes.data) self.assertEqual(editRes.status_code,200) Serializers: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "first_name", "last_name", "image", "email"] def update(self, instance, validated_data): profile_serializer = self.fields['profile'] profile_instance = instance.profile instance.save() profile_data = validated_data.pop('profile', {}) profile_serializer.update(profile_instance, profile_data) return super().update(instance, validated_data) class StudentSerializer(serializers.ModelSerializer): profile = UserProfileSerializer() class Meta: model = Student fields = ["gpa", "profile", "id", 'school'] read_only_fields = ("profile",) class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = ['id', 'name', 'image' ] class CustomRegisterSerializer(RegisterSerializer): is_student = serializers.BooleanField(default=True, write_only=True) is_teacher = serializers.BooleanField(default=False, write_only=True) school = serializers.CharField() @transaction.atomic def save(self, request): user … -
Automatically attach VS Code configuration to container
I'm using a VS code config to attach to a running container so I can run my tests inside the container. ptvsd is used for this. launch.json has the following config: { "version": "0.2.0", "configurations": [ { "name": "Run Django", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}/src", "remoteRoot": "/app" } ], "port": 3000, "host": "127.0.0.1", } ] }< ´´´ I also have a volume mapping in my `docker-compose.yml` so my updates are reflected directly in the container: volumes: - ./src:/app The issue is ... when I make a change VS code unattaches itself and I have to go into debug to restart it. Is there any way to configure VS code so that if an attach fails it will retry it after a few seconds for, say up to a minute or so? This would allow the StatReloader to complete and give it something to attach to. -
VS Code and Python
just reinstalled VS code on my new Mac, and everytime I start it it asks me to install python. Python is referenced in the .zshrc to my brew install, it is also correctly referenced in VS Code, and I have no issues working in python it just throws the error when I open a Python file. Screen shot of VS Code, bar and error -
How to remove clicked line from Bokeh plot
I need to plot several lines in one figure, and by clicking on one get it's reference and remove it from the figure, but I have no idea how to do it. I need to do it in django, so interactive matplotlib code I wrote is no good. In Matplotlib I did it like this: def on_pick(event): id = event.artist event.artist.remove() fig.canvas.draw() I can't find anything usefull, is it possible to do it in bokeh? Please direct me -
Firebase Firestore doesn't retrieve data under Apache (Django)
The following Django 3 code print("trying to add doc") db.collection('col_name').document('doc_name').set({'test_field':1}) print("doc added") works when running python manage.py runserver i.e, a document is created on Firebase When deployed to Apache24 (ApacheLounge version) with mod_wsgi on Win10, the second line hangs. Same hanging problem happens when we try to iterate through the collection (only read operations). for doc in collection('col_name').stream(): -
How can I use images in Django back end without saving it?
I want this site to take an image from user and show it on another page, well I want to to something more with the picture but I have already managed it. I am stuck here, how can I fix it. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Upload a Photo</title> </head> <body> <form action="showpicture/" method="GET"> <h1>Upload An Image</h1> <label for="img">Select image:</label> <input type="file" id="img" name="img" accept="image/*"> <br><br> <input type="submit"> </form> </body> </html>` My View File from django.shortcuts import render from django.http import HttpResponse, HttpResponseForbidden def index(req): return render(req, "pic/index.html") def showPic(req): return HttpResponse(req.GET['img'])` I want to show the picture in the next page without saving it, how can I do it ? -
I made Hashtag system for my website but after using special characters like " ' " or " ; " and so on it makes #hashtag in Django
I have uploaded an screen shot of the issue. I've tried to use SAFE but it doesn't work. post.content|safe|hashchange Hope someone can help me here -
how to filter items in django
I have some users in my application where some are admin and some are suppliers, I will like to filter only those that are suppliers. I have tried using some queryset but I am not getting it. I will also like some recommendation where I can learn more about to filter objects in Django or python. Thanks models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) telephone = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] def get_absolute_url(self): return "/users/%i/" % (self.pk) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_supplier == True: return User.get_email(self.user) + " - is_supplier" else: return User.get_email(self.user) + " - is_admin" views.py def Viewsupplier(request): suppliers = User.objects.filter(i am getting stuck here with the appriopriate filter) context = {"suppliers":suppliers} print(suppliers) return render(request, 'core/view-suppliers.html', context) -
Creating a registration view in django, always getting an integrity error
So here's the function i wrote for the view: def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] year = request.POST["Year"] form = registerForm(request.POST) if form.is_valid(): branch = form.cleaned_data['branch'] else: return render(request, "events/register.html", { "message": "You didn't provide all the fields", "form": registerForm() }) if not email.endswith("ac.in"): return render(request, "events/register.html", { "message": "You must have an institution account", "form": registerForm() }) # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "events/register.html", { "message": "Passwords must match.", "form": registerForm() }) try: name = User.objects.get(email=email) except ObjectDoesNotExist : name = None # Attempt to create new user #Now This is where the problem is if name is None: user = User.objects.create(username=username, email=email, password=password, year=year, branch=branch) user.save() else: return render(request, "events/register.html", { "message": "email already taken.", "form": registerForm() }) login(request, user) return HttpResponseRedirect(reverse("events:index")) else: ctx = { "form": registerForm() } return render(request, "events/register.html", ctx) So when the form is submitted, i first check if an object with the entered username already exists, if it does than return the form with a message(email already taken). But everytime i try to create a new user, this message is returned and i am unable to … -
How to update ManyToMany data?
I have a User who can follow/unfollow other users. Each User have a Profile where the users he follows he stored. MODEL class User(AbstractUser): pass class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) following = models.ManyToManyField("User", blank=True, related_name="following_name") follower = models.ManyToManyField("User", blank=True, related_name="follower_name") VIEWS @login_required def userlookup (request, username): if request.method == "POST": # Foo has ID = 5 # Bar has ID = 6 # Baz has ID = 7 # CurrentUser is FOO so CurrentUser = 5 CurrentUser = request.user.id # I am looking at Bar's Profile page so username = 'bar' # This gives TargetUser = 6 TargetUser = User.objects.get(username=username).id # Setup variable has a "boolean" to false by default isfollowing = 'false' # Obtain the list of users that Foo currently follows Following = list(Profile.objects.filter(user=CurrentUser).values('following')) # This returns : [{'following': 6}, {'following': 7}] # Loop through each entry to check if the TargetUser is followed by Foo or not for i in Following: if i['following'] == TargetUser: # On this occasion, Foo do follow Bar so we change the variable to true isfollowing = 'true' # Since the var is set to true, we want to remove the TargetUser from the list because we are "unfollowing him". if … -
unix venv django-admin permission denied
I am trying to set up django project on a Linux CentOS system. I have created a virtual environment like this: $ python3 -m venv venv And activated it like this: $ source venv/bin/activate Within this virtual environment I updated pip like this: (venv)$ python -m pip install -U pip This returned the message below: Successfully installed pip-21.0.1 Next I installed django and djangorestframework like so: (venv)$ python -m pip install django djangorestframework This returned the message below: Successfully installed asgiref-3.3.1 django-3.1.7 djangorestframework-3.12.2 pytz-2021.1 sqlparse-0.4.1 I then tried to start a new project like this: (venv)$ django-admin startproject myproject . This is when I get the response: -bash: /home/me/projects/venv/bin/django-admin: Permission denied I don't think the solution to this should be a simple chmod on that file, because I think perhaps something is incorrect in how I installed things in the first place? Surely all permissions should be automatic considering I was working with (venv) activated? What am I missing here? -
How do I periodically run code in django?
I want to periodically run the code in django For this I downloaded Celery and tried to configure it Added to settings.py INSTALLED_APPS = [ 'django_celery_results', 'django_celery_beat', } CELERY_TIMEZONE = "Australia/Tasmania" CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 CELERY_RESULT_BACKEND = 'django-db' CELERY_RESULT_BACKEND = 'django-cache' CELERY_CACHE_BACKEND = 'default' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } Created a celery.py file import os from celery import Celery name='shop' os.environ.setdefault('DJANGO_SETTINGS_MODULE', name+'.settings') app = Celery(name) app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.beat_schedule = { 'every-15-seconds':{ 'task':'offers.tasks.send_email', 'schedule':15, 'args':('dsssew.com',) } } app.conf.timezone = 'UTC' app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Created a tasks.py file from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def send_email(email): print(email) @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y @shared_task def xsum(numbers): return sum(numbers) Launched everything in turn python manage.py runserver celery -A shop worker -l INFO celery -A shop beat -l INFO beat brought me celery beat v5.0.5 (singularity) is starting. __ - ... __ - _ LocalTime -> 2021-02-18 20:31:57 Configuration -> . broker -> amqp://guest:**@localhost:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2021-02-18 … -
Reverse_Lazy is not redirecting me to the sprcified URL
I want to make a button for my users and the superuser to be able to delete their posts in django administration. When I click on delete button neither it redirects me to the specified URL nor deleting the post. I have used mixins in order to let admin to delete every post from everyone but the users can only delete their posts. #MIXIN.py class DeleteArticleAccessMixin(): def dispatch(self, request, pk, *args, **kwargs): article = get_object_or_404(Article, pk=pk) if article.author == request.user or request.user.is_superuser: return super().dispatch(request, *args, **kwargs) else: raise Http404("Access Denied!") #Views.py class ArticleDelete(DeleteArticleAccessMixin, DetailView): model = Article success_url = reverse_lazy('account:home') template_name = "registration/article_confirm_delete.html" #urls.py path('article/delete/<int:pk>', ArticleDelete.as_view(), name="article-delete"), #My home HTML page {% if user.is_superuser or user.is_author %} <a class="badge text-danger badge-primary" href="{% url "account:article-delete" article.pk %}">Delete Article</a> {% endif %} #My Html Delete page <div class="col-md-8 text-center mx-auto"> <div class="card card-danger"> <div class="card-header"> <h3 class="card-title">Delete Article</h3> </div> <div class="card-body py-4"> <form method="post">{% csrf_token %} <p class="py-2">Are you sure you want to delete "{{ object }}" written by "{{ object.author.get_full_name }}"?</p> <input type="submit" value="Confirm" class="btn btn-danger"> </form> </div> </div> </div> -
How to run github django projects on pc after cloning
This type of error is occuring in my system enter image description here -
What programming language to use for a chat app
I want to build an app where a chat is a very important feature. For frontend I use React Native and for backend Django (REST framework). But is Django (REST framework) the best choice for chat apps? Are there any languages (other than Erlang) that are better suited for programming chat apps? And Instagram itself uses only Django (REST framework) and React Native, if you trust the official source Instagram Engineering. Is it possible (of course it is) or useful to write an app only in Django (REST framework)? (And if so, does anyone perhaps have a tutorial I can use to build a chat app using Django? Many thanks in advance :) -
Django_rest_framework hyper Linked identity
thanks for your time. i've written some views in rest framework although aint beeing able to set the links for the 'player-detail' and 'event-detail' on url field even the view name(urls.py) beeing right. urls.py: from . import views from django.urls import path, include from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('home/', views.home_view, name='home'), path('player_list/', views.player_list, name='player_list'), path('event_list/', views.event_list, name='event_list'), path('player_detail/<int:id>/', views.player_detail, name='player-detail'), path('event_detail/<int:id>/', views.event_detail, name='event-detail'), path('api-auth/', include('rest_framework.urls')), #class based# path('player_list_class/', views.PlayerList.as_view(), name='player-list'), path('player_detail_class/', views.PlayerDetail.as_view(), name='player-detail'), path('event_list_class/', views.EventList.as_view(), name='event_list'), path('event_detail_class/', views.EventDetail.as_view(), name='event_detail'), ] urlpatterns = format_suffix_patterns(urlpatterns) serializers.py: from .models import * from rest_framework import serializers from .models import Player, Event class PlayerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Player fields = ['id','url', 'player_id', 'name', 'sex', 'age', 'height', 'weight', 'team'] class EventSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Event fields = ['id','url', 'noc', 'games', 'year', 'city', 'season', 'sport'] models.py: class Player (models.Model): player_id = models.PositiveIntegerField(default=1) name = models.CharField(max_length=100) sex = models.CharField(max_length=9, choices=sex_choices) age = models.PositiveIntegerField(null=True) height = models.FloatField(null=True) weight = models.FloatField(null=True) team = models.CharField(max_length=120) def __str__(self): return '%s %s' % (self.player_id, self.name) def save(self, *args, **kwargs): o1 = Player.objects.filter(player_id=self.player_id, age=self.age) if o1.exists(): raise ValidationError('Player already in') else: super().save(*args, **kwargs) class Event(models.Model): winner = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='events') noc = models.CharField(max_length=3) games = models.CharField(max_length=100) year = models.PositiveIntegerField() city … -
Django: adding cc in email with sengrid returns HTTP Error 400: Bad Request
I am following this link to send emails from Django using SendGrid. If my email address in cc and to_email is same, it returns HTTP Error 400: Bad Request. But it works fine if the email address is different. Did anyone solve this problem before? I need to add cc while sending an email from Django whether the email address is the same or different. Thanks in advance. sg = SendGridAPIClient(development.EMAIL_HOST_PASSWORD) cc_email = str(ImagingCenter.objects.get(institute_id=user.center_id).email) from_email = development.DEFAULT_FROM_EMAIL to_email = to_email data = { "personalizations": [{ "to": [{ "email": to_email }], "cc": [ { "email": cc_email } ], "subject": "CC Email Testing" } ], "from": { "email": from_email }, "content": [ { "type": "text/html", "value": html_message } ] } response = sg.client.mail.send.post(request_body=data)