Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After adding media to AWS S3, Django gives me a weird error whenever I access a page with a media file
The error is like this: ValueError at /postview/24 Required parameter name not set Request Method: GET Request URL: http://127.0.0.1:8000/postview/24 Django Version: 3.0.6 Exception Type: ValueError Exception Value: Required parameter name not set Exception Location: C:\Users\Lenovo\Desktop\src\env\lib\site-packages\boto3\resources\base.py in __init__, line 118 Python Executable: C:\Users\Lenovo\Desktop\src\env\scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\Lenovo\\Desktop\\src', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\Lenovo\\Desktop\\src\\env', 'C:\\Users\\Lenovo\\Desktop\\src\\env\\lib\\site-packages'] Server time: Thu, 4 Jun 2020 11:16:39 +0300 Wich has no real correlation with S3 because the error is intercepted on line 34 for some reason. This worked well until I added the S3 settings and permissions from the boto3 docs and django-storages docs. <!-- HELL --> 33 {% if user.is_authenticated %} 34 {% if user.is_superuser %} 35 <ul class="nav navbar-nav navbar-right"> 36 <li><a href="{%url 'comments'%}"><span class="glyphicon glyphicon-comment"></span> Comments</a></li> 37 <li><a href="{%url 'inbox'%}"><span class="glyphicon glyphicon-envelope"></span> Inbox</a></li> 38 <li><a href="{%url 'createpost'%}"><span class="glyphicon glyphicon-list-alt"></span> Create Post</a></li> 39 <li><a href="{%url 'logout'%}"><span class="glyphicon glyphicon-log-in"></span> Logout</a></li> 40 </ul> 41 {% else %} My setting.py file looks like this: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = r"*********************************************" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'personal', 'users', 'contact', 'Tasks', 'storages' … -
django not cleaning up previous data
I have a django setup which does not include any models or data base. It is just simple HTML, JAVAscript and python. It seems like django is not cleaning up the previous run data. How to cleanup data from forms after every run? I am not making use of sessions also. I am new to django and don;t have much time to learn sessions and implement things. Can any one give a solution on how to cleanup data after every run? -
Django ORM bulk read query
I have a model called User which has a property called is_free() which runs a query like this @property def is_free(self): return User.objects.free_user().filter(id=self.id).exists() When i try to get multiple users and populate them using a for loop there are many SQL queries executed based on the number of users i am populating which is affecting the API timings. For Example - for user in selected_users: user_list.append({"id": job.id, "name": job.name, "is_free": job.is_free, "title_display": job.title_display}) Is there a better way to do this without changing the model? I am using Django 1.8 and Python 2.7 -
django makemigrations override to create migration files with custom names
I have a python2.7 django project (I know, I am in 20th century!) that has some models in it. I need to override makemigrations so that the migration filenames are of the form 0001.py, 0002.py and so on, and not like 0001_initial.py, 0002_model1.py and so on which is by default what happens. I already looked at how to create custom manage.py commands and I am able to override makemigrations command. Presently my code for the custom command (python2.7) looks like this: from django.core.management.commands.makemigrations import Command as CoreMakeMigrationsCommand class Command(CoreMakeMigrationsCommand): def handle(self, *args, **options): super(Command, self).handle(*args, **options) It is doing nothing more than calling the original makemigrations at the moment. I need to be able to modify the behaviour of how autodetector.py(which is part of the makemigrations flow) decides the naming of the files. In this file, there's method suggest_name as shown below: @classmethod def suggest_name(cls, ops): """ Given a set of operations, suggest a name for the migration they might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible. """ if len(ops) == 1: if isinstance(ops[0], operations.CreateModel): return ops[0].name_lower elif isinstance(ops[0], operations.DeleteModel): return "delete_%s" % ops[0].name_lower elif … -
New tags are created automatically when I edit my Django Post with django-taggit
Everytime I try to edit my post, django-taggit creates a new url for the existing tags. What is the reason behind it and how to fix it? Here is my edit post view. note = get_object_or_404(Note, pk=pk) if note.user != request.user: messages.error(request, 'You are not authenticated to perform this action') return redirect('notes') if request.method == 'POST': form = AddNoteForm(request.POST, instance=note) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user form_data.save() form.save_m2m() return redirect('note_detail', slug=note.slug) else: form = AddNoteForm(initial={ 'note_title': note.note_title, 'note_content': note.note_content, 'tags': ','.join([i.slug for i in note.tags.all()]), }, instance=note) return render(request, 'modals/edit_note_modal.html', {'form': form} -
Upload an Image to Django Rest Framework using Requests Library
I am trying to make an api endpoint for creating a post, the user can choose whether they want to upload a text(tweet) or an image alone or both, I have a validate method in my serializer for if no image nor text is sent, but it's raising the error on every try regardless if what I sent it. Am not entirely sure if this is a serializer class error or the script I wrote for sending the POST request Here is the script: import os import requests from PIL import Image ENDPOINT = "http://0.0.0.0:8000/" IMG = os.path.join(os.getcwd(), "img/img.jpg") def send_request(method="GET", path="/", data=None, img_path=None): if data is None: data = {} if img_path is not None: with open(img_path, 'rb') as image: img_file = {"image": image} req = requests.request(method, ENDPOINT + path, data=data, files=img_file) else: req = requests.request(method, ENDPOINT + path, data=data) return req.text res = send_request(method="POST", path="api/posts/create/", data={"user": 1, "content": ""}, img_path=IMG) print(res) Here's the model class: from django.db import models from django.conf import settings import uuid import os class PostQuerySet(models.QuerySet): pass class PostManager(models.Manager): def get_queryset(self): return PostQuerySet(self.model, using=self._db) def upload_post_image(instance, filename): file_extension = filename.split('.')[-1] filename = f"{uuid.uuid4()}.{file_extension}" print(os.path.join()) return os.path.join('post_image/', filename) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = … -
How can i write better Code for the views.py
Good Morning, i have a Question. I worked on my First Web-Application and now i finished the stuff and want to make the code a bit better. This Projekt is my Thesis Projekt too so they look into my Code and if thats too bad, ill get a bad Grade. So there are only two Points on my list, for now, which are pretty important. At first, the Projekt is for Automate some Office Stuff like Create Google or Git Repos. So we have many API Calls and we have many Buttons on this Page. To delete the User, add him or whatever. We have more than user ofc, but i dont have to listen everything. The Point now is, that i have a Tempplate where i have like 8 Buttons. Its a Management Panel where we can do tons of Actions. The Code for that is just ugly. Here is a small Example: if 'delete' in request.POST: todel = Employee.objects.get(id=id) deleteUser(request, todel, deleteOrArchive=0) if 'deactivate' in request.POST: todel = Employee.objects.get(id=id) deleteUser(request, todel, deleteOrArchive=1) So there are many Ifs like that. I use Function Based Views everywhere because i thought its not that good to use Class Based Views here. … -
How to juggle between a null value for a field in sql query
I have a sql query. It first gets all the songs from the playlists. These songs could have an entry in Block Song Table and possibly some songs may not have an entry in the block song model. So, for those songs who have an entry they will have an unblock_flag which is a boolean field and will carry either true or false. But, the concern is that those songs which will not have an entry in the block song model table, will have null values for unblock_flag. I studied nvl in SQL, but it didn't work properly. The field to be changed is core_blocksong.unblock_flag in the below query. So, if anyone can suggest any other ways to make this scenario work? select songs.id, songs.name, songs.artist, songs.album, songs.albumart, songs."albumartThumbnail", cpr.votes, is_requested, core_blocksong.unblock_flag from (select id, name, artist, album, albumart, "albumartThumbnail" from (select song_id from core_plsongassociation where playlist_id in (1477)) as sinpl left join songs on sinpl.song_id=id) as songs left join (select` song_id, votes, bool_or(user_id=null) as is_requested from (select * from core_priorityrequests where client_id=2876 and is_played=False) as clpr left join core_priorityrequests_requested_by on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes) as cpr on songs.id=cpr.song_id left join core_blocksong on songs.id = core_blocksong.song_id where core_blocksong.unblock_flag='f'and … -
Cookies is not set in request header
I have a client-server application build with Angular 9 and Django and I am facing the following situation: After login, I receive the session-id in Response Header. Even if the browser sets this cookie and I am able to see it in Dev Tools > Application > Cookie, this cookie is not used in the subsequent requests. More exactly, if I make a request after login, my Django server shows that there is no session and the user is not logged in. I searched this problem on the Internet and I found out that I have to set {withCredentials: true} in request headers in my Angular project. I make an Interceptor to set {withCredentials: true} in every request header, but this is not working for me. I put this interceptor in Providers in AppModule in this way: providers: [[{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}]] Here is my code for the interceptor: @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(public auth: AuthService) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { request = request.clone({ withCredentials: true }); return next.handle(request); } } This is my login in Angular: login() { // stop here if form is invalid if (!this.loginForm.valid) { return; } this.authService.login(this.loginForm.value) … -
how can add number to integerField in django models?
i have a django model like this : class Post(models.Model): pub_date = models.DateTimeField(auto_now_add=True) featured = models.booleanField(default=False) num = models.IntegerField(defualt = 0, null=True,blank=True) def save(self,*args,**kwargs): if self.featured is not None: self.pub_date = timezone.now() self.featured = False self.num = ++1 super (Post,self).save(*args,**kwargs) infact i want add number in my num field when the timezone is updated but this line self.num = ++1 isnt working -
how to values from foreignkey Fiels of a model in django?
i have three models like :Event,Device,Nodes class Device(BaseModel): """ Store device information """ did = models.CharField(_("DID"), max_length=255, unique=True, db_index=True) active = models.BooleanField(default=False) class Event(BaseModel): """ Store events info """ title = models.CharField(_("Title"), max_length=255) location = models.ForeignKey(to=Location, on_delete=models.PROTECT, null=True, blank=True) status = models.CharField( _("Status"), choices=EVENT_STATUS, max_length=255, default="notstarted") def __str__(self): return self.title class Node(BaseModel): """ Store info of Nodes """ label = models.CharField(_("Label"), max_length=255) parent_node = models.ForeignKey( to="self", on_delete=models.CASCADE, null=True, blank=True) device = models.ForeignKey( to=Device, on_delete=models.CASCADE, null=True, blank=True) event = models.ForeignKey(to=Event, on_delete=models.CASCADE) level = models.IntegerField(_("Level"), null=True, blank=True) is_active = models.BooleanField(default=False) def __str__(self): return "{}-{}".format(self.label, self.level) def clean_fields(self, exclude=None): if self.parent_node == self: raise ValidationError(message={ "parent_node": "Node cannot be its own Parent Node." }) return super().clean_fields(exclude=exclude) I have doubt in query to fetch json data.In this i want to get json data values like: All Event objects fields with other fields 1)'total nodes with (not null) devices in it' as field 2)'total nodes with active devices in it' as field 3)'nodes having level 1 devices' 4)'nodes having level 2 devices' I tried using Event Models :butstauck with this queryat this : events = Event.objects.node_set.all() ####serializer as this one class EventSerializer(serializers.ModelSerializer): node = NodeSerializer() class Meta: model = Event fields = "__all__" def to_representation(self, … -
Handling 404 status with SPA using Create React App and Django API backend
Sorry if this is a duplicate! I have a SPA created with CRA and React Router and a separate (not in the same project) backend with Django to handle all APIs. I would like to know what's the best approach to handle 404 page not found url's, but having it return 404 status. Because as we know, using the <Switch /> and having a router <Route component={NoMatch} key="404_not_found" /> will display the 404 page but not return the 404 status. Now there are some topics online regarding this but I don't seem to understand what would be the best approach for my scenario. 1st suggested solution Is using express - but if I use express do I need to have it as a separate project and have it act like a proxy? if yes then that would be tedious having 3 separate projects for one platform! Or would it be possible to add express on top of my CRA in the same project? I could not find anyway of doing this! Please advise if I should follow this approach. 2nd suggested solution Would be to serve the 404 from Django backend. This would be more ideal but I did not … -
What type of authentication should I use for Django with Flutter?
I was creating FLutter project with Django + Django Rest framework as backend. What I wanted to add to the app is the user authentication and I found some ways to achieve that such as Session authentication or token authentication. According to this article https://hackernoon.com/auth-headers-vs-jwt-vs-sessions-how-to-choose-the-right-auth-technique-for-apis-57e15edd053, if we want to add user authentication for mobile api, it is best to use token authentication since session authentication is not suited for mobile phones. Thus, what I want to ask is that Is it really best to use token authentication for mobile apis instead of session authentication? -
social-auth-app-django: Refresh access_token
I use social-auth-app-django for my django website. Login all works, but after the token expires. I cant access the google's user data anymore. I found how to refresh the token, but it gives File "/mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py", line 17, in handle new_token = self.get_token(user=booking_user, provider='google-oauth2') File "/mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py", line 28, in get_token social.refresh_token(strategy) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/storage.py", line 58, in refresh_token response = backend.refresh_token(token, *args, **kwargs) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/backends/oauth.py", line 438, in refresh_token request = self.request(url, **request_args) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/backends/base.py", line 234, in request response.raise_for_status() File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/requests/models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token Here is some of my code def get_token(self, user, provider): social = user.social_auth.get(provider=provider) print('This is social of user: ', social) if (social.extra_data['auth_time'] + social.extra_data['expires']) <= int(time.time()): print('\n Token is out of date \n') strategy = load_strategy() social.refresh_token(strategy) return social.extra_data['access_token'] in my settings file: AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('DJANGO_SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') # Paste CLient Key SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get('DJANGO_SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') # Paste Secret Key SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar.events' ] -
Django multiple group permission
I have similar question about group permission but in my case i have multiple group permission what should i do in my decorator.py that if the user have permission for registrar it will go to registrar page and if the user have a permission for mis it go to mis page, same goes for the accounting Django Group permission how to print it in template This is my views.py @staff_only @login_required(login_url='loginpage') def registrar_adminpage(request): #this is for group permission 'Registrar' return render(request, 'Homepage/Registrar_adminsite.html'}) @staff_only @login_required(login_url='loginpage') def mis_adminpage(request): #this is for group permission 'MIS' return render(request, 'Homepage/mis_adminsite.html'}) @staff_only @login_required(login_url='loginpage') def accounting_adminpage(request): #this is for group permission 'Accounting' return render(request, 'Homepage/accounting_adminsite.html'}) my decorators.py def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_staff: return redirect('registrar_adminpage') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=None): if allowed_roles is None: allowed_roles = [] def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def staff_only(view_func): def wrapper_function(request, *args, **kwargs): groups = None if request.user.groups.exists(): groups = list(request.user.groups.all().values_list('name', flat=True)) if 'registrar' in groups: return view_func(request, *args, **kwargs) if 'mis' in groups: return … -
I keep getting this error when trying to use / setup django-shop [closed]
I am beginning to work with django-shop and django rest framework so I can develop back end REST APIs for e-commerce applications and keep getting this error : aise ImproperlyConfigured(msg.format(pm[0][0].__name__, pm[0][1])) django.core.exceptions.ImproperlyConfigured: Deferred foreign key 'OrderPayment.order' has not been mapped I have tried other solutions but they are of no use and fail. do help! thanks in advance :) -
Save image files in django-oscar database using S3 bucket
I am using django-oscar in my current project and trying to save the media files in an s3 bucket. I am adding the products in default dashboard in django-oscar. I am confused about how to save product images on s3 and the how to save image url in Product model. In order to achieve this, what should I do? Do I have to modify Product model and add a new field for image urls? Or tweaking STATIC_URL and MEDIA_URL would be enough? Here is my media configuration. STATIC_URL = '/static/' MEDIA_URL = "https://s3.amazonaws.com/<bucket_name>/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(STATIC_URL, 'media') -
How can I download OpenCV processed video as a django httpresponse file/attachment
I'm new to OpenCV. I am trying out a use case to import video in Django, process it and download the processed video as an attachment. while the importing and processing video is straight forward, I am facing issues in downloading the video as an attachment. considering the below code as an example: import numpy as np import cv2 cap = cv2.VideoCapture('input.avi') # Define the codec and create VideoWriter object #fourcc = cv2.cv.CV_FOURCC(*'DIVX') #out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if ret==True: frame = cv2.flip(frame,0) # write the flipped frame out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break # Release everything if job is finished cap.release() out.release() cv2.destroyAllWindows() It is clear that the output is stored in output.avi using the cv2.VideoWriter. Kindly help in getting this output as a file/attachment in django. Thanks! -
How to display Matplotlib or Seaborn graph on a webpage
I am using django for a project.How I display some graph created by Matplotlib and Seaborn on html page -
Testing - Assert Django-Notification Sent
I am using django-notifications and have a view which, upon a successful POST, sends a django-notification to the admin user. I am wanting to test that the notification is sent when the POST has been successfully submitted, but dont know how. Im unsure how to even test this. My only idea is to check that the django-notifications db field has a new entry added to it, but i have been unsuccessful. Im guessing I would check somehow similar to this: self.assertEqual(1, notify.objects.count()) test.py: from notifications.signals import notify def test_notification_sent_to_admin_on_success(self): # admin user needed to receive notification admin = User.objects.create_superuser('admin', id=1) # current user user = User.objects.create_superuser('username') self.client.force_login(user) referer = 'http://testserver{}'.format(reverse('final_question')) # POST to final_question sends the notification to admin self.client.post(reverse('final_question'), { 'final_question': 'When can I start' }, HTTP_REFERER=referer) # check that notification was sent to admin self.fail('Incomplete Test') -
creating API to do calculations in backed using DRF
This question might be simple, but I like to know the proper way of doing this. I want to create some APIs that lets end user to send a string to the backed, and backend does some calculations to extract entities, and returns Jason response containing a dictionary of these entities. So in this process, I really don't need any model, any serialization and as the result no CRUD happens in my views. I can use normal Django in my view to render Json response using: return JsonResponse(dic) Also my input is currently entered in a Django form. so my question is that: 1- what would be the correct url pattern if i don't use django form. How should I retrieve string in my view based on this pattern. 2- can I use DRF here or return JsonResponse(dic) is efficient enough, Thanks -
Django admin change form widget from integer dropdown to checkbox
I have the following model with a positive small integer field for different status: class Shops(models.Model): STATUS_CHOICES = [ (0, 'Inactive'), (1, 'Active'), (2, 'Closed'), (3, 'Transferred'), ] status = models.PositiveSmallIntegerField("Status", choices=STATUS_CHOICES, null=True, blank=True) With this on the admin site status widget will be generated as select box But i want it to be a checkbox with the checkbox value be 0 and 1 following STATUS_CHOICE, and i already handle the list page to filter by status = 0 or 1 only On the admin page status would be like so: I tried to override the admin change form like so: #Form class ShopsForm(forms.ModelForm): status = forms.CheckboxInput() def __init__(self, *args, **kwargs): super(ShopsForm, self).__init__(*args, **kwargs) self.initial['status'] = False if self.instance: if self.instance.status is not None: try: self.initial['status'] = False if self.instance.status == 1: self.initial['status'] = True except: pass self.fields['status'].label = "Active" def clean_status(self): if self.cleaned_data['status'] is not None: data = self.cleaned_data['status'] else: data = None return data class Meta: model = Shops exclude = ['status'] #ModelAdmin class ShopsAdmin(admin.ModelAdmin): list_per_page = 50 form = ShopsForm list_display = ( ... 'status' ) list_display_links = ( ... 'status' ) fields = ( ... 'status', ) readonly_fields = ( 'id', ) def save_model(self, request, obj, … -
Connecting Django to Mongo Remotely
I'm trying to connect my MongoDB which is on another local server to Django and make migrations. This are my settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': "DjangoDB", 'USER': "somename", 'PASSWORD': "somepass", 'HOST': '172.17.1.147', 'PORT': '27017', 'AUTH_SOURCE': 'admin', 'AUTH_MECHANISM': 'SCRAM-SHA-1' } } Where everything match, but Django trying to connect to localhost in spite of set HOST and PORT above.. pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connect ion refused why? Forgot I set something? -
ValueError: needs to have a value for field “id” before this many-to-many relationship can be used
I'm working on a project like an E-commerce website. Everything works fine so far but if there's nothing in the user cart/bag the error will occur. I have tried the save method but I think I've done something wrong. Can someone helps me with the solution views.py def your_cart(request): user = User.objects.getFromUser(request.user) order = models.Order.objects.filter(owner = user, is_ordered = False) if (len(order)==0): order = models.Order() order.owner = raiuser else: order = order[0] items = order.items.all() if request.method == 'POST': demand_date = request.POST.get('demand_date') demand_date_obj = datetime.strptime(demand_date,"%m/%d/%Y %I:%M %p") order.demand_date = localtime.localize(demand_date_obj) order.save() return render(request, "rai_smartInventory/client_inventory/checkout.html", {'items':items}) models.py class Order(models.Model): owner = models.ForeignKey('user.User', on_delete=models.SET_NULL, null=True) is_empty = models.BooleanField(default=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) date_ordered = models.DateTimeField(auto_now_add=True) pickup_date = models.DateTimeField(blank=True, null=True) pickup_place = models.CharField(max_length=100,default='') description = models.CharField(max_length=100,default='') is_approved = models.BooleanField(default=False) is_returned = models.BooleanField(default=False) demand_date = models.DateTimeField(blank=True, null=True) def get_cart_items(self): return self.items.all() def __str__(self): return '{0}'.format(self.owner) def dict(self): return { 'id':self.id, 'owner':self.owner, 'date_ordered':self.date_ordered.isoformat() if self.date_ordered != None else '', 'is_approved':'Approved' if self.is_approved == True else 'Declined', 'pickup_date':self.pickup_date.isoformat() if self.pickup_date != None else '', 'pickup_place':self.pickup_place, 'description':self.description, 'is_returned':self.is_returned, 'demand_date':self.demand_date.isoformat() if self.demand_date != None else '', } Thank you in advance. -
How to send with Sendgrid a reset password email from a Django app deployed in Heroku?
I have been struggling for a while in trying to correctly setup the settings.py to send an email for password reset.This is my current configuration: SENDGRID_API_KEY = os.environ["SENDGRID_API_KEY"] SENDGRID_PASSWORD= os.environ["SENDGRID_PASSWORD"] SENDGRID_USERNAME= os.environ["SENDGRID_USERNAME"] EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = os.environ['SENDGRID_USERNAME'] #EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = os.environ["SENDGRID_PASSWORD"] EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = os.environ["DEFAULT_FROM_EMAIL"] #SENDGRID_SANDBOX_MODE_IN_DEBUG = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I have come across the following posts that are related to my problem but none of them have worked: Sending SMTP email with Django and Sendgrid on Heroku No module named 'sendgrid_backend' in django Send email with Sendgrid in Django Setting up email with Sendgrid in Heroku for a Django App When I used the EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"(after I installed the django-sendgrid-v5 library) I didn't receive any error but I didn't receive any email :'( and in the previous cases I encountered the following error SMTPServerDisconnected at /password-reset/ and Connection unexpectedly closed. Any help, suggestion, comment, crazy idea is really appreciated because I have spent several hours in this problem that will be a milestone in my project. Thank you everyone :)