Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PDF document does not contain utf-8 encoding
I am making an application on Django. You need to add html page to PDF document. The document is being created, but the Cyrillic alphabet is smeared with squares. #views.py def fetch_pdf_resources(uri, rel): if uri.find(settings.MEDIA_URL) != -1: path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, '')) elif uri.find(settings.STATIC_URL) != -1: path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, '')) else: path = None return path def export_pdf(request, pk): obj = get_object_or_404(Application, pk=pk) template_path = 'applications/applications_detail.html' context = {'applications': obj, 'to_pdf': True} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="ApplicationDetail.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(BytesIO(html.encode('UTF-8')), response, encoding='utf-8', link_callback=fetch_pdf_resources) return response #urls.py path('export_pdf/', views.export_pdf, name = 'export_pdf') -
Why am I getting this Django NoReverseMatch error?
I'm getting Django's dreaded "NoReverseMatch" error and I can't see the problem. I believe I'm doing everything correctly. When I try to go to the music application's home page at 127.0.0.1:8000/music/ I get the following error: NoReverseMatch at /music/ Reverse for 'album-delete' with arguments '(",)' not found. 1 pattern(s) tried: ['music/album/(?P<pk>[0-9]+/delete/$'] Here are my urls: # app/urls.py urlpatterns = [ path('music/', include('music.urls')), ] # music/urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('album/add/', views.AlbumCreate.as_view(), name='album-add'), path('album/<int:pk>/', views.AlbumUpdate.as_view(), name='album-update'), # Problem is with this url pattern: path('album/<int:pk>/delete/', views.AlbumDelete.as_view(), name='album-delete'), ] Here is the template calling the delete url: # music/index.html <form action="{% url 'music:album-delete' album.id %}" method="post"> {% csrf_token %} <input type="hidden" name="album_id" value="{{ album.id }}"> <button type="submit"></button> </form> Here is the class-based view to delete an album: # music/views.py class AlbumDelete(generic.DeleteView): model = Album success_url = 'music:index' The error is triggered by the form's action attribute because if I just set the action to blank, the error goes away. <form action="" method="post"> <!-- No error --> -
How do i get the username of a logged user writing a text and display it beside the text permanently in Django
Please see the image, i want to add name of the person entering the text at the end of the text. [1]: https://i.stack.imgur.com/qd5fn.png Here is my code for template. {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">add new entry</a> </p> <ul> {% for entry in entries %} <li> <b><p>{{ entry.date_added|date:'M d, Y H:i' }}</p></b> <p>{{ entry.text|linebreaks }}</p> <a href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a> </p> </li> {% empty %} <li> There are no entries for this topic yet. </li> {% endfor %} </ul> {% endblock content %} Here is my views function for topic. def topic(request, topic_id): """Show a single topic and all its enteries""" topic= Topic.objects.get(id=topic_id) entries= topic.entry_set.order_by('-date_added') context= {'topic': topic, 'entries':entries} user_if= request.user return render(request, 'learning_logs/topic.html', context) Here is my Topic and Entry models. from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): """A topic user is learning about""" text=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model.""" return self.text[:50] +"..." class Entry(models.Model): """Something specific learned about the topic""" topic=models.ForeignKey('Topic',on_delete=models.CASCADE) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural='entries' def __str__(self): """Return a string … -
Putting a Django app under a path on a webserver
I am developing a Django app, and testing it on http://localhost:8000 on the development server. My urls file has urls in the sorts of ; path('somepath1/', myviewclass.function1, name='view_name1'), path('somepath2/', myviewclass.function2, name='view_name2'), etc I have some static links to views in some of the templates using the {% url 'view_name1' %} tags. When I navigate the app, as I click links the paths work correctly : If I goto http://localhost:8000/somepath1/, and then click on a link to another view I get the url : http://localhost:8000/somepath2/ When I put the app on the webserver under the url : http://myserver.com/myapp, as I click the links and submit forms the paths start accumulating : If I goto http://localhost:8000/somepath1/, and the click on a link to another view I get the url : http://localhost:8000/somepath1/somepath2/, and that is not matched in the urls so I get a 404. How do I prevent this ? Thanks Regards -
Rest Framework Simple JWT: AttributeError at /api/token/
I'm using simple_jwt for authenticating Django_rest_api but getting this response on an attempt to login: AttributeError at /api/token/ 'str' object has no attribute 'decode' Packages: Django==3.1.4 djangorestframework-simplejwt==4.4.0 -
Django Child template not loading the form
I have a base Django template: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'CS/base.css' %}"> </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="/">Cheat Sheet</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'CS-home' %}">Home</a> <!-- <a class="nav-item nav-link" href="">About</a> --> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="#">Register</a> </div> </div> </div> </nav> </header> {% block body %} {% endblock body %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> And a Child Template home.html: {% extends "CS/base.html" %} {% block body %} {% endblock body %} {% block content %} <div class="container"> <form action="/URL/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </div> {% endblock content %} And my views.py function to load the home.html file: def home(request): context={} context['form']=urlForm return render(request,'CS/home.html',context) When I try to render the form in the child template … -
Django production server on digital ocean cant access images from spaces
When using a local server everything works perfectly. I can upload an image from my local server to Digital Ocean spaces I can open a url (from spaces) with my local server and convert it to bytes. url = 'https://wwww.myspaces.com/my-spaces-static/images/xxxxxxxxxxxxxxxx.png' ssl._create_default_https_context = ssl._create_unverified_context resp = urllib.request.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) The code above fails however when i switch from my local server to my digital ocean production server. I have recently created a domain and https access with letsEncrypt on my Digital Ocean droplet. I am uncertain to what i'm missing. Is this a problem with SSL? I am not sure how to correctly debug this to get more detail on why the code on my production server is failing. -
Problems Rendering a function in Django
@smokesignal.on('rfid') def _RFID_cb(request,payload): print(payload) context={"payload":payload,'tableheader':['EPC-96','AntennaID','PeakRSSI','LastSeenTimestampUTC','TagSeenCount']} return render(request,"index.html",context) def tag_seen_callback(llrpMsg): """Function to run each time the reader reports seeing tags.""" tags = llrpMsg.msgdict['RO_ACCESS_REPORT']['TagReportData'] #print(tags) if tags: smokesignal.emit('rfid', { 'tags': tags, }) The print shows : [{'EPC-96': b'8a4b6028555555558a4b6028', 'AntennaID': (1,), 'PeakRSSI': (-43,), 'LastSeenTimestampUTC': (1608938708959031,), 'TagSeenCount': (1,)}] When I try to render the _RFID function I get this error: builtins.TypeError: _RFID_cb() missing 1 required positional argument: 'payload' -
How to change the default settings of warpdrive in a django Docker file?
I'm using Docker to build a Django Application using Apache and mod_wsgi(python package). I followed this tutorial by Graham Dumpleton (https://www.youtube.com/watchv=H6Q3l11fjU0&list=PLW4uuEXFgYkPDCwo7kT73P6SYVbvvIDl4&index=6&t=2s). I'm using warpdrive package because it automates few tasks like installing requiments.txt, using mod_wsgi as a default WSGI server, and a few more. The default settings of warpdrive are 5 threads and 1 process which I think is too low for my Django API as you can do only 5 concurrent requests (threads*process=concurrent requests). How to change the default threads, processes, and other configurations of warpdrive? I tried using the below command in the Dockerfile but it didn't change the threads. CMD [ "warpdrive", "start" ,"--threads","10"] Dockerfile FROM python:3 RUN apt-get update && \ apt-get install -y --no-install-recommends apache2 apache2-dev locales && \ apt-get clean && \ rm -r /var/lib/apt/lists/* ## Installing MS ODBC SQL SERVER 2017 for pyodbc library RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - RUN curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list RUN apt-get update && ACCEPT_EULA=Y apt-get install -y msodbcsql17 RUN apt-get update && ACCEPT_EULA=Y apt-get install -y mssql-tools RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc RUN /bin/bash -c "source ~/.bashrc" RUN apt-get install unixodbc-dev RUN adduser --disabled-password --gecos "Warp Drive" --uid 1001 … -
Logged in user information incorrectly dispalyed
I have created a page to update User profile. If I try to update a value of user with existing user, error is thrown as expected, however the variable user.username in profile.html shows the value I am trying to update. My query is why {{ user.username }} is picking up the incorrect value even though the save() method is not called. profile.html <div class="content p-3"> <div><img class="rounded-circle" src="{{ user.profile.image.url }}" width="100" height="100"></div> <div>{{ user.username }}</div> <div>{{ user.email }}</div> </div> <div class="w-25"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> <legend>Profile Info</legend> {{ user_form | crispy }} {{ profile_form | crispy }} </fieldset> <input class="mt-3" type="submit" value="Update"> </form> </div> forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py @login_required def profile(request): if (request.method == "POST"): user_form = UserUpdateForm(request.POST, instance=request.user) profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if (user_form.is_valid() and profile_form.is_valid()): user_form.save() profile_form.save() messages.success(request, f"Your profile is updated successfully") return redirect("profile") else: messages.error(request, f"Failed to update profile") else: user_form = UserUpdateForm(instance=request.user) profile_form = ProfileUpdateForm(instance=request.user.profile) return render(request, 'User/profile.html', {'user_form': user_form, 'profile_form': profile_form} -
Why does ubuntu end up with different versions of python and pip and django gets installed globally instead of in the virtualenv?
I'm trying to learn django and i installed ubuntu bash on windows to use it there, ubuntu comes with python preisntalled but not pip so i installed pip and updated it but when i use pip3 -V it shows the past version, there is two pip installs and i can't figure out how to upgrade the one that python uses, also i installed django when i was already inside the virtualenv but it was installed globally, so i guess is because the same problem, does anyone know how can i have just one python and one pip installed? so none of this happens? i reinstalled ubuntu cuz got really annoyed. -
django get record which is latest and other column value
I have a model with some columns, between them there are 2 columns: equipment_id (a CharField) and date_saved (a DateTimeField). I have multiple rows with the same equipment_id and but different date_saved (each time the user saves the record I save the now date time). I want to retrieve the record that has a specific equipment_id and is the latest saved, i.e.: | Equipment_id | Date_saved | | --- ----- | --------------------- -------- | | 1061a | 26-DEC-2020 10:10:23| | 1061a | 26-DEC-2020 10:11:52| | 1061a | 26-DEC-2020 10:22:03| | 1061a | 26-DEC-2020 10:31:15| | 1062a | 21-DEC-2020 10:11:52| | 1062a | 25-DEC-2020 10:22:03| | 1073a | 20-DEC-2020 10:31:15| I want to retrieve for example the latest equipment_id=1061. I have tried various approach without success: prg = Program.objects.filter(equipment_id=id) program = Program.objects.latest('date_saved') when I use program I get the latest record saved with no relation to the previous filter -
How to remove a django _like index from a primary key
I am using a CharField in django to store a primary key. I have defined this as: id = models.CharField( max_length=64, default=create_id, primary_key=True, null=False, editable=False ) This results in my table having the following two indexes: CREATE UNIQUE INDEX api_participant_pkey ON public.api_participant USING btree (id) CREATE INDEX api_participant_id_cb12634b_like ON public.api_participant USING btree (id varchar_pattern_ops) The text in the id is meaningless, I am always going to query that field through an exact match, never using LIKE. Is there an easy way to remove the _like index? I've seen How to remove index varchar_pattern_ops in a django (1.8) migration? on how to remove the index when it is a field being indexed, but I am not sure how to do this for a primary or foreign key. I'm using postgresql and Django==2.2.13 and this is a live database I cannot just recreate. -
Cant see any return values using requests.post REST Django
So I am trying to communicate with an external API. The GET request is working fine but when I use the POST request I do not see any values in return. I know for a fact that everything up to the return is working fine because that if I use the shell, I can print the values of the serializer. I also know that the body of the message is correct because I am using Postman as well. Here is the views.py (I am using modelviewset): class Creating_Account(viewsets.ModelViewSet): queryset = GetInfo.objects.all() serializer_class = GetInfo_Modelserializers def create(self, request): URL = 'https://example.com/api' body = {'authenticationKy': settings.KEY} r = requests.post(url, json=body) json = r.json() serializer = GetInfo_Modelserializers(data=json) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) What I am supposed to see: What I am supposed to see What I see when I run the server: What I see when I run the server -
CSS file not affecting page in Django
I have created a navigation bar in html and css and want to implement it into a page. The HTML works fine, but the CSS is not effecting the HTML at all. I have setup my static files correctly and messed around with loads of settings to try and get it working. Any help would be great. I am pretty new to HTML and CSS so if I have made any mistakes, please highlight them. Thanks settings.py """ Django settings for completestudent project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'siv&qzku5zi8b!2d=%0@z2i34eje)$-t#ezbdot1-e9^zahgg@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #own apps 'expendetures', 'pages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] … -
Ec2 not properly reflecting github changes
I deployed my Django project to an ec2 server successfully but the code doesn't necessarily update properly. My first code pull worked successfully initially, but for some reason maybe depending on the browser, there's a 50/50 chance I'll have to refresh that page I updating to see the changes. Also, my second pull wasn't acknowledged at all. I added some tag links and they just don't show up? What could be going on here? -
Filter queryset for foreign key field in django admin
I have a built-in User model which is related to Profile model through one-to-one relation. Profile model has active_group field which is a ForeignKey field related to a built-in Group model. class Profile(models.Model): user = models.OneToOneField( User, ... ) ... active_group = models.ForeignKey( Group, ... ) ... Any user can belong to multiple groups and active_group represents what group is currently selected. In the admin section those models are represented as following. class ProfileInline(admin.StackedInline): model = Profile can_delete = False ... def get_fields(self, request, obj=None): fields = [..., 'active_group'] ... @admin.register(User) class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = CustomUserCreateForm ... inlines = [ProfileInline, ...] CustomUserChangeForm and CustomUserCreateFrom are heirs of UserCreationForm and UserChangeForm. I want to limit selection in active_group field to only those groups, which user belongs to instead of all existing groups. I tried to use render_change_form and formfield_for_foreignkey but neither worked. -
Rendering multiple dataframes from API calls in Django Views
I have a page that is meant to show company financials based on customers input(they input which company they're looking for). Once they submit, in the view function I want to create 5 API urls which then get the json data, create a list with the dates from 1 API result (they will all contain the same dates, so I will use the same list for all), then create new dictionaries with specific data from each api call, as well as the list of dates. I then want to create dataframes for each dictionary, then render each as html to the template. My first attempt at this I attempted to do all requests.get and jsons.load calls one after another in a try block within " if request.method == 'POST' " block. This worked well when only grabbing data from one API call, but did not work with 5. I would get the local variable referenced before assigned error, which makes me think either the multiple requests.get or json.loads was creating the error. My current attempt(which was created out of curiosity to see if it worked this way) does work as expected, but is obv not correct as it is calling … -
How to implement token authentication using httponly cookie in Django and Drf
I'm building an application with django , Drf and currently using vanilla JS as Frontend for now. I searched almost all through web on different use case for authentication on the web and I found out different links but these links seem to always favour the session authentication and token authentication. Using Django helps us with the session authentication as default so I decided to study the auth process using a token auth. While doing this, I initially used the localstorage as a store for my tokens gotten from the backend response after user authenticates, But for some reasons which are valid , most devs/engineers advise against using the localstorage as it prones one to xss attacks.. So I decided to implement the httponly cookie method, but I haven't seen a practical use of this done on Django, I've seen theories on implementing all these but haven't seen someone done this.. Please how can I use the httponly cookie with my token stored as a cookie with DJANGO EDIT I know a httponly cookie does not allow JavaScript to access a cookie, so I decided to do this. Django sends the cookie httponly with the token as the cookie User … -
Login system with Django, Kivy and SHA256
I've created a simple REST API to list and create users with Django REST Framework and I'm trying to integrate it with an Kivy app. I've used the django.contrib.auth.models.User as my user class, and passwords are being created as show below: serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user As I'm using the set_password function, my REST API gives me SHA256 hashed passwords when I list my users: GET /list/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "username": "user1", "first_name": "Katy", "last_name": "Smith", "email": "katysmith@domain.com", "password": "pbkdf2_sha256$216000$rV8FoNw98RYu$0pdfnA4HO+15o4ov4GZVMXiq0tLNJopfLDV++iPvC5E=" }, { "username": "user2", "first_name": "John", "last_name": "Smith", "email": "johnsmith@domain.com", "password": "pbkdf2_sha256$216000$q4wfz8tiFnnF$gmOuN7HJurbEqHykZ221UX8STcG9pAQ8WQTKF+qDtbw=" }, With that backend, I'm creating an app frontend with Kivy. I have a login screen that asks users to input their username and password. My thinking about how should I create a login system (as I'm just a student in programming) is: Use urllib.request to get the user list; Loop and check if the username provided is in the list; Check if the password provided is the password … -
Limit the time users use the software
I have an app program by Python3 and I want to limited the time users use this app(4 hours a day). My idea: Count and write the time to the hidden file, check the time when open (but users can delete this file( intentionally or by an antivirus program,...)) Count the time users use and send it to my Django website. When users open app, it check out time allowed to use remaining in my web, if the time is up, notify the user and close the app. It is possible? Is there any other way? Please give me a suggestion. -
DAMN ! worker 2 (pid: 2954) died, killed by signal 9 :( trying respawn ... Respawned uWSGI worker 2 (new pid: 3008)
I am using Pytorch with Django on ubuntu ec2. It works well without Nginx and apache but it fails with the server. DAMN! worker 2 (PID: 2954) died, killed by signal 9 :( trying respawn ... -
Djnago with Paypal for server site integration
I am using django 3 and django-paypal module, It's my first time with payment integration so Is there any better way to just add paypal like client site integration in production?? i am trying many tutorial docs but they are not sufficient ! it would be highly appreciated if anyone suggest me any best way and also with the links to follow . Thank you -
"This field is required" after submitting form in a filled field using django and AJAX
I have been trying to add ajax to my django project these past days and I am finding problems with the form submission and data displaying. When I submit a POST form with just one field (with required =True) it does not recognize the form as a valid form (do not pass the .is_valid if) and the form error says "This field is required": forms.py enter code here from django import forms import datetime class FriendForm(forms.Form): name = forms.CharField( required=True, widget=forms.TextInput(attrs={'class': 'special', 'id':'id_name', 'name':'name'})) views.py from django.http import JsonResponse, HttpResponse from django.shortcuts import render from django.core import serializers from .forms import FriendForm, form_busqueda_address from .models import Friend import json import requests from decimal import Decimal import decimal def indexView (request): form = FriendForm () friends = Friend.objects.all () return render (request, "index.html", {"form": form, "friends": friends}) def searchFriend(request): form = FriendForm () if request.method =="POST": form = FriendForm (request.POST) if form.is_valid(): form = FriendForm (request.POST) name = form.cleaned_data['name'] query = Friend.objects.filter(nick_name=name) responseData = serializers.serialize('json', list(query)) return JsonResponse(responseData, safe=False) else: print(form.errors) query = { 'errors': form.errors, } return HttpResponse(json.dumps(query), content_type="application/json") main.js $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for … -
Do I need to check if form.is_valid(): here?
I am doing the CS50 Wiki project as an assignment (it involves a wiki homepage with the ability to search, edit and add entries) and it seems to be working ok. My question is: when I did my edit_entry and new _entry functions as below, I didn't use if form.is_valid(): check, and my question is, why would one need to? Since, when a form data is left blank, Django forms will prompt me (as I understand). Assuming I just stay on the current page until the save button is pressed and the form is not blank is there anything wrong with the following? (In general I understood that Django checks the user form data, so am not too sure in what context the check is needed. (Yes, I'm new to this) Thanks all. def edit_entry(request, title): content = util.get_entry(title) data ={'content': content, 'title':title} if request.method == "POST": util.save_entry(title, request.POST['content']) return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) else: form = EditForm(initial= data) return render(request, "encyclopedia/edit.html", { "content" : content, "title":title, "form":form }) def new_entry(request): form = EditForm() if request.method == "POST": util.save_entry(request.POST['title'], request.POST['content']) return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) else: return render(request,"encyclopedia/new_entry.html",{"form":form})