Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'people' not found. 'people' is not a valid view function or pattern name
I got the error in my title when I tried to add a URL link so I can get to the person when I click on the URL. Beginner here so sorry if I am making silly mistakes. I am not sure where in my view function I messed up so any help is really appreciated views.py from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import People # Create your views here. class pplList(ListView): model = People context_object_name = 'people' class pplDetail(DetailView): model = People context_object_name ='cnd' template_name = 'base/people.html' people_list.html <h1>Interviewee Dashboard</h1> <table> <tr> <th> Item</th> <th> </th> </tr> {% for cnd in people %} <tr> <td>{{cnd.name}}</td> <td><a href="{% url 'people' cnd.id %}">View</a></td> </tr> {% empty %} <h3>No items in list</h3> {% endfor %} </table> models.py from unittest.util import _MAX_LENGTH from django.db import models from django.contrib.auth.models import User # Create your models here. status_choices = ( ("Choose", "Choose"), ("Resume Submitted","Resume Submitted"), ("Resume Reviewed", "Resume Reviewed"), ("Interview Scheduled","Interview Scheduled" ), ("Interview Completed","Interview Completed" ), ) wl = ( ("Choose", "Choose"), ("Accepted", "Accepted"), ("Rejected", "Rejected"), ) class People(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200) age = models.IntegerField(null=True, blank=True) address = models.TextField(null=True, … -
Reporting data entries in the project
In the project I use Django and PostgreSql, there is data entry every day. I want to receive the data of that day at the time I set myself, convert it into pdf and send it as an e-mail. Is there something automatic to do this all the time or what kind of script or query should I write? In other words, I want to do a reporting process on a daily basis, but I want to ensure that it is done automatically. -
How to host a django project on a hostinger vps?
I have a django project. I want to host it on a vps. I saw a few vps services and liked the hostinger vps.I want to host it to that vps. But the problem is, I am using django celery.I am also using django channels(WebSocket). It means,you know, I'm using asgi. And I want to use apache server with it. Can I know how to deploy this project on a vps? -
Django REST: Authentication credentials were not provided
There are similar questions like this on StackOverflow which didn't solve my problem. I'm using Postman to test my APIs. For some reason, my token authorization is not working and it's showing the following message, "detail": "Authentication credentials were not provided." My settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } These are my installed apps: ... 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'dj_rest_auth', 'dj_rest_auth.registration', ... I spent some hours to find the problem but failed. Can anyone please help me with where might the problem be? -
Context data not passing to Django templates
My cart view. I have passed context on return but it doesn't appear on the templates. If i print the def cart(request): total = 0 quantity = 0 cart_items = None tax = None grand_total = None try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, is_active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quality) quantity = cart_item.quality tax = (total / 100) * 2 grand_total = total + tax except: pass context = { 'total': total, 'quantity': quantity, 'cart_items': cart_items, 'tax': tax, 'grand_total': grand_total, } return render(request, 'c.html', context) Html Template. Here I created a for loop to get items from the array. But It doesn't show any objects from the array. But always print "Item" string for each object. {% extends 'base.html' %} {% load static %} {% block content %} {% extends 'base.html' %} {% load static %} {% block content %} {% for item in cart_items %} item.product.product_name {% endfor %} {% endblock %} {% endblock %} -
Symmetric django model
I want to create a model, which is symmetric on two fields. Let's call the model Balance: class Balance (models.Model): payer = models.ForeignKey(auth.User, ...) payee = models.ForeignKey(auth.User, ...) amount = models.DecimalField(...) It should have the following property: balance_forward = Balance.objects.get(payer=USER_1, payee=USER_2) balance_backward = Balance.objects.get(payer=USER_2, payee=USER_1) balance_forward.amount == -1 * balance_backward.amount What is the best way to implement this? -
How to Filter out Django Models
How do I create a lesson in a course without it showing in another course. I have a foreign key which is the course and it is under the models Lesson. I want to only view the lesson that is created under the certain course. But my problem is when I create a lesson in course 1, the lesson also shows in course 2. (sorry for bad english) views.py from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView from courses.forms import AddCourseForm, AddSectionForm, AddLessonForm from courses.models import Course, Section, Lesson def coursepage(request): courses = Course.objects.all() if request.user.is_authenticated: return render(request, "courses/courses.html", {'courses': courses}) else: return redirect('loginpage') def addcourse(request): if request.method == "POST": form = AddCourseForm(request.POST) if form.is_valid(): form.save() return render(request, "courses/successcourse.html", {'form1': form}) form = AddCourseForm() return render(request, "courses/addcourse.html", {'form': form}) def updatecourse(request, id): course = Course.objects.get(id=id) context = { 'course': course } return render(request, 'courses/editcoursehtml', context) def updatecourserecord(request, id): course = Course.objects.get(id=id) form = AddCourseForm(request.POST, instance=course) if form.is_valid(): form.save() return redirect("coursepage") return render(request, 'courses/editcourse.html', {'course':course}) def deletecourse(request, id): course = Course.objects.get(id=id) course.delete() return redirect("coursepage") class CourseDetailView(DetailView): queryset = Course.objects.all() template_name = "courses/detail.html" def sectionspage(request): section = Section.objects.all() if request.user.is_authenticated: return render(request, "sections/sections.html", {'sections': section}) else: return redirect('loginpage') def addsections(request): … -
not able to authenticate access_token comming from flutter app in django using google-oauth2 errors come up like your "credentials are not correct"
@api_view(['POST']) @permission_classes([AllowAny]) @psa() def register_by_access_token(request, backend): token = request.data.get('access_token') user = request.backend.do_auth(token) print(request) if user: token, _ = Token.objects.get_or_create(user=user) return Response( { 'token': token.key }, status=status.HTTP_200_OK, ) else: return Response( { 'errors': { 'token': 'Invalid token' } }, status=status.HTTP_400_BAD_REQUEST, ) so above is the code and this is the URL re_path('api/register-by-access-token/' + r'social/(?P<backend>[^/]+)/$', register_by_access_token), But all the time user = request.backend.do_auth(token) this thing is giving error that "credentials are not correct" -
How to retrieve random records of Django ORM on a weekly basis
I am new to Django and I'd need some help for a project I have. I am currently building the API using Django-Rest-Framework and I would like to have a view which returns a weekly list of exercises. I am not sure how i could make it so the queried objects change weekly... atm I've created a custom Manager which retrieves a random amount of exercises from the exercise db Models.py class ExerciseManager(models.Manager): random_exercises = [] def random(self, amount=20): self.random_exercises.clear() exercises = Exercise.objects.all() for i in range(amount): self.random_exercises.append(random.choice(exercises)) return self.random_exercises class Exercise(models.Model): name = models.CharField(max_length=100, unique=True) objects = ExerciseManager() def __str__(self): return f"{self.name}" views.py @api_view(['GET']) def exercise_list(request): exercises = Exercise.objects.random() serializer = ExerciseSerializer(exercises, many=True) return Response(serializer.data) -
I use django auth in my project. how can i overwrite login view to add a remember me view?
This is my urls.py: from django.urls import path, reverse_lazy from django.contrib.auth import views as auth_views from .forms import EmailValidationOnForgotPassword from . import views app_name = 'account' urlpatterns = [ path('', views.dashboard, name='dashboard'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('account:password_change_done')), name='password_change'), path('password_change/done', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', auth_views.PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword, success_url=reverse_lazy('account:password_reset_done')), name='password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(success_url=reverse_lazy('account:password_reset_complete')), name='password_reset_confirm'), path('reset/done', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Is there any attributes i can use like 'success_url' or 'form_class' -
form is not submit and load another page in production
i have a form page which work perfectly in locally but after uploading it to railway it start showing this error I also checked locally it worked perfectly fine and load the page when click forms submit button but in production it throws above mentioned error here is my form template <form action="{% url 'personal_readme:preview' %}" method="POST" enctype="multipart/form-data"> **{% csrf_token %}** <div class="name_tag"> <h2><iconify-icon icon="bi:person-circle"></iconify-icon> ( Title )</h2> {{ form.name.label_tag }} <span>{{ form.name }}</span> </div> <hr> <div class="support_tag"> <h2><iconify-icon icon="fa-solid:handshake"></iconify-icon> ( Support )</h2> <iconify-icon icon="line-md:buy-me-a-coffee-filled"></iconify-icon> {{ form.buy_me_coffee.label_tag}} {{ form.buy_me_coffee}} <iconify-icon icon="simple-icons:patreon"></iconify-icon> {{ form.patreon.label_tag}} {{ form.patreon}} </div> <hr> <div class="genrate text-center"> <button type="submit" class="gen_btn"><iconify-icon icon="bxs:file-md"></iconify-icon> Genrate File</button></div> </form> my views.py for def home(request): if request.method == 'POST': form = Personal_Readme_form(request.POST) if form.is_valid(): form.save() return redirect('personal_readme:preview') else: form = Personal_Readme_form() return render(request, 'home.html', {'form': form}) any suggestion might be helpful -
Django-forms: ValidationError not working / check if attribute exists
I am trying to get an error for the form if name of a created process already exists. Now what happens is that the form just doesn't submit, but it doesn't raise any errors to the form itself noting what is going on. I have looked all different ways to get the ValidationError to do something, but I cannot get it work at all. Form works otherwise as it submits if value doesn't already exist. What am I missing here? Here is models.py class Process(models.Model): name = models.CharField('Process name', max_length=100, unique=True, error_messages={'unique':"Name already in use"}) Here is forms.py class NewProcess(forms.ModelForm): class Meta: model = Process fields = [ 'name', ] def __init__(self, *args, **kwargs): super(NewProcess, self).__init__(*args, **kwargs) def clean_name(self): process_name = self.cleaned_data.get('name') existing = Process.objects.filter(name=process_name).exists() if existing: raise forms.ValidationError(u"Name already in use") return process_name Here is views.py def process_create(request, *args, **kwargs): createprocess = NewProcess(request.POST or None) processes = Process.objects.all() if request.method == 'POST': createprocess = NewProcess(request.POST) if createprocess.is_valid(): process = createprocess.save(commit=False) #other functions here creatprocess.save() context = { 'processes':processes, } return render(request, "process/process-list.html", context) context = { 'createprocess':createprocess, } return render(request, "process/process-create.html", context) -
Django Error: 'WSGIRequest' object has no attribute 'order'
I'm trying to render out the get_cart_total to the email template I'm working on, which gets sent when the success view is triggered and the boolean is True, currently it gets an error message saying 'WSGIRequest' object has no attribute 'order', what's causing this and how do I fix it? Model class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) email = models.EmailField(max_length=150) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total Views def success(request): if order.complete == True: email = request.user.customer.email #error cart_total = request.order.get_cart_total html_message = render_to_string('check/emails/test.html', {'cart_total': cart_total}) recipient_list = [email, ] send_mail( subject, plain_message, email_from, recipient_list, html_message=html_message ) Traceback Traceback (most recent call last): File "D:\test\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\test\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\test\shop\views.py", line 364, in success cart_total = request.order.get_cart_total AttributeError: 'WSGIRequest' object has no attribute 'order' -
I have HTML page stored in javascript variable how to show it in the page
this is my variable have HTML code fetched from database const z = " <div id="div_idadnan"><div class="accordion" id="accordionExample0"><div class="accordion-item"> <h2 class="accordion-header" id="headingOne"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOneadnan" aria-expanded="true" aria-controls="collapseOne">adnan</button></h2><div id="collapseOneadnan" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample0">"<div style="background-color:#eecf9e" class="accordion-body" id="adnan"><table class="table table-bordered border-primary"><thead><tr><th style="font-size:20px;" scope="col">اللاعب</th><th style="font-size:20px;" scope="col">الحرف </th> <th style="font-size:20px;" scope="col">إسم </th><th style="font-size:20px;" scope="col">إسم بنت</th><th style="font-size:20px;" scope="col">حيوان </th><th style="font-size:20px;" scope="col">نبات </th><th style="font-size:20px;" scope="col">جماد </th><th style="font-size:20px;" scope="col">بلاد </th><th style="font-size:20px;" scope="col">الغرفة </th><th style="font-size:20px;" scope="col">مجموع </th></tr></thead><tbody id="divvadnan"><tr><th scope="row">⭐<button id="removeme" type="button" onclick="userremove('adnan')" class="btn btn-primary btn-rounded" data-hover="CLICK ME" data-active="IM ACTIVE"><span>adnan</span></button> </th><td style="font-size:18px;" id="letter">ق</td><td style="font-size:18px;" id="noun">ق</td><td style="font-size:18px;" id="gnoun">ق</td><td style="font-size:18px;" id="animalNoun">ق</td><td style="font-size:18px;" id="plants">ق</td><td style="font-size:18px;" id="inanimate">ق</td><td style="font-size:18px;" id="countries">ق</td><td style="font-size:18px;" id="room">1234567</td><td style="font-size:18px;" id="sum">NaN</td></tr><tr><td scope="row"></td><td scope="row"></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','noun_result')" id="noun_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="noun_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','gnoun_result' )" id="gnoun_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="gnoun_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','animal_result')" id="animal_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="animal_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','plants_result')" id="plants_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="plants_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','countries_result')" id="countries_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="countries_resulttdadnan"></div></td><td><select style="font-size:16px;" onchange="OnSelectedIndexChange('adnan','inanimate_result')" id="inanimate_resultadnan" disabled=""><option style="font-size:16px;" href="#">0</option> <option style="font-size:16px;" href="#">5</option><option style="font-size:16px;" href="#">10</option></select><div id="inanimate_resulttdadnan"></div></td><td class="success" id="sumadnan">0</td></tr><button type="submit" class="btn btn-primary" id="calcadnan" onclick="calc('adnan' , 'ق' , 'ق' ,'ق','ق','ق','ق','ق','1234567')" style="">Calculate</button></tbody></table></div></div></div></div></div><div id="div_idkaram"><div class="accordion" id="accordionExample1"><div class="accordion-item"> <h2 class="accordion-header" id="headingOne"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOnekaram" … -
Django - Stop Page from reloading after GET Request
I'd like to show all grades from one user on Button Click. Now I wanted to integrate an expandable Button from Bootstrap. The GET Request works perfectly, but the JavaScript for the expandable Button gets triggered on Button Click and then the Page gets reloaded. That means the Button now is back at the original state. Do you guys maybe have a way to fix that? noten.html {% if subject_list %} <form name="subject-list" method="GET"> <ul> {% for subject in subject_list %} <p> <button class="btn btn-primary" type="submit" data-bs-toggle="collapse" data-bs-target="#{{ subject }}" aria-expanded="false" aria-controls="collapseExample" value="{{ subject }}" id="{{ subject }}" name="subject"> {{ subject }} </button> </p> <div class="collapse" id="{{ subject }}"> <div class="card card-body"> {% if grades %} {% for grade in grades %} <li>{{ grade }}</li> {% endfor %} {% else %} <p>Du hast keine Noten in diesem Fach!</p> {% endif %} </div> </div> {% endfor %} </ul> </form> {% endif %} views.py def noten(request): if request.user.is_authenticated: # if user is logged in object_list = Subject.objects.order_by('name') subject_list = [] for subject in object_list: subject_list.append(subject.name) if request.method == 'GET': subject = request.GET.get('subject', '') if subject != '': print(f"GET {subject}") grades = Test.get_grades(student=request.user.id, subject=subject, self=Test) return render(request, 'noten.html', {'subject_list': subject_list, 'grades': grades}) else: … -
Python inside a virtualenv is broken (Django)
TL;DR - Microsoft Store Apps are broken (0 bytes), hence the Python interpreter is unable to create process and run "Python" inside virtualenv, I failed to follow numerous explanations of how to change virtualenv path for Python. Recently, without any changes to my computer/environment, an issue started occurring when executing (also tried python3, which brings the same): python manage.py runserver This brought back the following issue: Unable to create process using '"C:\Users\MyUser\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe"' As I dug deeper, I realized that all of the apps installed under this folder are 0 bytes, hence they are completed broken, all of a sudden. Therefore I figured it's not an issue with Django, rather the python itself. I tried changing the virtualenv path for Python.exe, instead of using WindowsApps version, I installed the original Python from the original website. I failed to do so, multiple times. I tried: "https://stackoverflow.com/questions/4757178/how-do-you-set-your-pythonpath-in-an-already-created-virtualenv/47184788#47184788" - Adding the path inside "activate" and "activate.bat", as set PYTHONPATH="C:\Users\MyUser\AppData\Local\Programs\Python\Python310\python.exe" And the issue persists. I tried every solution/article I found in regards to the issue I have. Many of them claim a simple result, whereas the rest claim a complete refactor is required. Even downloading from Microsoft store is broken, it always fails. Since I'm … -
Django models foreign key validation
I have the following Django models: class Owner(models.Model): name = models.CharField(max_length=30) class Dog(models.Model): name = models.CharField(max_length=30) owner = models.ForeignKey(Owner) class GoForAWalk(models.Model): date = models.DateTimeField() location = models.CharField() owner = models.ForeignKey(Owner) dog = models.ForeignKey(Dog) I want that a Owner can only GoForAWalk with one of his own Dog. Currently any owner can go for a walk with any dog. Would you restrict this via model validators or via some logic during the creation of a new GoForAWalk object? Can anyone provide an example? I'm quite stuck. Thanks a lot! Cheers, Philipp -
Why does Django debugger keep saying the variable is 'None' when its not?
I have a problem with Django sessions. I am trying to create a clinic website which has a booking functionality so users can book their appointments online. Unfortunately the Django sessions not working properly! The booking is in two steps: Getting the first two datas which are: 'service' and 'day'. Then showing the user the hours (time) available in that day for user to choose for appointment. In the first step in the booking process I get the datas "day" and "service" and then store it in the session so I can check what hour (time) is free in that day and only show the ones that are not booked before. But when we move to the second step of the booking process Django raises a ERROR that the 'day' and 'service' data are 'None'! but they are not 'None' as shown in the 'Debug picture2' link at the end of this question. Views.py: from django.shortcuts import render, redirect from datetime import datetime, timedelta from .models import * from django.contrib import messages def tehranBooking(request): today = datetime.now() minDate = today.strftime('%Y-%m-%d') deltatime = today + timedelta(days=21) strdeltatime = deltatime.strftime('%Y-%m-%d') maxDate = strdeltatime times = [ "3 PM", "3:30 PM", "4 PM", … -
Override error from django image extensions in models
I want to get my custom error from validate_image this is my models.py def validate_image(image): valid_image_extensions = ['jpg', 'png', 'jpeg'] input_extension = str(image).split('.')[1] if input_extension not in valid_image_extensions: raise ValidationError( f"We aren't accepted your extension - {input_extension} only accepted {','.join(valid_image_extensions)}" ) class Image(models.Model): description = models.CharField(null=True, default='Image', blank=True, max_length=120) image = models.ImageField(upload_to='images', validators=[validate_image]) When i try upload image with .raw extension i expected my custom validation but i have error from django. { "image": [ "File extension “raw” is not allowed. Allowed extensions are: bmp, dib, gif, tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm." ] } How i can run custom validation before django validation ? -
Why i can't get variable name from Django
I have a Django project that i'm working on. I need to print something to CLI to make it easier to debug. This is what i need print('============================================') print('VARIABLE_NAME_IN_CAPS') print(variable) print(f'LENGTH : {len(variable)}') print('============================================') this is my function to get variable name. This is where i got the snippet def get_variable_name(variable): globals_dict = globals() return [var_name for var_name in globals_dict if globals_dict[var_name] is variable] But when i called the function i get empty array []. I've tried to do it without function and do a separate test in another file and it worked. Is there anything that prevent this to happen in Django ? -
ValueError at / The 'image' attribute has no file associated with it
How can i solve this error??i cannot see uploaded picture from users.it give ValueError at / The 'image' attribute has no file associated with it. error everytime. The job was to display user uploaded post in the social media site. I first created a model named “uploade” and added fields such name, location, number and profile picture. It worked excellent until I tested imageField associated with profile picture. [i cant understand whts wrong here,for this error][1] [1]: https://i.stack.imgur.com/yvffJ.png **---HTML---** {% for post in posts reversed %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <!-- <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/avatar-2.jpg' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> --> <span class="block font-semibold "><a href="/profile/{{post.user}}">@{{post.user}}</a></span> </div> <div> <a href="#"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 "></i> </a> <div class="bg-white w-56 shadow-md mx-auto p-2 mt-12 rounded-md text-gray-500 hidden text-base border border-gray-100 " uk-drop="mode: hover;pos: top-right"> <ul class="space-y-1"> <!-- <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-share-alt mr-1"></i> Share </a> </li> --> <!-- <li> <a href="#" class="flex items-center px-3 py-2 hover:bg-gray-200 hover:text-gray-800 rounded-md "> <i class="uil-edit-alt … -
The content published by wagtail using the RichTextField field does not support spaces and indents
I am a beginner and use the blog developed by wagtail to take notes. After the record code part is saved, the blank space and indentation disappear. This problem is stuck. Help me. Thank you! class BlogPage(Page): body = RichTextField(blank=True) saved e.g: class BlogPage(Page): body = RichTextField(blank=True) -
MongoDB with Django: TypeError: Model instances without primary key value are unhashable
I'm trying to connect MongoDB with Django. settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '<name>', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': f'mongodb+srv://{mongodb_username}:{mongodb_password}@{mongodb_cluster}/?retryWrites=true', 'uuidRepresentation': 'standard', 'waitQueueTimeoutMS': 30000 } } } models.py import uuid from django.db import models # Create your models here. class ModernConnectUsers(models.Model): user_id = models.UUIDField(primary_key=True, default=uuid.uuid4()) user_name = models.CharField(max_length=30, null=False) The model has not been used anywhere for now. python manage.py makemigrations && python manage.py migrate outputs: Migrations for 'modern_connect': modern_connect/migrations/0003_alter_modernconnectusers_user_id.py - Alter field user_id on modernconnectusers Operations to perform: Apply all migrations: admin, auth, contenttypes, modern_connect, sessions Running migrations: No migrations to apply. Your models in app(s): 'modern_connect' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/sarvesh/PycharmProjects/modernConnect/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 317, in handle emit_post_migrate_signal( File … -
Python Jsonschema validation returning error on correct input
I am quite new to Python, and trying to validate a json file in the following way with jsonschema validation: carsSchema = {"type": "object", "properties" : { "model_year": {"type" : "string"}, "make": {"type" : "string"}, "model": {"type" : "string"}, "rejection_percentage": {"type" : "string"}, "reason_1": {"type" : "string"}, "reason_2": {"type": "string"}, "reason_3": {"type" : "string"}} then reading a json file with inputs: file = json.loads(request.FILES['file'].read()) for instance in file: print(validate(instance, carsSchema)) the file inputs looks like this: [ { "model_year": "2013", "make": "Mercedes-Benz", "model": "CLS", "rejection_percentage": "0,0", "reason_1": "", "reason_2": "", "reason_3": "" } ] I am receiving None on all the file inputs even though they are in correct format. Thanks in advance :) -
If statement in Django template always runs the code no matter the condition is True or False
I'm using a Key-Value model to make static template's data dynamic. This is my model's code: class SiteDataKeyValue(models.Model): key = models.CharField(max_length=200, verbose_name="Text title") value = models.TextField(verbose_name="Text") def __str__(self): return self.key For each static page, e.g. About us or Contact us, first I've created the texts in the admin panel. Then, I've written the views below: class ContactUsPageView(ListView): """ In this view we are fetching site data from database, in a function named get_context_data. In this function, we filter the model for objects that contains the word 'contact', therefore fetching data referring to the about page only. After that the context list is sent to the template, and there with a for loop and an if statement, each key, value set is chosen for the proper place. """ model = SiteDataKeyValue template_name: str = "core/contact-us.html" def get_context_data(self, **kwargs): context = super(ContactUsPageView, self).get_context_data(**kwargs) context["contact_page_data"] = self.model.objects.filter(key__contains="contact") return context Finally, in the template, I'm trying to use these data with a for loop and an if statement as shown below: {% for text in contact_page_data %} {% if text.key == "contact us factory address" %} <p class="card-text"><i class="bi bi-geo-alt me-2"> {{ text.value }} </p> {% endif %} {% endfor %} I have just …