Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send a POST request to the server from Fetch API? Examples don't work
I can't send a post request to the server. For some reason, the reguest.POST on the server is empty. Below are code examples JS on front let weekends = [] await fetch('{% url "get_weekends" %}', { method: 'POST', headers: new Headers({'Accept': 'application/json', 'Content-Type': 'application/json'}), params: {after: after_str, before: before_str} }).then(function (response) { return response.json(); }).then(function (data) { if (data['status'] === 'ok') { weekends = data['weekends'] } else { console.error(data) show_error('Не удалось получить список ваших выходных! Ошибка в статусе!') } }).catch(function (e) { console.error(e) show_error('Не удалось получить список ваших выходных! Не удалось выполнить запрос!') }); after_str and before_str saved str data (01.12.2021 and 31.12.2021) Python on backend def get_weekends_view(request): """ Вью возвращает список выходных пользователя в заданном промежутке времени """ form = GetAfterAndBeforeForm(request.POST) if form.is_valid(): after, before = form.cleaned_data['after'], form.cleaned_data['before'] result = [] for weekend in Weekend.objects.filter(user=request.user, date__range=(after, before)): result.append({'date': weekend.date.strftime('%d.%m.%Y'), 'status': weekend.get_status_display()}) return {'status': 'ok', 'weekends': result} else: return {'status': 'error', 'msg': 'Форма заполнена не верно! ' + str(request.POST)} forms class GetAfterAndBeforeForm(forms.Form): after = forms.DateField() before = forms.DateField() -
Connecting Python Bot to Django and frontend
I've created a simple python bot and talks some defined commands, since it's in a particular python file (.py file). Is there anyway I can link it to my Django framework? Like if I click on some button, particular python file will execute is there anyway to do so? If there are any specific library please let me know. -
Retrieving data from Django HTML form and passing it to a MySQL database
I have a database with multiple user names and phone numbers attached to each user. On the Django template that I created the user is presented with a list of names, and the user can click on a name, or multiple names, and the database is to respond with the phone number assigned to the name. However, I am using a for loop within the Django template to iterate over the names in the database to display for the user, as the count can change. It works correctly when I select one name, however, if I select multiple name, it takes the last name selected versus displaying all names. This error is due to my for loop solution which has the same "name" assigned to all inputs. Anyone have an idea on how I can approach this? My View form: def select_contact(request): alldata = identity_log.objects.values_list("first_name", flat=True) #https://docs.djangoproject.com/en/4.0/ref/models/querysets/ checkform = contact_form(request.POST or None) context = {'alldata': alldata} print(checkform) display_type = request.POST.get("contact_option", None) if display_type in alldata: print(display_type) return render(request, 'message_me/select_contact.html', context) My template: {% extends "base.html" %} {% load static %} {% block body %} <p>Please select your favorite Web language:</p> {% for x in alldata %} <form id="contact_option" role="form" action="" … -
Django retrieving env var fails on ElasticBeanstalk
I deployed my Django app using ElasticBeanstalk. When I access the top page I get 502 error. My log shows raise KeyError(key) from None KeyError: 'MY_APP_SECRET' in my settings.py. I double checked that value for MY_APP_SECRET is set on ElasticBeanstalk console. It seems Django at least sees DJANGO_SETTINGS_MODULE env var. How can I make it work? -
How to solve net::ERR_TIMED_OUT in axios post call?
Axios.post(`https://16.16.6.1:8000/api/login`, { username: "userName", password: "password" }) .then(res => { console.log("Logging in") }) .catch(err => { console.log(err) alert(err.message) }) Earlier I used to use backend which was running in my own system so used to use localhost or window.location.hostname in place of specific hostname address like "16.16.6.1". I wanted to access the Django server running on this host, it was giving me this error. -
Drf how to: simple-jwt authenticating without the USERNAME_FIELD
I have extended the TokenObtainPairSerializer, my user model has the email as the USERNAME_FIELD but this type of user does not have an email instead I want to use an auto-generated unique id to authenticate in place of the email. class MyTokenStudentSerializer(TokenObtainPairSerializer): def validate(self, attrs): user = authenticate()( student_id=attrs['student_id'], password=attrs['password']) if user is not None: if user.is_active: data = super().validate(attrs) refresh = self.get_token(self.user) refresh['student_id'] = self.user.student_id try: data["refresh"] = str(refresh) data["access"] = str(refresh.access_token) data['student_id'] = self.user.student_id data['firstname'] = self.user.firstname data['middlename'] = self.user.middlename data['lastname'] = self.user.lastname data['phone'] = self.user.phone data['last_login'] = self.user.last_login data['joined_date'] = self.user.joined_date except Exception as e: raise serializers.ValidationError( {'error': 'Something Wrong!'}) return data else: raise serializers.ValidationError( {'error': 'Account is not activated'}) else: raise serializers.ValidationError({ 'error': 'Incorrect student id and password combination!'}) even tho i don't pass an email field this takes email and password, how do i get it to take the student_id instead of the email. -
How to get previous Date can anyone please? Actually I m working on Blood donation project
#Models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.IntegerField() cnic = models.CharField(max_length = 13) blood_group = models.CharField(max_length= 10) last_donation = models.DateTimeField(auto_now_add=True) #Views.py from django.shortcuts import render from .models import * from .forms import UserForm from datetime import datetime,timedelta from django.contrib import messages def home(request): return render(request, 'home.html') def donor(request): if request.method == "POST": userform = UserForm(request.POST) if userform.is_valid(): userform.save() else: userform = UserForm() return render(request, 'donor.html',{'userform':userform}) #forms.py from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import User from datetime import datetime,timedelta from django.shortcuts import render class UserForm(ModelForm): class Meta: model = User fields = "__all__" def clean_cnic(self): cnic = self.cleaned_data['cnic'] print("This is a cnic",cnic) if User.objects.filter(cnic = cnic).exists(): # i want to get previous date Actually I m working on Blood donation project. first time user will come he or she entered data and the date will automatically add Beacuse it is auto_now_add. Again the same user will come and entered data I will match the CNIC if user is exist if user exist then I have to get previous date and after getting previous date I have to minus previous date from current date to check it completed 90 days … -
Testing firebase push notification
I have done some setup looking at the documentation of django-fcm and wrote the following scripts. Now, I havent done the frontend part, but want to test it locally. Is there anyway we can test it from the localhost console like using curl request? My code: class PushNoti(models.Model): message = models.TextField(blank=True) notify_time = models.TimeField(blank=True) My view: #fcm firebase from firebase_admin.messaging import Message,Notification from fcm_django.models import FCMDevice message = Message( notification=Notification(title="title", body="text", image="url")) class NotificationView(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): data= request.data serializer = self.serializer_class(data=data) if serializer.is_valid(): serializer.save() device = FCMDevice.objects.all() device.send_message(title="Title", body="Message",message=message,icon=None, data={"test": "test"}) FCMDevice.objects.send_message(message=message) return Response(serializer.data,status=200) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) When I call the post api the pushnoti object gets created without any error but I am not sure whether the notification is being sent to the channel or not. Also in setting file: INSTALLED_APPS = ( ... "fcm_django" ... ) FIREBASE_APP = initialize_app() FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "[string for AppConfig's verbose_name]", "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, "UPDATE_ON_DUPLICATE_REG_ID": True, } Also, in the doc FCM_DJANGO_SETTINGS doenst have any server key field. Dont we need to provide a server key in the settings generated from the firebase?? -
Cannot resolve keyword 'book_hex' into field
I'm using Django. Instead of using a PrimaryKey to identify separate books, I thought of using a code to distinguish two books. I've implemented a random 10-digit code generator and I've plugged it in to the urlpatterns and functions. That all works. But now I can't access the code of a book in a ForeignKey as I could access id with the underscore in front: r = UserRents.objects.get(book_code=code) Django gives the following error: FieldError at /main/accept_rent_request/tQYMlQMIFM/ Cannot resolve keyword 'book_code' into field. Choices are: book, book_id, creation_date, id, status, user, user_id Here's the UserRents model: class UserRents(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) status = IntegerField(default=0) creation_date = models.DateTimeField(default=timezone.now) updation_date = 0 # Change to models.DateTimeField(default=timezone.now) when updated def __str__(self): return self.book.title How can I access the code property of the book to which the UserRents table is ForeignKeying to? -
Django Alluth Authentication Error in Production
I have integrated Google Login on production site. Basically Backend-Django(port-8000),Frontend-React(port-3000) inegration. I have manage successfully login with google login on http://example.com:8000/accounts/login/ But on Frontend its shows error. http://example.com:3000 ERROR is Now on my Google OauthId credentials are Authorized JavaScript origins http://example.com:8000 http://example.com:3000 Authorized redirect URIs http://example.com:8000/accounts/google/login/callback/ The error is not understanble for me as i am new to django world. Can someone guide me. -
How can i fix this error with using captcha in django?
My code[python version=3.10, django version=4.0]: def get_code(request): img = ImageCaptcha(200, 100) im = img.generate_image(chars='1234') fp = BytesIO() im.save(fp, 'png') return HttpResponse(fp.getvalue(), content_type='image/png') Error: TypeError at /get_code/ 'float' object cannot be interpreted as an integer Request Method: GET Request URL: http://localhost:8000/get_code/ Django Version: 4.0 Exception Type: TypeError Exception Value: 'float' object cannot be interpreted as an integer -
How to use multiple filters in same field in django?
I am trying to filter the same filed on different values. example of my API is- example.com/deals?store=amazon&store=flipkart&country=india I am using django-filter in the backend. Here is my code. class DealsList(generics.ListAPIView): throttle_classes = [UserRateThrottle] serializer_class = DealModelSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] queryset = DealsModel.objects.all() filterset_fields = ['category','store', 'price', 'highest_price', 'is_all_time_low', 'discount','rating','product__country'] search_fields = ['product_name','category','store'] pagination_class = CursorSetPagination def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) serializer = self.get_serializer(page, many=True) data = [] for item in serializer.data: lst = list(item.items()) # buy_url = Scrapper(lst[3][1]) # item['buy_url'] =buy_url.ConverttoAff() data.append(item) return self.get_paginated_response(data) When I am trying to filter the same field with multiple values it only shows the result of the first field. for example- example.com/deals?store=amazon&store=flipkart&country=india Here it filters out only the amazon stores, not flipkart. What is the best way to filter it out as per the requirements? -
Django filter column with OR statement
I found a question very similar to this one but that one did not specify how to return a specific column and I have been trying combinations for the past few hours with no luck. home_team_list2 = PreviousLossesNbav1WithDateAgg.objects.values_list('actual_over_under_result_field', flat=True).filter(Q(away_team_field="Chicago") | Q(home_team_field="Chicago")) This does not throw me any errors but it does not return anything. I am attempting to return that specific column from my models filtering on away team or home team equal to "Chicago" -
Django form_valid() doesnt work for registration
I'm Try to create Registration Form With Django. But When i try, Form Doesn't Work, The Data not send to Database. I Know Why the form can't work, because method form_valid is not working. My Question Is How do i know it's not working ? Where i found the error ?. This is my code. models.py class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.full_name forms.py class RegistrationForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['full_name'].widget.attrs.update({ 'required' : '', 'type' : 'email', 'placeholder' : 'Nama Lengkap Anda', }) self.fields['email'].widget.attrs.update({ 'required' : '', 'type' : 'text', 'placeholder' : 'emailanda@universitasmulia.ac.id', }) self.fields['password1'].widget.attrs.update({ 'required' : '', 'type' : 'password', 'placeholder' : 'Password', }) self.fields['password2'].widget.attrs.update({ 'required' : '', 'type' : 'password', 'placeholder' : 'Konfirmasi Ulang Password', }) class Meta: model = Account fields = ("full_name", "email", "password1", "password2") views.py class RegistrationView(FormView): template_name = 'authentication/registration.html' form_class = RegistrationForm success_url = '/authentication' def form_valid(self, form): messages.success(self.request, 'Please Check Your Email For Infomation Detail!') print('Success Created Your Account') registration.html <form method="POST" class="register-form" id="register-form"> {% csrf_token %} <div class="form-group"> … -
What should i learn and how?
I want to become full stack developer and i want to learn HTML, CSS, JS and DJANGO(Python). which one i have to learn first and give how much time to each language. HTML CSS JS DJANGO -
Django ModuleNotFoundError: No module named 'my_app_name' while loading WSGI on ElasticBeanstalk
I'm trying to deploy my Django app to ElasticBeanstalk. I deployed my app without errors but when I access the root page it show 502 error and the log shows ModuleNotFoundError: No module named 'my_app_name' How can I solve this? Logs Dec 16 01:16:26 ip-172-31-43-109 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Dec 16 01:16:26 ip-172-31-43-109 web: return util.import_app(self.app_uri) Dec 16 01:16:26 ip-172-31-43-109 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/gunicorn/util.py", line 359, in import_app Dec 16 01:16:26 ip-172-31-43-109 web: mod = importlib.import_module(module) Dec 16 01:16:26 ip-172-31-43-109 web: File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module Dec 16 01:16:26 ip-172-31-43-109 web: return _bootstrap._gcd_import(name[level:], package, level) Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 983, in _find_and_load Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 677, in _load_unlocked Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap_external>", line 728, in exec_module Dec 16 01:16:26 ip-172-31-43-109 web: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed Dec 16 01:16:26 ip-172-31-43-109 web: File "/var/app/current/src/my_app_name/wsgi.py", line 18, in <module> Dec 16 01:16:26 ip-172-31-43-109 web: application = get_wsgi_application() Dec 16 01:16:26 ip-172-31-43-109 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application … -
500 error on one specific page. Apache2. Ubuntu 18
As a developer, I have to let you know that I'm a great fan of Stackoverflow. I have solved so many problems thanks to all of you! Currently, I'm struggling with a 500 error. I have been looking for a solution through this page and the web, but I haven't found anything. I recently created a web app using tesseract to extract text from images. I successfully deployed the website using Ubuntu 18 and Django. The thing is that when I installed Apache2 to use it as an HTTP server the page that loads the images and converts them to text sent me a 500 error. The access logs are: [17/Dec/2021:01:48:59 +0000] "GET /main-app/downloads/ HTTP/1.1" 500 417 [17/Dec/2021:01:49:03 +0000] "GET /main-app/downloads/ HTTP/1.1" 500 417 The error logs are: [wsgi:error] [pid 755:tid 139986828527360] [wsgi:error] [pid 755:tid 139986761361152] in regards to how the page handles the request: file_path =os.path.join(BASE_DIR, file_url) str(file_path) if os.path.exists(file_path): path = open(file_path, 'r') mime_type, _ = mimetypes.guess_type(file_path) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) # Just in case: "attachment; filename=%s" % '.csv' return response else: raise Http404 Just to let you know, I have granted 775 permissions to the folders that handle the app and … -
Assigning value to variable inside for loop
I have a for loop that goes through a list of cities as well as their broad variables (safety, affordability, transit, etc). If there's a match between the city's broad&specific variable and the broad&specific variable the user selects on the page then it assigns a weighted value else the value is 0. I am trying to add the values for each broad variable in the list but I get the error local variable 'city_variable1_value' referenced before assignment When I reference city_variable1_value and city_variable2_value as 0 before the first if statement then my total_city_value = city_variable1_value + city_variable2_value equals 0 when it should be 0.24 for example. The code is below! # list of each variable's broad category broad_variable_list = ["safety", "affordability", "transit", "language", "attractions"] # weighting of each variable ranking weight_variable1 = 0.33 weight_variable2 = 0.24 weight_variable3 = 0.17 weight_variable4 = 0.14 weight_variable5 = 0.12 def get_ranking(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = RankingForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required specific_variable1 = form.cleaned_data['specific_variable1'] specific_variable2 … -
Errors in rendering booklist to templates
from django.http import HttpResponse booksList = [ { 'id' = '1', 'title' = "Beginner's Course in Django", 'description' = 'Foundational Course in Django'} { 'id' = '2', 'title' = "Intermediate Course in Django", 'description' = 'Next steps in Django' }, { 'id' = '3', 'title' = "Advanced Course in Django", 'description' = 'The complexities of Django' }, ] I am I am rendering data to a template using the above bookList and getting two errors: '[' was not closed Pylance and '{' was not closed Pylance Kindly advise. -
Django Forms, Class LoginForm(User): str() argument 'encoding' must be str, not tuple
I Got Error, class LoginForm(User): TypeError: str() argument 'encoding' must be str, not tuple. My Question, How To Call "AUTH_USER_MODEL" from forms.py. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.full_name settings.py #User model AUTH_USER_MODEL = 'authentication.Account' forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.conf import settings from .models import Account User = settings.AUTH_USER_MODEL class LoginForm(User): pass -
Django Media File Not Showing in Bucket
I have an issue trying to get my bucket to display both folders media and static. Currently when I collectstatic it only gets from static and not media. So It can obtain static from the bucket but not media files yet. How do I get media to show in my bucket? Policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicRead", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject", "s3:GetObjectVersion", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::<AWS_STORAGE_BUCKET_NAME>/*" } ] } with the following settings.py # All of this is in my console.aws.amazon to configure aws s3 static files only # If I am in prod # IAM Management Console AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') # Amazon S3 Buckets AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = None AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = 'us-east-2' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] AWS_STATIC_LOCATION = 'static' STATICFILES_STORAGE = 'portfolio.storage_backends.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) """ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') """ AWS_PUBLIC_MEDIA_LOCATION = 'media/public' DEFAULT_FILE_STORAGE = 'portfolio.storage_backends.PublicMediaStorage' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' PRIVATE_FILE_STORAGE = 'portfolio.storage_backends.PrivateMediaStorage' # Fixes Found another file with the destination path """ STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', #'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9 … -
'list' object has no attribute '_meta' plese help me out i was stuck
enter image description here recently I want to edit the row of the table but stocked there for among 3 days help me out to get rid out of this -
Can't connect dat.gui in my javascript on my django server
I'm new in web dev and I´m trying to import the dat.gui package library in my javascript, but it isn't working :c I'm using python and django to make the server, and I used the mehtod that comes in the docs in the HTML downloading the package and writting the root manually. It seems to read the package in the html but I don't know why I can't do the samething on my Javascript. HTML: JAVASCRIPT: import * as DAT from '/package/build/dat.gui.min.js' -
No messages being sent by celery beat (using django-celery-beat)
I am in the process of upgrading to celery 5.x for a Django project. Since there is no longer a @scheduled_task annotation, I changed all of those to @shared_task and wrote some code to create CrontabSchedule instances and associate PeriodicTask instances with those for each task that should run on a schedule. I am invoking that from a beat_init signal receiver. I'm running celery worker & beat as separate processes. I am logging info from the function that sets up the CrontabSchedule and PeriodicTask instances, and I see that log output from the celery beat process. Immediately after that, I see a DatabaseScheduler: Schedule changed." message. That's all as expected and good. Subsequently, however, celery beat just sits and does nothing. beat never sends any messages, and as a result, celery worker never executes any scheduled tasks. In django-admin shell_plus, PeriodicTask.objects.all() shows me many scheduled tasks with schedules that all look as they should. Here's 1 example from the output that should be running once per minute, every day: <PeriodicTask: dhnetwork.tasks.send_queued_mail: {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59} {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23} * {1,2,3,4,5,6,7,8,9,10,11,12} {0,1,2,3,4,5,6} (m/h/dM/MY/d) America/Los_Angeles> Any ideas what I might be doing wrong and/or how to diagnose the problem? -
testing in Django
I am trying to test my Django application to get 100 % statement coverage. I Am using class-based view and overwriting some af the functionalities. One of them is the form valid in my AttendanceLogFormView in my views.py My question is how do I test that this method is working as it should with unit tests in Django? I am very new to testing so I very difficult for me to wrap me head around the concept I just know I need to test the if/else for statement coverage - but I don't know how? class AttendanceLogFormView(CreateView): model = AttendanceLog template_name = "attendancecode/Createattendancelog.html" form_class = AttendanceLogForm success_url = "/attendancecode/success/" # Checks if data input is valid and saves object def form_valid(self, form): obj = form.save(commit=False) user = "nadi6548" obj.date = date.today() getClass = Class.objects.get(name=obj.keaclass) getCourse = Course.objects.get(name=getClass.Course_name) getLocation = School.objects.get(id=getCourse.location_id) coords_1 = (getLocation.lat, getLocation.long) coords_2 = (obj.lat, obj.long) # check location and that student goes in the class if (geopy.distance.distance(coords_1, coords_2).km < 0.5) and Student.objects.get( username=user, Class_id=obj.keaclass): # check log is a code with correct info and correct date and that # student has subject + code is active if AttendanceCode.objects.filter( code=obj.attendanceCode, keaclass_id=obj.keaclass, subject_id=obj.subject_id, date=obj.date, isActive="True") and StudentHasSubject.objects.get( student_name_id=user, subject_name_id=obj.subject_id): …