Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you link form action to a view method?
In my rendered index.html, I have: <form action="???" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> In my views.py, I have: class weather(base.TemplateView): # Generates the above html def get_hours(request): # do something with request.Post return shortcuts.render(request, "index.html", {"form": form}) How do I make the form action call the get_hours? I want to post to the same page the form is on so the page won't refresh and will display the results on the same page. -
Django request header not in preflight response
my application uses angular for frontend and Django for the backend. The front end is sending data in a custom header called mobile. This are the request-headers from the frontend. Accept: application/json, text/plain, */* code: +1 Content-Type: application/json mobile: 1234678901 Referer: http://localhost:4200/ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 But I am getting an error like this. from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field mobile is not allowed by Access-Control-Allow-Headers in preflight response. I have also added the header to the CORS_ALLOW_HEADERS in my settings.py file. My settings.py file has something like this. from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ( 'mobile' ) But still I am getting the CORS error. What am I missing? Thanks in advance. -
I am trying to save attendance in my Django attendance app but keep getting TypeError, expected string or bytes-like object
I have tried everything. Checked several solutions on this platform, none have worked. Please help!! The error looks like this TypeError at /attendance/student/ expected string or bytes-like object Request Method: POST Request URL: http://127.0.0.1:8000/attendance/student/?reg_class=1 Django Version: 3.1 Exception Type: TypeError Exception Value: expected string or bytes-like object Exception Location: line 75, in parse_date Python Executable: C:\Users\Mrs Onajide\Desktop\school_management_system.venv\Scripts\python.exe Python Version: 3.8.3 My View from django.shortcuts import render, redirect from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .forms import SearchEnrolledStudentForm, AttendanceForm, DateForm from student.models import EnrolledStudent from academic.models import ClassRegistration from .models import StudentAttendance from django.forms.formsets import formset_factory def student_attendance(request): forms = SearchEnrolledStudentForm() class_name = request.GET.get('reg_class', None) if request.method == 'POST': class_info = ClassRegistration.objects.get(id=class_name) student = EnrolledStudent.objects.filter(class_name=class_name) count = student.count() attendance_formset = formset_factory(AttendanceForm, extra=count) formset = attendance_formset(request.POST) date = DateForm(request.POST) list = zip(student,formset) if formset.is_valid(): for form, student in zip(formset,student): mark = form.cleaned_data['mark_attendance'] StudentAttendance.objects.create_attendance(class_info.name, student.roll, mark, date) return redirect('home') My Model from django.db import models from academic.models import ClassRegistration from student.models import EnrolledStudent from django.utils import timezone class AttendanceManager(models.Manager): def create_attendance(self, std_class, std_roll, std_id, datel): std_cls = ClassRegistration.objects.get(name=std_class) std = EnrolledStudent.objects.get(roll=std_roll, class_name=std_cls) std_att = StudentAttendance.objects.create( class_name=std_cls, student = std, status = std_id, date = datel ) return … -
Speed of the django website after deploying it on heroku
I have deployed a django website on herokuapp (using free tier without having to pay anything) for testing.Currently when the site opens it takes a bit more time to open than the time it takes to open on localhost(127.0.0.1:8000).Also the images take a bit more time to load.My concern is that if I upload it on a platform such as digital ocean or linode or aws will I get the website to load in the same time as it is loading on heroku or there will be a better performance . Or is it the problem with the coding that is making it load slower. If that is the case please tell me ways so that I can get my website to load faster. -
I am unable to update two models at the same time in Django Views.py
I already ask questions related to this at How can I update first_name, last_name & email of Django model User and update other field in separate models But I'm not getting a proper solution. That's why I make this question similar to that one. I have pages.views.py: from django.shortcuts import render, redirect from .forms import CreateUserForm from accounts.models import Account from django.contrib import messages def signupPage(request): if request.user.is_authenticated: return redirect('/') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() # focus on this line Account.objects.create(user=user) messages.success(request, 'Signup success. Now, you can login.') return redirect('login') else: messages.warning(request, 'Signup failed. Please, try again.') context = {'form':form} return render(request, 'signup.html', context) Also, I have accounts.models.py: from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) # This field is used for to update django model User first_name=models.CharField(max_length=30, null=True, blank=False) last_name=models.CharField(max_length=30, null=True, blank=False) email = models.EmailField(max_length=30, null=True, blank=True) profile_photo = models.ImageField(upload_to='profile', null=True) mobile_number = models.PositiveBigIntegerField(null=True) date_of_birth = models.DateField(auto_now_add=False, auto_now=False, null= True) zip_code = models.IntegerField(null=True) address = models.CharField(max_length=225, null=True) website = models.URLField(max_length=100, null=True) bio = models.CharField(max_length=225, null=True) In Accounts.view.py: from django.shortcuts import render, redirect from .forms import AccountForm from .models import Account from … -
Django primary key prefix and length
I am looking to add a custom primary key to my models. Here is what i have so far. ticket_id = models.CharField(max_length=10, primary_key=True, editable=False) I basically want the primary key for each record to look like this, auto-incrementing from 001. AB001 AB002 AB003 AB004 How would I accomplish this? Many Thanks -
Django Session isn't getting updated appropriately
Stumbled upon the error message - The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. This error is popping up when rendering a django template (narrowed down the error to the line - return render(request, {})). This process involves uploading a file, running view logic, and presenting the results to the user. It worked for a good many files and is throwing this error for one specific file. The view logic involves a bunch of django session updates. Suspected that this error could be due to the huge session size. Ironically though, the size of the session as I checked in the DB is 120 MB, which sounds reasonable. Can you walk me through the possible issues that could have led to this error? Thanks in advance! -
Can't send API Requests from python code hosted on AWS Lightsail instance
I have a django website that is hosted on an AWS Lightsail. I am trying to add in a Speech to text tool in it. I have tried Google Cloud Speech to text as well as Microsoft Azure Speech to text APIs for this purpose and have used sample code from their websites. The code works fine when i'm running it on my localhost, but the same code does not work when hosted on that AWS Lightsail instance. There is no error, the reponse just never comes and the status stays on "pending.." Is there any log i can check for an error? Or is there any additional step required? Thank you in advance. -
Dynamic inheritance from Model
I have a Photo-Model that helps me achieve storing each image as a thumbnail aswell: class Photo(models.Model): image = models.ImageField(upload_to=upload_path, default=default_image) thumbnail = models.ImageField(upload_to=upload_path_2, editable=False, default=default_image_2) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Now I have another Model, lets call it User, which inherits from Photo: class User(Photo): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Now lets say there are multiple classes inheriting from Photo and depending on the inheriting class, I want to set another upload_path and default_image. How Do I achieve that? Can I somehow use the constructor? Thanks in Advance! -
How can I solve this problem in update crud in Django?
Well, I've been trying to solve this problem for days, at the time of performing the update crud, the form doesn't make me valid and the modified records aren't saved. Next I will show you how my code is in each module: views.py def modificarcurso(request,id): curso = Curso.objects.get(id=id) curso = CursoForm(request.POST, instance=curso) if curso.is_valid(): curso.save() return redirect("/mostrarcursos") return render(request, 'mostrarcursos.html', {'curso': curso}) forms.py class CursoForm(forms.ModelForm): class Meta: model = Curso fields=['docente','anio','paralelo','jornada'] models.py class Curso(models.Model): docente= models.ForeignKey(Docente,on_delete=models.CASCADE) anio = models.IntegerField(default=1) paralelo = models.CharField(max_length=1) jornada = models.CharField(max_length=20) user = models.CharField(max_length=100) user_mod = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) estado = models.IntegerField(default=1) # 1 es activo y 2 es eliminado class Meta: db_table ="Cursos" verbose_name ="Curso" verbose_name_plural ="Cursos" def __str__(self): return self.paralelo + ' ' + self.jornada Well, and in the html code the form is created where the records are entered with the name of each field. -
Not Found: /style.css/ , django
I'm trying to create my own website on Django, but some problems stop me and I can't solve them myself. I want to create a sidebar. I found a website with css and HTML code for it. style.css: @import url('https://fonts.googleapis.com/css?family=Montserrat:600|Open+Sans:600&display=swap'); *{ margin: 0; padding: 0; text-decoration: none; } .sidebar{ position: fixed; width: 240px; left: -240px; height: 100%; background: #1e1e1e; transition: all .5s ease; } .sidebar header{ font-size: 28px; color: white; line-height: 70px; text-align: center; background: #1b1b1b; user-select: none; font-family: 'Montserrat', sans-serif; } .sidebar a{ display: block; height: 65px; width: 100%; color: white; line-height: 65px; padding-left: 30px; box-sizing: border-box; border-bottom: 1px solid black; border-top: 1px solid rgba(255,255,255,.1); border-left: 5px solid transparent; font-family: 'Open Sans', sans-serif; transition: all .5s ease; } a.active,a:hover{ border-left: 5px solid #b93632; color: #b93632; } .sidebar a i{ font-size: 23px; margin-right: 16px; } .sidebar a span{ letter-spacing: 1px; text-transform: uppercase; } #check{ display: none; } label #btn,label #cancel{ position: absolute; cursor: pointer; color: white; border-radius: 5px; border: 1px solid #262626; margin: 15px 30px; font-size: 29px; background: #262626; height: 45px; width: 45px; text-align: center; line-height: 45px; transition: all .5s ease; } label #cancel{ opacity: 0; visibility: hidden; } #check:checked ~ .sidebar{ left: 0; } #check:checked ~ label #btn{ margin-left: … -
Why boto3 dose not recognize my AWS_ACCESS_KEY_ID in Django on EC2?
I was connecting the S3 to Django on EC2. I confirmed that it works on the my computer (window), but when I uploaded it to AWS EC2 Ubuntu and ran it, I saw the following message. when i ran python manage.py commands File "/home/ubuntu/django/e/lib/python3.6/site-packages/botocore/session.py", line 821, in create_client aws_secret_access_key)) **botocore.exceptions.PartialCredentialsError: Partial credentials found in explicit, missing: aws_secret_access_key** But I think I set it up correctly. in my settings.py AWS_S3_HOST = 's3.me-south-1.amazonaws.com' AWS_S3_REGION_NAME= config('AWS_S3_REGION_NAME') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_kEY = config('AWS_SECRET_ACCESS_kEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') I tried Give IAM permission on EC2 Delete EC2 retry set env var via export throw away virtualenv and try install awscli and configure it s3 bucket policy configure tried to write it inline because it might not be able to refer to the .env file, but it gave me same message. I struggled with this problem all day today. When it comes to AWS Config, I think I've tried everything I can. If you have any guesses about the cause of this problem, please give me a hint. And I only think boto3 looks up keys in a peculiar way on EC2 -
django what is best way to handle Exception in views
I have like 15 views , I dont want to add try, except for every view . Should I create a middleware or decorator or mixins or something else for error handling ? -
alternative option of blank=True in django model
I want to have a ForeignField that can be null some times depending on a BooleanField. so is this necessary to make it blank=true. Explaning the requirement: I have in models.py class InfaUsers(models.Model): first_name = models.CharField(max_length=30, default=None, null=True) last_name = models.CharField(max_length=30, default=None, null=True) ...[some more fields]... class DisputeUserRole(models.Model): corporate_party = models.ForeignKey(CorporatePartyNames, on_delete=models.CASCADE, default=None, null=True) party_name = models.CharField(max_length=100, default=None, null=True) is_individual = models.BooleanField(default=True) infa_user = models.ForeignKey(InfaUsers, on_delete=models.CASCADE) role = models.ForeignKey(UserRoles, on_delete=models.CASCADE) dispute = models.ForeignKey(Disputes, on_delete=models.CASCADE) ...[some more fields]... class CorporatePartyNames(models.Model): name = models.CharField(max_length=100, default=None, null=True) is_added_by_infa_user = models.BooleanField(default=True) ...[some more fields]... class DisputeUserRole(models.Model): corporate_party = models.ForeignKey(CorporatePartyNames, on_delete=models.CASCADE, default=None, null=True) # can not make it blank=True because of some api, which may go in fault. party_name = models.CharField(max_length=100, default=None, null=True) is_individual = models.BooleanField(default=True) infa_user = models.ForeignKey(InfaUsers, on_delete=models.CASCADE) ...[some more fields]... in admin.py: class DisputeUserRoleInline(admin.TabularInline): model = DisputeUserRole form = DisputeUserRoleForm # fields = ['corporate_party', 'is_individual', 'address', 'nationality', # 'infa_user', 'is_added_by_infa_user', ] @admin.register(Disputes) class DisputesAdmin(admin.ModelAdmin): list_display = ('id', 'case_id', 'status', 'created_at') inlines = [ DisputeUserRoleInline, ] fields = ['is_new_case', 'case_id', 'claim_amount', 'type_of_dispute'] # list_filter = ('group', 'collection_type') form = DisputesForm class Meta: model = Disputes in forms.py: class DisputesForm(forms.ModelForm): class Meta: model = Disputes exclude = [] class DisputeUserRoleForm(forms.ModelForm): full_name = forms.CharField(required=False) # … -
Gunicorn , no module named mysite.wsgi
I tried to configure gunicorn but i'm an error i can't solve. I looked around to see, but no issue ... I think it's a simple trick , if you can help me I based my configuration on this tutorial here I started on a brand new installation , so folder are standard: -tripplanner | -my_env/ | -mysite/ | mysite/ | firstapp/ | manage.py when I'm on the Step 7 — Testing Socket Activation i got this error for sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-09-14 14:38:46 UTC; 10s ago Process: 7946 ExecStart=/home/debian/.local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock mysite.wsgi:application Main PID: 7946 (code=exited, status=3) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: return _bootstrap._gcd_import(name[level:], package, level) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 983, in _find_and_load Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: ModuleNotFoundError: No module named 'mysite.wsgi' Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: [2020-09-14 14:38:46 +0000] [7950] [INFO] Worker exiting (pid: 7950) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: [2020-09-14 14:38:46 +0000] [7946] [INFO] … -
Django data migration fails unless it's run separately
I've run into this a couple other times and can't figure out why it happens. When I run the migrations all together through ./manage.py migrate then the last migration (a data migration) fails. The solution is to run the data migration on it's own after the other migrations have been completed. How can I run them all automatically with no errors? I have a series of migrations: fulfillment/0001.py order/0041.py (dependency: fulfillment/0001.py) order/0042.py order/0043.py I followed this RealPython article to move a model to a new app which which works perfectly and is covered by migrations #1 to #3. Migration #3 also adds a GenericForeignKey field. Migration #4 is a data migration that simply populates the GenericForeignKey field from the existing ForeignKey field. from django.db import migrations, models def copy_to_generic_fk(apps, schema_editor): ContentType = apps.get_model('contenttypes.ContentType') Order = apps.get_model('order.Order') pickup_point_type = ContentType.objects.get( app_label='fulfillment', model='pickuppoint' ) Order.objects.filter(pickup_point__isnull=False).update( content_type=pickup_point_type, object_id=models.F('pickup_point_id') ) class Migration(migrations.Migration): dependencies = [ ('order', '0042'), ] operations = [ migrations.RunPython(copy_to_generic_fk, reverse_code=migrations.RunPython.noop) ] Running the sequence together I get an error: fake.DoesNotExist: ContentType matching query does not exist. If I run the migration to order/0042.py then run order/0043.py everything works properly. How can I get them to run in sequence with no errors? -
import OAuth2Authentication ImportError: No module named 'oauth2_provider.ext'
I'm trying to login by Facebook in my python projcet .it keeps telling me that ImportError: No module named 'oauth2_provider.ext' whenever I migrate it using terminal my installed using pip freeze : certifi==2020.6.20 cffi==1.14.2 chardet==3.0.4 cryptography==3.1 defusedxml==0.7.0rc1 dj-database-url==0.5.0 Django==2.2.16 django-braces==1.14.0 django-oauth-toolkit==1.3.2 django-oauth2==3.0 django-rest-framework-social-oauth2==1.0.4 djangorestframework==3.11.1 gunicorn==19.6.0 idna==2.10 oauthlib==3.1.0 Pillow==3.3.0 pycparser==2.20 PyJWT==1.7.1 python-social-auth==0.3.6 python3-openid==3.2.0 pytz==2020.1 requests==2.24.0 requests-oauthlib==1.3.0 shortuuid==1.0.1 six==1.15.0 social-auth-app-django==1.1.0 social-auth-core==3.3.3 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==3.2.1 and requirements.txt file contains: Django==1.10 gunicorn==19.6.0 Pillow==3.3.0 whitenoise==3.2.1 dj-database-url==0.5.0 psycopg2==2.7.5 django-rest-framework-social-oauth2==1.0.4 and my runtime.txt file : python-3.5.2 and the code I used to login by Facebook from the site I used in settings.py in INSTALLED_APPS = [.., 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] TEMPLATES = [ ..., 'OPTIONS': {..., 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'rest_framework_social_oauth2.backends.DjangoOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_FACEBOOK_KEY = '355645928947054' SOCIAL_AUTH_FACEBOOK_SECRET = 'c606775c70e7dc01626ee41cbf95a0b8' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } and in urls.py : in urlpatterns = [... , .., url(r'^api/social/', include('rest_framework_social_oauth2.urls')), ] -
Form in django not saving in Psql
Sorry I am learning Django and this is my first project. I want to allow the user to up/down vote others users post. I have a model. I am using postgresql as database, and I am able to create users, and was even able to create posts for each users, but when I added in my model Django the following vote fields: upVote = models.ManyToManyField(User, related_name="upvote") downVote = models.ManyToManyField(User, related_name="downvote") it just stopped saving users post in the database. It does not display any errors nothing, it just does not save. model.py from django.db import models from django.contrib.auth.models import User # Create your models here. from django.conf import settings class UserPost(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL ) title = models.CharField(max_length=250, blank=False) description = models.CharField(max_length=500, blank=False) images = models.ImageField( upload_to='post_pictures/', null=True, blank=True) videos = models.FileField(upload_to='post_videos/', null=True, blank=True) upVote = models.ManyToManyField(User, related_name="upvote") downVote = models.ManyToManyField(User, related_name="downvote") In the view.py the login and the registering works, but since I want to display all the post in the index I see nothing. Bc the DB is empty. @login_required(login_url='/login-page/') def personalPage(request): form = FormPost(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() messages.success(request, "Successfully created") return render(request, 'accounts/personal-page.html', … -
Upload a CSV file using AJAX in djngo
I want to upload a CSV file using ajax query. template: <form id="attendance-form" method="POST" enctype="multipart/form-data"> <input type="file" id="upload-attendance" name="employee-attendance-file"> </form> AJAX: $("#upload-attendance").change(function(e) { e.preventDefault(); // disables submit's default action var input = $("#upload-attendance")[0]; var employeeAttendanceFile = new FormData(); employeeAttendanceFile.append("attendance-file", $('#upload-attendance')[0].files[0]); console.log(employeeAttendanceFile); $.ajax({ url: '{% url "attendance:employee-attendance-upload" %}', type: 'POST', headers:{ "X-CSRFToken": '{{ csrf_token }}' }, data: { "employee_attendance_file": employeeAttendanceFile, }, dataType: "json", success: function(data) { data = JSON.parse(data); // converts string of json to object }, cache: false, processData: false, contentType: false, }); }); after uploading a CSV file, when I console.log the file(console.log(employeeAttendanceFile);) variable nothing return. When I fetch ajax request from django view, it(print(csv_file)) also returns None. views.py: class ImportEmployeeAttendanceAJAX( View): def post(self, request): csv_file = request.FILES.get("employee_attendance_file") print(csv_file) Where am I doing wrong? -
Django Private Channel - two users
I'm trying to build a channel. I'd like to restrict the detail views to consumer and seller. I don't want the other users have an access to the detail views. The thing is I can make it accessible to one but I don't know how to make it accessible for both consumer & seller? class Group(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="") ... def __str__(self): return self.name #Detail channel @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class CheckoutDetail(generic.DetailView): ... def get(self,request,*args,**kwargs): self.object = self.get_object() if self.object.consumer or self.object.seller != request.user: #it's redirect me to home page return HttpResponseRedirect('/') return super(CheckoutDetail, self).get(request,*args,**kwargs) -
I am getting an error when running server in Django
when executing py manage.py runserver command I get the error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1520.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\users\galen\mysite\mysite\urls.py", line 20, in <module> path('polls/', include('polls.urls')), File "C:\Users\galen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\urls\conf.py", … -
Converting data types for python and django
I have two main variables, week_order_overall_total which is a custom python money data type using this (https://github.com/mirumee/prices) and then the actual integer references below (5, 200, 15 etc). When I try I do a calculation with the two using payout = week_order_total_card - hm_fees, I get an error message: '>=' not supported between instances of 'Money' and 'int' I imagine this is because there are two different data types being used. I have tried resolving it using int(week_order_overall_total) but that doesn't work. CODE: if trial_status =="yes": if admin_value <=5: hm_fees=5 else: hm_fees=admin_value elif early_customer =="yes" and week_order_overall_total >=1 and week_order_overall_total <= 200: hm_fees=15 elif week_order_overall_total == 0: hm_fees=0 elif week_order_overall_total >= 1 and week_order_overall_total <= 200: hm_fees=20 elif week_order_overall_total >= 201 and week_order_overall_total <= 400: hm_fees=35 else: hm_fees=55 payout = week_order_total_card - hm_fees Any help is appreciated. -
Redirect back to previous page after login in django-allauth
There is a button in blog detail view that asks user to login to comment, but after login user is redirected to home page because in settings.py I declared: LOGIN_REDIRECT_URL = "projects:home" I searched and I found this could be a solution: <a href="{% url 'account_login' %}?next={{request.path}}">Please login to reply</a> but this even didn't work. Thank You -
How to make Django template engine recognize an expression from an injected string
I am injecting meta/title tags dynamically for each page by using a yaml file full of html tags. HTML {% if meta_tags %} {% for tag in meta_tags %} {{ tag|safe }} {% endfor %} YAML trending_bonds: - '<title>Trending Searches for {% now "Y-m-d" %}</title>' The view just loads the yaml into a dict of strings and passes it along to template in that meta_tags variable. I need that {% now %} expression to be run and show the current date but it keeps getting inserted as a string just like shown above. Any ideas? -
Django html template how to display variable inside variable?
i have templater which contains.Driver, Car and campaign model and i have template base model wherere all model and body, text and another field contains and i added in body {driver.fleet} but when i try to see html template its not shwoing value of fleet its just shows {driver.fleet} like this. <section class="table_driver" style="margin: 0 auto; max-width: 760px;"> <div class="somehtinff_fix"> {{template.container_en|safe}} #this is fiels </div> </section> conainer_en text is like this Our tips for you: (General tip) To give you more peace of mind and a safer driving, next morning, you should go and inflate you tires to the currect pressure. Why?(link) {driver.fleet} #this should through that driver fleet name (Specific tip) We also noticed that you have the tendecy to drive in a lower gear even on a straight, this forces your engine to overspeed, use more fuel and overheat. Try to drive on a higher gear on a straight even if you driving slow. Try driving in a 4th or 5th gear, 6th might be to hight but you can try, less noise, smoother driving and less 5 to 10% fuel consumption. Trip(Link this is the code where template file exist ctx = { "driver": self.driver, # `here …