Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found (404) on a Class-based views
I have a problem with my class bases views and i can't resolve it! i try to render a web page that show a detailed post. But my class based view refuse to work correctly. So i tried many things but no one fix my prob. It return me a 404 page not found. my urls.py from django.urls import path from .views import PostListView, PostDetailView from .models import Post from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('about/', views.about, name='blog-about'), ] my view.py # pylint:disable=no-member from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post def home(request): context = Post.objects.all() return render(request, {'posts': context}) class PostListView(ListView): model = Post context_object_name = 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model = Post def about(request): return render(request, 'blog/about.html', {'title': 'About'}) my post_detail.py {% extends "blog/base.html" %} {% block content %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <img class="img-profile" src="{{ object.author.profile.image.url }}" /> <a class="mr-2" href="#">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted | date:"d F, Y " }}</small> <hr /> </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content }}</p> </div> </article> {% endblock content %} thanks:) -
Annotation of cumulative sums of fields in queryset
This one is a doozy. I have a model which records data from when a user has watched a video: class VideoViewed(models.Model): user = models.ForeignKey(Employee, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) date_time = models.DateTimeField(default=timezone.now) From the queryset I would like to have each object in the queryset store a value which is a cumulative sum of total videos viewed by that specific user up until this point in time. Currently I have this annotation: queryset = queryset.annotate( user_views_cumsum=Window(Sum('video'), order_by=F('date_time').asc()))\ .values('user', 'video', 'date_time', 'id', 'user_views_cumsum').order_by('date_time', 'user_views_cumsum') Which I want to give the Queryset: <QuerySet [ {'user': 2, 'video': 13, 'date_time': datetime, 'id': 5, 'user_views_cumsum': 1}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 6, 'user_views_cumsum': 2}, {'user': 4, 'video': 13, 'date_time': datetime, 'id': 7, 'user_views_cumsum': 1}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 8, 'user_views_cumsum': 3}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 9, 'user_views_cumsum': 4}, {'user': 4, 'video': 13, 'date_time': datetime, 'id': 10, 'user_views_cumsum': 2} ]> But Sum('video') is giving me the cumsum of the videos id so it looks like this: <QuerySet [ {'user': 2, 'video': 13, 'date_time': datetime, 'id': 5, 'user_views_cumsum': 13}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 6, 'user_views_cumsum': 26}, {'user': 4, 'video': 13, 'date_time': datetime, 'id': 7, … -
connecting the views to the my models in Django
I have this data: [ { "x": -1.31242086143345, "y": 0.40178573392332, "z": -1.02033965707123, "ts": 1580485700059, }] I posted this data and I received this data with this code in my views: def save_acc(request): accelerometer_data = json.loads(request.read()) return JsonResponse(accelerometer_data,safe=False) I created my model according to each element of the first data: from django.db import models class accelerometer_data(models.Model): x = models.DecimalField(max_digits=30, decimal_places=10) y = models.DecimalField(max_digits=30, decimal_places=10) z = models.DecimalField(max_digits=30, decimal_places=10) ts = models.DecimalField(max_digits=30, decimal_places=10) So, in mysql database the name of table is accelerometer_data and there are 5 columns:id, x , y ,z ,ts I just need whenever, I post data to my app, I need directly save data to my database. I think I have to connect my views to my models, for this problem but I do not know how I can do this, thanks for yor help -
Send Context to base template using django templates
Hi i have a ( base template) and need to display all sections in a drop-down-list so how can i send a context with the Section objects to display them in a for loop ? <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> {% for sec in Sections %} <a class="dropdown-item" href="#">{{sec.section_name}}</a> {% endfor %} </div> -
Django ORM multiple table join with AbstractUser
I googled but got confused in multiple table join (with 1:1, 1:n, and n:m relations). My models looks like this: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Event(models.Model): owner_events = models.ForeignKey(User, on_delete=models.CASCADE, related_name='events') name = models.CharField(max_length=30) date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): # defekt return reverse('event_detail', kwargs={'pk': self.pk}) return self.name def get_event(self): name = escape(self.name) date = escape(self.date) return "Name: " + str(name) + " Datum: " + str(date) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) interests = models.ManyToManyField(Subject, related_name='interested_teachers') matches = models.ManyToManyField(Match, related_name="teacher_matches") def __str__(self): return self.user.username def get_events(self): return "Name: " + str(self.events.name) + "Date: " def get_events_adr(self): return self.events def get_interests(self): return "Interests: " + str(self.interests.name) Here this is how the tables look like in the db: Classroom_Event Classroom_Teacher Classroom_User In views I want to have events (event_id, name, date) and teachers information (user_id, name) displayed. In SQL it would be something like this: select classroom_event.id, classroom_event.name, classroom_event.date, classroom_user.id, classroom_user.username from classroom_event left join classroom_user on classroom_event.owner_events_id = classroom_user.id left join classroom_teacher on classroom_user.id = classroom_teacher.user_id -
Python 2 script in Django 3
I have a script that uses a library that is not available in python 3. I used the answer (execnet) to this question to call the python 2 script X from a python 3 script Y. This works fine without any problem. I added both scripts to the directory of the Django app I want to use script X in. Testing script Y still works. Importing script Y to be called from views.py works. Calling the function in Y form views.py works. But now script Y does not find script X anymore. The Django error says ImportError: No module named X If I add the script n the settings.py script to INSTALLED_APPS I get ModuleNotFoundError: No module named 'X'. Is there an easier way to run a python2 script froom django 3? -
How to update Django model's pre-existing record during creation of a new one
In Django, is there a way to update an existing record while creating a new one with FK relationship to the same parent object. To elaborate, the scenario will be: Parent model A has a child model B. New records are added in model B for each instance of A On Save, before the new record is added in B, a Boolean field in the previous record is set to True. The update of the older record will happen along with creation of new record. If one were to fall back on legacy VB workflow, a dataset will have been created for all values of B for an instance (PK) of A --> Sort (asc) the dataset on PK of B --> Goto the last record of the dataset --> Change the boolean value of the hit --> Add a new record. How does one approach this scenario in Django? -
How to import an existing database in my Django project?
I'm trying to add an existing sqlite3 database to my Django project but it doesn't seem to be recognized. I've added that database to my project folder, modified the settings.py file to reflect that addition: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'added_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'added_db.sqlite3'), } } I then ran the 'python manage.py makemigrations' and the 'python manage.py migrate' commands but it doesn't seem to do anything. When I run 'python manage.py inspectdb', it only shows the tables within the default database. What am I missing? -
How do I create a custom user feed in Django?
I've been following Corey Schafer's tutorial series on Django but I still don't understand how basically any of it works. I've created a website and have 'post' objects, but I want each user to have their own feed of these posts with the ability to remove them from their feed. I need to save each user's feed to the database so I created a PostList model but I have no clue where to go from here. tag_choices1 = [ ('Animals', 'Animals'), ('Children', 'Children'), ('Disabled Persons', 'Disabled Persons'), ('Non-Profit', 'Non-Profit') ] tag_choices2 = [ ('Education/School', 'Education/School'), ('Homeless Aid', 'Homeless Aid'), ('Manual Labor', 'Manual Labor'), ('Nature', 'Nature'), ] class Post(models.Model): title = models.CharField(max_length=50) description = models.TextField(max_length=500) date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) tag1 = models.CharField( choices=tag_choices1, default='', max_length=7, blank=True ) tag2 = models.CharField( choices=tag_choices2, default='', max_length=7, blank=True ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class PostList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) post_list = [Post.objects.all()] -
Django Migration using a OneToOneField
Migration for a OneToOneField returns an error as follows : MySQLdb._exceptions.OperationalError: (1824, "Failed to open the referenced table 'auth_user'") My models are as follows : class Employer(models.Model): emp_Name = models.OneToOneField(User, on_delete=models.CASCADE, null=True) emp_Company = models.CharField(max_length=100) def __str__(self): return self.emp_Name I have two database routers one for the [auth, session, admin and contenttypes] and the other for the main app. It works for ForeignKey. I am creating a job portal and require the employer to be able to login too. -
How to switch my website from HTML to Django?
I want to switch my website from HTML to django, i completed the website by html and CSS and having some trouble to switch between HTML files and the design in not proper, so is there a way to change my website to django. -
Django template radio button auto select
I am developing an app with django. Here is the screenshot. I need to know when user will select on a plan in the next page that plan radio button should auto select. I am able to grab all the information regarding the selected plan but dont understand how to select that plan's radio button. here is the screenshots. Let me know anyone has the answer. here is the next image where the radio buttons are present. -
using objects.latest in DRF queryset raises error
I have the following view: from rest_framework.viewsets import ModelViewSet from .serializers import LocationInfoSerializer from .models import LocationInfo class LocationInfoViewSet(ModelViewSet): queryset = LocationInfo.objects.latest() serializer_class = LocationInfoSerializer using this api raises the following error: TypeError at /locations/ 'LocationInfo' object is not iterable But if I change the queryset to: class LocationInfoViewSet(ModelViewSet): queryset = LocationInfo.objects.all() serializer_class = LocationInfoSerializer -
How to use the ajax response data to fill Multiple ManyToManyFields in django
1.I am a Django learner. 2.I don't have much knowledge on jquery & Ajax. 3.I have two models ModelRegister and ModelGSPRequest in Models.py. 4.I have a requirement to populate 2 ManyToManyFields in ModelGSPRequest with the data based on selected drop down value,which is a Foreign Key to ModelRegister. 5.To accomplish this requirement ,i have written an Ajax function named load_model_details which triggers when there is a change in the model name drop down selection. Through this method i.e.,load_model_details i got all the model instances for the selected model & then i am passing it as a context to model_info_options.html to get the model number and OS Name details for the selected model. 6.When i select Model Name, Model Number and OS Name fields are filled with both the details which is not as per expected. i.e,For example if user selectedmodel name:G5 modelNumber filled with H850,H860,O and P. But it should contain only H850,H860 . Similarly os name filled with H850,H860,O and P but it should be only O and P. 7.So , Please suggest the proper way of accessing the response data in success method to display the correct data as per expected. Models.py: --------- class ModelRegister(models.Model): 'This class is … -
Django, Is it okay to combine the Insert and Update in one class?
I have class grades(models.Model) , I just wonder if it is okay to combine the insert and update into a single class, if the system detect the user is exist it will go to update and if not go to insert, any ideas? if request.method == 'POST': def grades(request): global gradekos, dates, averages id = request.POST.get('teacher') teacher = EmployeeUser(id=id) category_id = request.POST.get('category') category = gradingCategories(id=category_id) subject_id = request.POST.get('subject') subject = Subject(id=subject_id) ave=request.POST.get('gradeko') grade_id = request.POST.get('grade') grade = EducationLevel(id=grade_id) student = request.POST.get('students') students = StudentsEnrolledSubject(id=student) periods = request.POST.get('period') period = gradingPeriod(id=periods) gradekos = [] dates = [] averages = [] for average in request.POST.getlist('average'): averages.append(average) for gradeko in request.POST.getlist('gradeko'): gradekos.append(gradeko) for date in request.POST.getlist('date'): dates.append(date) i = 0 h = 0 for single_date in dates: for student in request.POST.getlist('students'): studentInsert = StudentsEnrolledSubject(id=student) insert_data = studentsEnrolledSubjectsGrade( Teacher=teacher, Students_Enrollment_Records=students, Date=single_date, Grade=gradekos[i], Grading_Categories=category, Subjects=subject, ) insert_data.save() update = studentsEnrolledSubjectsGrade(id=student) update.Teacher=teacher, update.Students_Enrollment_Records=students, update.Date=single_date, update.GradeLevel=grade, update.Grade=gradekos[i], update.Grading_Categories=category, update.grading_Period=period, update.Subjects=subject, update .save() i += 1 -
i got this error NOT NULL constraint failed: accounts_user.password, need your guidance
so the problem is when i try to register this error show up : django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_user.password i tried to migrate and did all recommended things like migrations but it didn't work any idea ? any help guys ? this is my files views.py from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import authenticate,login,logout from django.views.generic import FormView,TemplateView,ListView from django.conf import settings from .forms import RegisterForm from .models import User # Create your views here. #user-login view def register(request): registred=False if request.method=="POST": user_register=RegisterForm(data=request.POST) if user_register.is_valid(): username=user_register.cleaned_data.get('username') email=user_register.cleaned_data.get('email') password=user_register.cleaned_data.get('password1') user=User.objects.create(username=username,email=email,password=password) user.set_password(user.password) user.save() registred=True return HttpResponseRedirect(reverse('index')) else: return HttpResponse('there is a problem') else: return render(request,'register.html',{'registred':registred,'user_register':RegisterForm}) def user_login(request): if request.method=='POST': email=request.POST.get('email') password=request.POST.get('password') user=authenticate(email=email,password=password) if user is not None: return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account not found") else: return render(request,'login.html') #user-logout view @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) #registration view forms.py: # accounts.forms.py from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields = ('email','username','full_name','short_name','password') def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username).exists(): raise forms.ValidationError('This username already exists') return username def clean_email(self): email = self.cleaned_data.get('email') … -
Django saving data from html field to database
I am new to Django, I am trying to take input from user using html generated text field and not use django forms. <form action="" method="post"> { % csrf_token % } <label for="name">Enter name: </label> <input id="namefield" type="text" name="name_field" value="Default name"> <input type="submit" value="OK"> </form> I want to save the name to my database, without creating a django form and taking in data from the form and saving it in the database via views.py file. -
How to set background image in django html template?
Here is my html code <div class="m-grid__item m-grid__item--fluid m-grid m-error-5" style="background-image: url('{% static "Default/assets/images/bg5.jpg" %}');"> <div class="m-error_container"> <span class="m-error_title"> <h1> Oops! </h1> </span> <p class="m-error_subtitle"> Something went wrong here. </p> <p class="m-error_description"> We're working on it and we'll get it fixed <br> as soon possible. <br> You can back or use our Help Center. </p> </div> </div> Here is the code in settings.py STATIC_DIR = os.path.join(BASE_DIR, "UI") # path for the static files i.e css, JS, images STATICFILES_DIRS = [ STATIC_DIR, ] And following is the folder hierarchy MySchoolSpace --> Project Folder MySchoolSpace --> Folder contains settings.py etc. UI Default assets images bg5.jpg styles scripts manage.py db.sqlite3 -
Django Cannot Save the Form
I want to create a patient form for my system. I entry all values but it cannot save the patient. Where is my mistake? There is no error as I can see. When I push the "save" button nothing happens and it opens the same form page. [23/Feb/2020 16:21:24] "GET / HTTP/1.1" 200 2168 [23/Feb/2020 16:21:24] "GET /static/css/home.css HTTP/1.1" 200 2512 [23/Feb/2020 16:21:27] "GET /create/ HTTP/1.1" 200 4740 [23/Feb/2020 16:21:44] "GET /create/ HTTP/1.1" 200 4740 [23/Feb/2020 16:21:44] "GET /create/ HTTP/1.1" 200 4740 Thanks for your attention. views.py def patient_create(request): if not request.user.is_authenticated: return render(request, "http404.html") form = PatientForm(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() messages.success(request, "Başarılı bir şekilde oluşturdunuz.", extra_tags='mesaj-basarili') return HttpResponseRedirect(post.get_absolute_url()) context = { 'form': form } return render(request, "patient_form.html", context) models.py class newPatients(models.Model): title = models.CharField(max_length=100) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) dept = models.TextField() address = models.TextField() phone = models.CharField(max_length=15) notes = RichTextField(verbose_name="notes") def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_create_url(self): return reverse('post:create', kwargs={'slug': self.slug}) def get_unique_slug(self): slug = slugify(self.title.replace('ı', 'i')) unique_slug = slug counter = 1 while newPatients.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def save(self, *args, **kwargs): … -
How to open Python script in Django
i have a script in python, which is working good (in few words you can type name of footballer, then script is looking for him on one website, get a link of this footballer profile and then scrap something, for example birthdate, but this is not important for now). I would like to use it on my Django website, but i got stuck. This is what i have now: urls.py: path('scraping', views.scraping, name='scraping'), path('scrapingscore', views.scrapingscore, name='scrapingscore'), views.py: def create_request(url): req = Request( url, data=None, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) return req def get_request(req): return urlopen(req).read() def scraping(request): rootlink = 'https://www.transfermarkt.pl' link = 'https://www.transfermarkt.pl/schnellsuche/ergebnis/schnellsuche?query=' # data=request.POST.get("textfield") # i commented it when i created form data = SearchForm(request.POST) data = data.replace(" ", "+") print(data) search = link + data + '&x=0&y=0' print(search) soup = BeautifulSoup( get_request(create_request(search)), features="lxml" ) anchor = soup.find("a",{"class":"spielprofil_tooltip"}) link = anchor.get("href") original_link = rootlink + link response = requests.get(original_link).text soup1 = BeautifulSoup(response, 'html.parser') links = soup1.find("span", itemprop="someClass").text # not important now, just example return HttpResponseRedirect('scrapingscore') def scrapingscore(request): return render_to_response('scrapingscore.html') forms.py: class SearchForm(forms.Form): search = forms.CharField(label='search', max_length=100) scraping.html: {% extends "base.html" %} {% block content %} <form action="{% … -
my form in Django doesn't appear in same template
hi i am facing problem here..i want to show comment form in same template the comment show ... the code here it shows the comments but doesn't show the forms ...i added the comments from adminsite directly to see if the comment show up please help.. this is my code models.py class Comment(models.Model): medicine = models.ForeignKey('medicine_1.Medicine', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text views.py def add_comment_to_post(request, pk): medicine = get_object_or_404(Medicine, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = medicine comment.save() return render(request, 'medicine.html', {'medicine': medicine , 'comment':comment,'form': form}) else: form = CommentForm() return render(request, 'medicine.html', {'form': form}) urls.py url(r'^(?P<medicine_id>[0-9]+)/$', views.add_comment_to_post, name='add_comment_to_post'), forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) html template medicine <form method="POST" action="{% url 'medicine_1:add_comment_to_post' medicine.id %}">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Send</button> </form> the output look like: -
(DJANGO) NoReverseMatch at post/<slug:slug>
I'm trying to implement comments form in my Django Blog. I was going through this tutorial(https://djangocentral.com/creating-comments-system-with-django/), but there is an error happened in the end. The error page is saying: NoReverseMatch at /post/firstpost/ Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user\/(?P[^/]+)$'] urls.py from django.urls import path from django.conf.urls import include, url from . import views from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView urlpatterns = [ #Blog section path("", PostListView.as_view(), name='blog-home'), path("user/<str:username>", UserPostListView.as_view(), name='user-posts'), path('post/<slug:slug>/', views.post_detail, name='post-detail'), path("posts/new/", PostCreateView.as_view(), name='post-create'), path("post/<slug:slug>/update/", PostUpdateView.as_view(), name='post-update'), path("post/<slug:slug>/delete/", PostDeleteView.as_view(), name='post-delete'), path("about/", views.about, name="blog-about"), path("<category>/", views.blog_category, name="blog_category"), ] models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) forms.py from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') admin.py from django.contrib import admin from .models import Post, Category, Comment class CategoryAdmin(admin.ModelAdmin): pass @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'created_on', 'active') list_filter = ('active', 'created_on') search_fields = ('name', 'email', 'body') actions = ['approve_comments'] def approve_comments(self, request, queryset): queryset.update(active=True) admin.site.register(Post) admin.site.register(Category, CategoryAdmin) views.py def post_detail(request, … -
Django - password validation helpt text translation
I notice that it's possible that some password valildators do not have Russian language help_text default translation. Or they do just I do not know how to use it. In setting.py, LANGUAGE_CODE = 'ru', AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # this validator's help_text is not translated: Your password can’t be too similar to your other personal information. }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', # This validator's help_text is translated: Ваш пароль должен содержать как минимум 8 символов. }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] only MinimumLengthValidator displays translated help_text in Russian. others still display English. I wonder how to customise it? anyone can help? Thanks!! -
Can I add in a function that will send automatic emai?l
I want to put in a function that will send automatic email 20 days before the contract ends. Below set-up i am receiving an error - ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Here is my code: Model: class Client(models.Model): enter code hereclient_name = models.CharField(max_length=300) address = models.CharField(max_length=300) start_date = models.DateField(default=datetime.now, blank=True) end_date = models.DateField(default=datetime.now, blank=True) created = models.DateTimeField(auto_now_add=True) ACTIVE = 'AC' TO_EXPIRE = 'TE' EXPIRED = 'EX' STATUS_CHOICES = [ (ACTIVE, 'Active'), (TO_EXPIRE, 'To Expire'), (EXPIRED, 'Expired'), ] status = models.CharField(max_length=2, choices=STATUS_CHOICES, default=ACTIVE) user = models.ForeignKey(User, on_delete=models.CASCADE) Views from django.shortcuts import render, redirect, get_object_or_404 from .models import Client from .forms import ClientForm from datetime import date from dateutil.relativedelta import relativedelta from django.core.mail import send_mail def client(request): clients = Client.objects.all() for client in Client.objects.filter(end_date=date.today() + relativedelta(days=5)): send_mail('Contract to be Expired!', 'A Gentle Reminder', 'gilzgetuya@gmail.com', ['gilbert.g@akigroup.com'], fail_silently=False) return render(request, 'client/client.html', {'clients': clients})e -
Django CSRF verification failed Request aborted
Html body is like : <div id="login"> {%if id == 2 %} <form action="{%url 'User:mainPageBridge'%}" method="post"> {% csrf_token %} <h1>Welcome Back!</h1> <div class="field-wrap"> <a style="color:#ffffff">Email :</a> {{form.username}} </div> <div class="field-wrap"> <a style="color:#ffffff">Password :</a> {{form.password}} </div> <p class="forgot"><a href="{%url 'User:login' id=3%}">Forgot Password?</a></p> <button type="submit" class="button button-block"/>Log In</button> </form> {%else%} <form action="{%url 'User:passwordReset'%}" method="post"> {% csrf_token %} <h1>Forget Password</h1> <div class="field-wrap"> <a style="color:#ffffff">Username : </a> {{form.username}} </div> <button type="submit" class="button button-block"/>Send Mail</button> </form> {%endif%} </div> As you can see, I added the csrf_token in two forms as a child of form tag. I just wanna create a form.The part where I take error, is after '{% else %}' statement. Even thought I add everything needed, it throws this error : CSRF token missing or incorrect