Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type
enter image description here i am trying to run this project but its giving TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type Project Github Link: https://github.com/prathmachowksey/Attendance-System-Face-Recognition -
TypeError at /register/ list indices must be integers or slices, not str
How can i solve this issue in my forms.py from django import forms from django.forms.widgets import EmailInput, FileInput, PasswordInput, TextInput, Textarea from django.contrib.auth.models import User from django.contrib.auth import authenticate,get_user_model User = get_user_model() class RegistertionForm(forms.Form): first_name = forms.CharField(widget=TextInput(attrs={ 'class': 'validate form-control', 'placeholder': 'Full Name', 'type': 'text', 'id': 'first_name'}), min_length=2, max_length=150) username = forms.CharField(widget=TextInput(attrs={'class': 'validate form-control', 'placeholder': 'Username', 'type': 'text', 'id': 'username'}), min_length=4, max_length=150) email = forms.CharField(widget=EmailInput(attrs={'class': 'validate form-control', 'type': 'email', 'placeholder': 'Enter your email address', 'id': 'email'})) number = forms.CharField(widget=TextInput(attrs={'class': 'validate form-control', 'type': 'number', 'placeholder': 'phone number', 'id': 'number'})) password = forms.CharField(widget=PasswordInput(attrs={'class': 'validate form-control', 'type': 'password', 'placeholder': 'Password', 'id': 'password'})) password2 = forms.CharField(widget=PasswordInput(attrs={'class': 'validate form-control', 'type': 'password', 'placeholder': 'Confirm-password', 'id': 'password2'})) description = forms.CharField(widget=Textarea(attrs={'class': 'validate form-control', 'placeholder': 'Write about yourself', 'id': 'description'})) # picture = forms.CharField(widget=FileInput(attrs={'class': 'validate form-control', 'type': 'file', 'id': 'profile', 'name': 'profile'})) def clean_firstname(self): firstname = self.cleaned_data['firstname'].lower() qs = User.objects.filter(firstname=firstname) if qs.count(): raise forms.ValidationError("Name already exists") return firstname def clean_username(self): username = self.cleaned_data['username'].lower() qp = User.objects.filter(username=username) if qp.count(): raise forms.ValidationError("Username already exist") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = User.objects.filter(email=email) if r.count(): raise forms.ValidationError("Email already exists") return email def clean_phone(self): number = self.cleaned_data['email'].lower() r = User.objects.filter(number=number) if r.count(): raise forms.ValidationError("Phone number already exists") return number def clean_password2(self): … -
Make API call on page load (Django)
I'm trying to figure out a way to make an API call and retrieve the results on page load. Any pointers would be appreciated! -
Why am i getting server 500 error in Django?
I have been trying to use the Django template inheritance feature for my project Since I've added {% block content %}s I am now getting a server error 500 whenever I try to run the child template. The base template runs fine. I am quite sure it has something to do with the content blocks, but I'm not sure why as I don't repeat any names of blocks and everything on the child template is contained within a block. Code goes like this: Base.html <!DOCTYPE html> <style> 'My style' </style> <html lang='en'> <head> <meta charset='UTF-8' {% block title %} webpage {% endblock %} <script>'Jquery reference'</script> </head> {% block script %} 'empty' {% endblock %} <body> <div id='navbar'> 'My navbar' </div> <div id='main_content_block'> {% block content %} <h1>This is my base</h1> {% endblock %} </div> </body> </html> Home.html {% extends 'main/base.html' %} {% block title %} <title>Home</title> {% endblock %} {% block script %} 'My javascript' {% endblock %} {% block content %} 'My content' {% endblock %} Thanks for your time -
How to deploy django app with channels and websocket to Heroku?
I'm creating messanger. I met a need to deploy my app to heroku. My config/settings.py from pathlib import Path from datetime import timedelta import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'corsheaders', 'users', 'tokens', 'channels', 'chat', 'college' ] AUTH_USER_MODEL = 'users.User' ASGI_APPLICATION = 'config.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(os.environ.get('REDIS_URI'), 25690)], }, }, } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('ELEPHANT_NAME'), 'USER': os.environ.get('ELEPHANT_USER'), 'PASSWORD': os.environ.get('ELEPHANT_PASSWORD'), 'HOST': os.environ.get('ELEPHANT_HOST'), 'PORT': 5432 } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ........................ I user heroku-redis config.asgi import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing from config.middlewares import TokenAuthMiddleware os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": TokenAuthMiddleware( URLRouter( chat.routing.websocket_urlpatterns ) ), }) Procfile release: python manage.py migrate web: daphne config.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=core.settings -v2 Honestly I don't know which port i should specify. Don't … -
Heroku Serving Localhost URL (127.0.0.1:8000) in Ajax API URLs in Django App
I'm currently working on a Django project and it's hosted on Heroku from GitHub. The front-end is served via Ajax calls to an API. let myurl = "/api/properties/"; $.ajax({ async: true, url:myurl, method:'GET', success: function(result){ .... } }); Everything works well on localhost, but on Heroku, I keep getting the error: GET http://127.0.0.1:8000/api/properties/ net::ERR_CONNECTION_REFUSED My API URL has no http://127.0.0.1:8000 on GitHub but on Heroku it has it after analyzing the source code on the Sources tab on Chrome: let myurl = "http://127.0.0.1:8000/api/properties/"; $.ajax({ async: true, url:myurl, method:'GET', success: function(result){ .... } }); I don't understand why my app's API URL isn't taking the domain URL https://appname.herokuapp.com/api/properties/ and it's across all the Ajax API URLs on the Django app. I have cleared my browser cache, opened the app in 'incognito mode' and even redeployed the project several times but not change. Kindly help me debug this and understand where the localhost URL is coming from. -
Django 3.2.8: 0 static files copied to '/static'
This error occurs when performing command python manage.py collectstatic: 0 static files copied to '/home/project'. That means there is no changes and my static files already exist in the destination but in this folder only one file: static/ - staticfiles.json But I want all my CSS, js, HTML for panel admin to be in it. Django Settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static/") STATICFILES_DIRS = ( STATIC_ROOT, ) urls.py ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I also tried these 1, 2 but no results were found. -
How to set subdomain from django-host in cpanel?
I have a Django based web application. I deploy the website on hosting using cPanel. There is already provided for the installation of Python-based applications. On my website I use a subdomain that I created with the django-host library. When run on localhost, like http://driver.localhost:8000 and can run. How do I make the subdomain accessible when I deploy the website to hosting? Seperti https://driver.gatotkacatravel.com -
Function view throws an exception of UnboundLocalError at /group/share/42/ when a user tries share a post
What could possibly be the course of this exception UnboundLocalError at /group/share/42/ when i try sharing post of another user in a group.The exception trace seems to be on the the first line of the forloop ( new = new_post.video.add(img) ) Here is my view for users to share post def share_post(request, pk): original_post = Post.objects.get(pk=pk) form = ShareForm(request.POST) if form.is_valid(): new_post = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, shared_on = timezone.now(), shared_user = request.user) new_post.save() for img in original_post.video: shared = new_post.video.add(img) shared.save() return redirect('group:main',original_post.group.pk) Here is my model Post. -
django "can't adapt type '__proxy__'" error message
class GenderTypeEnum: FEMALE = 1 MALE = 2 UNKNOWN = 3 types = ( (FEMALE, _("Female")), (MALE, _("Male")), (UNKNOWN, _("Unknown")) ) class PersonModel(models.Model): identity = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=75) last_name = models.CharField(max_length=75) gender = models.PositiveIntegerField(choices=GenderTypeEnum.types) class StaffModel(models.Model): person = models.ForeignKey('PersonModel', on_delete=models.CASCADE, related_name='staffs') registration_number = models.CharField(max_length=50, unique=True) start_date = models.DateField() finish_date = models.DateField(null=True, blank=True) I am using the following query to list the gender statistics of the staff StaffModel.objects.values("person__gender").annotate(count=Count("person__gender")) output: [ {"person__gender":1, "count":1}, {"person_gender":2, "count":5} ] But gender field is a choices field so that, output that I want like this: [ {"person__gender":1, "gender_exp":"Male", "count":1}, {"person_gender":2, "gender_exp":"Female", "count":5} ] I created the following class by looking at the answer given to @bachkoi32 Display name of a choice field in Django while using annotate In order to output, I use this class: class WithChoices(Case): def __init__(self, model, field, condition=None, then=None, **lookups): fields = field.split('__') for f in fields: model = model._meta.get_field(f) if model.related_model: model = model.related_model choices = dict(model.flatchoices) whens = [When(**{field: k, 'then': Value(v)}) for k, v in choices.items()] return super().__init__(*whens, output_field=CharField()) I changed my query: qs = StaffModel.objects.values("person__gender").annotate(gender_exp=WithChoices(StaffModel, 'person__gender'), count=Count("person__gender")).values("person__gender","gender_exp","count") When I want to print the query result, it raise the error; django.db.utils.ProgrammingError: can't adapt type 'proxy' qs = … -
django input in form returns None
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="{% url 'newlink' %}" method="POST"> {%csrf_token%} <input type="text" name="urllink"/> <button type ="submit" id="submit">등록하기</button> </form> <div id="crawling"> title : {{crawling_title}} <img src="{{crawling_img_link}}"/> </div> </body> </html> ▲ rental_newlink.html def newlink(request): if request.method == 'POST': #폼 다채우고 저장버튼 눌렀을 때 url = request.GET.get("urllink") url_link = str(url) print("url link : ", url_link) driver = webdriver.Chrome('C:/Users/박철현/파일들/멋쟁이사자처럼/단풍톤/BILLIM/chromedriver') driver.get('https://book.naver.com/bookdb/book_detail.naver?bid=21312636') title = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="container"]/div[4]/div[1]/h2/a'))).text img = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="container"]/div[4]/div[1]/div[1]/div/a/img'))) img_link = img.get_attribute("src") print("이미지 링크 : ", img_link) driver.quit() return render(request, 'rental_newlink.html', {'crawling_title':title, 'crawling_img_link':img_link}) else: #글을 쓰기위해 들어갔을 때 return render(request,'rental_newlink.html') ▲ views.py The problem is url = request.GET.get("urllink") in views.py results in None value(from <input type="text" name="urllink">) I think request.GET.get("urllink") can't parsing the <input> in html. I don't know the reason why it can't parsing the <input> and returns None value. Rest of the Code work fine. (Below print("url link : ", url_link) works fine.) -
Integrate python-social-auth to drf-spectacular (Swagger)
I have a Django (DRF) project with OAuth2 based on python-social-auth and Swagger based on drf-spectacular. I need to integrate these two libraries together so that Swagger allow OAuth2 authorization, for example Google OAuth2. I found OAuth2 configuration for drf-spectacular in settings: SPECTACULAR_SETTINGS = { ... 'SWAGGER_UI_OAUTH2_CONFIG': { ... # Oauth2 related settings. used for example by django-oauth2-toolkit. # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#oauth-flows-object 'OAUTH2_FLOWS': [], 'OAUTH2_AUTHORIZATION_URL': None, 'OAUTH2_TOKEN_URL': None, 'OAUTH2_REFRESH_URL': None, 'OAUTH2_SCOPES': None, }, ... } But I'm not really sure whether it fits me or not. I wrote this in my version of this config, but it appearently has no effect: 'SWAGGER_UI_OAUTH2_CONFIG': { 'OAUTH2_AUTHORIZATION_URL': 'https://accounts.google.com/o/oauth2/auth', 'OAUTH2_TOKEN_URL': 'https://accounts.google.com/o/oauth2/token', 'OAUTH2_SCOPES': ['openid', 'email', 'profile'], } Swagger still has no OAuth2. Any idea how to manage it? -
how to submit a form and display output without refreshing
I'm trying to create a simple calculator which gets an input number from the user and shows the calculated output below it. The code works fine but it redirects and reloads the page, obviously. I don't want that I want the output to be displayed as soon as the user fills the form. I have 0 knowledge of js and ajax so I would appreciate you guys helping me with that part. I searched a lot but couldn't understand what to do. this is my form: <form id="myform" method="POST"> {% csrf_token %} Enter first number: <input type="text" name="num1"><br><br> <input type="submit"> </form> and this is the output bellow the form I want: <h1>congrats!</h1> as simple as that. fill the form, submit and display a simple message without refreshing -
Ajax POST to an url then redirect to it
I'm building a web app where user can create markers on a leaflet map. Marker's details are saved in a backend with Django. My goal is to redirect the user to a detail page to fill marker's detail after clicking on the map. Here the js code to redirect to url create with an Ajax post. window.location.href = {% url 'create' %}; $.ajax({ url: {% url 'create' %}, data: { markers: markers_dict}, type: "POST" }).done(function (response) { console.log(response); }); but I'm struggling in the views.py because this redirect and AJAX post create two request one GET and another POST: def create_marker(request): if request.method == "POST": r = request.POST.get("markers") print(r) return JsonResponse({"response":"succeed"}) else: return JsonResponse({"response":"failed"}) It always returns the failed response even if it prints r in the console. How can I send these frontend data to the create url while redirect to this url and create a django from with these data ? -
How can I apply base.html file for extending to every template in django
Is there a way to extend base.html file in python django by default, I want it because I am overwriting {% extends %} tag in every html file -
Django ManytoMany Field Queryset for Exact and Similar Match
I have the following models: class Disease(models.Model): name = CICharField("Disease Name", max_length=200, unique=True) symptoms = models.ManyToManyField(Symptom, through='DiseaseSymptom', related_name='diseases') class Symptom(models.Model): name = CICharField("Symptom Name", max_length=200, unique=True) On the front-end, I have multiple select boxes where users can select multiple Symptoms to find disease and that will pass to Disease model as symptoms_selected params. I have the following get_queryset on Disease > views.py def get_queryset(self): params = self.request.query_params query_symptoms = self.request.GET.getlist('symptoms_selected') if query_symptoms: i = 0 queryset = Pattern.objects.all() while i < (len(query_symptoms)): symptom = [query_symptoms[i]] queryset = queryset.filter(symptoms__id__in=symptom) i=i+1 else: queryset = Pattern.objects.all() For eg: Disease Data: Disease A: Got Symptoms: A, B, C, D Disease B: Got Symptoms: A, D, P, Q Disease C: Got Symptoms: A, Q, X, Y Currently, if Users select 3 symptoms: A, D, Y. It returns Null. Instead of Null, I want to show users some similar matches with 2 and 1 symptoms. I want queryset will return: Exact match diseases i.e. 3 Symptoms matched diseases 2 Symptoms matched diseases 1 symptom matched diseases Can anyone tell me how can I achieve this? -
Input type file (multiple) not working in Django
I got a form with an input <form method="POST" enctype="multipart/form-data"> <input type="file" multiple> </form> When I upload files in that input, I'm trying to get those files with: request.FILES But I'm getting null object. Why is this happening? -
Django class based views: page "GET" content disappears after "POST" request is executed
I am building a homepage that has a dynamically updated blogs section and a BMI calculator section. Initially, the page loads perfectly fine. But the problem is that when I calculate the BMI (POST request) the page refreshes and the blogs section (GET) disappears. my urls.py urlpatterns = [ path('', HomeViews.as_view(), name='home_page'), my views.py class HomeViews(ListView, View): template_name="home_page.html" def get(self, request, *args, **kwargs): posts_diet = BlogModel.objects.filter(cat__title='Healthy Diet').order_by('-created_at')[:1] return render(request, 'home_page.html', { 'posts_diet' : posts_diet, }) def post(self, request, *args, **kwargs): if request.method == "POST": # get input height_metric = request.POST.get("height-metric") weight_metric = request.POST.get("weight-metric") #----bmi Formula----- if height_metric: bmi = float(weight_metric) / (float(height_metric)**2) else: bmi = 0 return render(request, 'home_page.html', { 'bmi': bmi, }) my home_page.html <div> {% for pst in posts_diet %} <div> <img src="uploads/{{ pst.blog_main_image }}" /> <div> <p>{{ pst.cat | striptags | slice:':50' }}</p> <p>{{ pst.created_at | date:"M d, Y" |striptags | safe }}</p> </div> <div> <h1>{{ pst.title | striptags | slice:':150' }}</h1> <button> </button> </div> </div> </div> {% endfor %} my terminal: # initial homepage request (everything loads perfectly fine) [24/Dec/2021 14:34:21] "GET /static/css/dist/styles.css HTTP/1.1" 200 30992 [24/Dec/2021 14:34:21,606] - Broken pipe from ('127.0.0.1', 65275) # on submitting POST request GET gets executed but GET content is … -
Django: Complex query sets take longer to execute
If I do an OR search filter on the fields of the model and the m2m model associated with it, the annotate, the query will take a long time to execute.(1500-2000ms) If I remove Q(tags__name__icontains=value) from the filter in the following queryset It works in about 30-50ms, so I think the cause is a problem with m2m. Filtering the m2m field from the model that is tied to m2m will loop through the entire through table, which in my opinion is time consuming. How can I rewrite the queryset to improve this? Video: 300k rows, Tag: 5k rows, video_tag_through: 1.3m rows # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=30) created_at = models.DateTimeField(default=timezone.now) ... class Video(models.Model): title = models.CharField(max_length=300) tags = models.ManyToManyField(Tag, blank=True) updated_at = models.DateTimeField(auto_now=True) ... class History(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Favorite(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Playlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_wl = models.BooleanField(default=False, editable=False) ... class Track(models.Model): playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... This may sound complicated and confusing, but the query set looks like this # query Video.objects.annotate( is_viewed=Exists(History.objects.filter(user=user, video=OuterRef("pk"))), is_favorited=Exists( Favorite.objects.filter(user=user, video=OuterRef("pk")) ), is_wl=Exists( Track.objects.filter( playlist__user=user, playlist__is_wl=True, video=OuterRef("pk") ) ), … -
how to make all letters lowercase in Django model?
I want to make both the integer choices uppercase in my models.py, but even though I write them uppercase (CASE1, CASE2), they don't change in browser? Why? class Cases(models.IntegerChoices): CASE1 = 1, CASE2 = 2, -
Django UpdateView not loading forms with styles
I created a form using Django's UpdateView class, however, when the form loads it seems like the text boxes and text areas are not styled (looks like form.as_p style). Here is an example of exactly what I did. Views.py class UpdatePostView(UpdateView): template_name = 'Post/UpdatePost.html' model = Post fields = ['Title', 'Body'] success_url = reverse_lazy('BlogApp:main') def form_valid(self, form): form.instance.Title = form.cleaned_data['Title'] form.instance.Body = form.cleaned_data['Body'] form.instance.save() return super().form_valid(form) Here is how I loaded the form in UpdatePost.html: <form id="UpdatePostForm" method="POST"> {% csrf_token %} <div class="form-group"> <label for="PostTitle">{{form.Title.label}}</label> {{form.Title}} </div> <div class="form-group"> <label for="PostBody">{{form.Body.label}}</label> {{form.Body}} </div> <input class="btn btn-primary" type="submit" for="UpdatePostForm" value="Update"> </div> </form> -
How to design django model for different products features of buyerSeller App
I am new to django and trying to make buyerSeller djangoApp in which they can list their products them self from single submit form. I have to lots of products features to be in one form but i want seperate model and also i have used Javascript to show/hide specific form fields with category selection. I am stuck to design model and link them, So please help me how to design model and link each other. class Category(models.Model): name = models.CharField(max_length=40,blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True) def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=40) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True) def __str__(self): return self.name class Listingproducts(models.Model): #Needs to be shown in all Category selections owner = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=200,null=True) price = models.IntegerField(null=True) isnegotiate = models.CharField(max_length=200, choices=negotiate, null=True) adsexpiry = models.CharField(max_length=200, choices=ads_expiry, null=True) deliverycharges = models.CharField(max_length=200,blank=True,null=True) isdeliver = models.CharField(max_length=200, choices=isdeliver, null=True) deliveryarea = models.CharField(max_length=200, choices=delivery_area, null=True) conditions = models.CharField(max_length=200, choices=condition_type, null=True) userfor = models.CharField(max_length=200, blank=True, null=True) descriptions = models.TextField(max_length=200,null=True) featured_image = models.ImageField(null=True, default='default.jpg') # --------- Vechicles Features list -------------------- lotno = models.CharField(max_length=200,null=True) enginecc = models.IntegerField(blank=True,null=True) kilometersrun = … -
JS gives me POST 404 (Not Found) when I try to update my models in django with fetch - even though the same code works for other function
I'm working on a small project and I'm trying to use JS fetch to delete an item (called script) from the read later for a specific user (ReadLater is a separate model in Django). Prior to writing this function, I also wrote the same function for adding and deleting notes of users (where Note is also a separate model) and the same code works as it should, but for some reason, when I try to remove from Read Later, in fetch I get Post 400 - not found. I've been busting my head for over an hour now, just looking at the code, but I don't see where I'm mistaken. What am I missing? URLs: urlpatterns = [ ... # API path("add_note/<int:script_id>", views.add_note, name="add_note"), path("delete_note/<int:note_id>", views.delete_note, name="delete_note"), path("read_later/<int:script_id>", views.read_later, name="read_later"), ... ] View: @csrf_exempt @login_required def read_later(request, script_id): """Removing selected script from read_later""" if request.method == "POST": try: script = Script.objects.get(pk=script_id) user = request.user data = json.loads(request.body) # Double-checking if remove is what we want if data.get('action') == 'remove': rl = ReadLater.objects.get(user=user, script=script) rl.delete() return JsonResponse({"message":"Removed from Read Later successfully."}, status=201) except Script.DoesNotExist: return JsonResponse({"error": "Script not found"}, status=404) else: return HttpResponseRedirect(reverse('index')) JS: document.addEventListener('DOMContentLoaded', function() { document.querySelector('#mp_read_later_view').addEventListener('click', function(e) { const … -
Login with custom css with Django
So i have a django web and i want in the login page to custom a background image by static files. I tried to do it but it seems that it doesn't read my static filed. settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static')] TNX! -
How to display data on Piechart from MYSQL database using django?
I am trying to extract data from the database and view the results on a pie chart, the charts should change dynamically when the values in the database change. But I am getting error in my script. Here is my view.py: def pie_chart(request): labels = [] data = [] queryset = Persons.objects.order_by('-id')[:3] for city in queryset: labels.append(city.firstname) data.append(city.salary) return render(request, 'breedingherdsummary.html', { 'labels': labels, 'data': data, }) Model.py: class Persons(models.Model): id = models.IntegerField(primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) address = models.CharField(max_length=100) dob = models.CharField(max_length=100) salary = models.IntegerField doj = models.DateField class Meta: db_table = "test" Here is my script: <script> var config = { type: 'doughnut', data: { datasets: [{ data: {{ data|safe }} , backgroundColor: [ '#FFA07A', '#E9967A', '#FA8072', '#F08080', '#CD5C5C' ], label: 'Salary' }], labels: {{ labels|safe }} }, options: { responsive: true, innerRadius: "40%" } }; window.onload = function() { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> Any help will be highly appreciated. Thank You!