Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I count all elements in loop "for in" in Jinja2 templates Django
I tried to use loop: user_list = <QuerySet [<TableUsers: Jane>, <TableUsers: Kate>, <TableUsers: Jons>, <TableUsers: Jacob>, <TableUsers: Jane>, <TableUsers: Jons>, <TableUsers: Jane>]> {% for user in user_list %} {% if user.name == "Jane" %} {{all_count_username_jane}} # this is all count user with name Jane {{user.name}} {% elif user.name == "Jons" %} {{all_count_username_jons}} # this is all count user with name Jons {{user.name}} {% endif %} {% endfor %} How can I count all "Jane" and "Jons"? -
Django Public user profile + user's posts
I hope you're well. I'm beginning with Django. I'd like to create - like facebook - a public profile. I've already created a UserProfileUpdateView with country, adresse, image, ... When a user post something I'd like to have a link to his public profile (country, adresse, image, ... + posts): class UserPostView(ListView): template_name = 'user_post.html' model = Post context_object_name = 'posts' def get_context_data(self, **kwargs): context = super(UserProfileView, self).get_context_data(**kwargs) context['userprofile'] = UserProfile.objects.get(user=self.request.user) return context def get_queryset(self): return Post.objects.filter(user=self.kwargs['pk']) A - I'd like to display the public profile link with username (which is unique) and not with a number. Does anyone has an idea about how I can solve this? path('<int:pk>/',UserPostView.as_view(),name="user_posts"), -
ReactJS API calls to Django REST - use IP or localhost?
I run a ReactJS front end application and Django REST back end/API both on the same webhost. The application works perfectly fine on localhost, however when you run it from somewhere else it can't seem to connect to the API. Console of client's browser: Django REST running on the server: Am I supposed to connect to it using the external IP of the server instead of localhost? Localhost should work right, since both the frontend and Django API are hosted on the same server? -
Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$']
I am working on a Small Django Blog project but got stuck with this error:- NoReverseMatch at / Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$'] Exception Location: /home/manish/Videos/open-source/Blog-Env/lib/python3.8/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 Python Executable: /home/manish/Videos/open-source/Blog-Env/bin/python Python Version: 3.8.2 Python Path: ['/home/manish/Videos/open-source/Blogger/mysite', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/manish/Videos/open-source/Blog-Env/lib/python3.8/site-packages'] Server time: Sat, 22 Aug 2020 14:40:46 +0530 Here's the Django codes:-urls.py from django.urls import path from .views import ( PostDetailView, PostUpdateView, PostDeleteView, PostListView, about, post_create, Profileview ) urlpatterns = [ path("", PostListView.as_view(), name="blog-home"), path("about/", about, name="blog-about"), path("profileview/<name>", Profileview, name="blog-profile"), path("post/<int:pk>/", PostDetailView.as_view(), name="post-detail"), path("post/<int:pk>/update/", PostUpdateView.as_view(), name="post-update"), path("post/<int:pk>/delete/", PostDeleteView.as_view(), name="post-delete"), path("post_create/", post_create, name="post_create"), ] Here's the views.py file:- from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Post from django.views.generic import ListView from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import DetailView, UpdateView, DeleteView from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import PostForm from django.db.models import Q class PostDetailView(DetailView): model = Post ............ ............ Here's the base.html file:- {% load static %} <!doctype html> <html lang="en"> … -
Django timezone gives wrong result even though USE_TZ = True
I have a model like this: class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(default=timezone.now()) The date_added displayed in the template: {% localtime on %} {{ entry.date_added|date:'d M, Y H:i'}} {% endlocaltime %} As suggested in https://docs.djangoproject.com/en/3.0/topics/i18n/timezones. In my setting.py, my USE_TZ = True However, the output gives medatetime.datetime(2020, 8, 22, 9, 20, 16, 439533, tzinfo=<UTC>) or 22 Aug, 2020 9:20 in my webpage Why does the output be in UTC? In my understanding, aware datetime means it follows the user's timezone. My timezone is UTC+7, so it must be 22 Aug 2020 16:20. I've read Retrieve timezone aware DateTimeField in Django that suggests changing TIME_ZONE = but wouldn't that makes it unaware? What can I do to fix it? I expect the datetime follows the user's timezone Thank you -
Integrity Error: NOT NULL constraint failed: users_profile.user_id
I want to implement update User Profile,in django rest framework. I am getting the above mentioned error, no matter what I try and change in my code. Below is the the code for my user serializers, user model and api views. users/api/serializers.py: from rest_framework import serializers from ..models import User,Profile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username','first_name','last_name','phone','id') class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Profile fields = ('user', 'bio', 'image') def update(self,instance,validated_data): user_data = validated_data.pop('user',{}) user = instance.user instance.bio = validated_data.get('bio',instance.bio) instance.image = validated_data.get('image',instance.image) instance.save() return instance Is there anything wrong in my serializer, cause I tried hardcoding and saving a particular user profile also by using for ex: instance.user.id = 21 and then saving it, but i get the same error Is there anything wrong in my serializer, cause I tried hardcoding and saving a particular user profile also by using for ex: instance.user.id = 21 and then saving it, but i get the same error users/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.conf import settings import os import random import string class MyAccountManager(BaseUserManager): def create_user(self,phone,username,first_name,last_name): if not phone: raise ValueError("Users must have a valid phone number") if not username: … -
django rest framework update instance to include dicts with different keys
The purpose of this specific part of the program is to scrape a website returning a list of dictionaries compare the scraped list of dictionaries to the dictionaries which are stored for timestamp key value pair differences ( see data structure below ) add to the list of already stored dictionaries the scraped dictionaries with different timestamps ( this is implemented in the serializers.py partial_update() function ) when running request.patch with data that has differing timestamps I get a <Response [500]> Internal Server Error I have listed the serializers.py and data structure below. what am I doing wrong here ? should I be implementing something in the viewset partial_update() function as well ? thanks ahead of time for your help. serializers.py ( partial_update() function ) def partial_update(self, instance, validated_data): instance_is = instance["income_statements"] instance_timestamps = [x["timestamp"] for x in instance_is] if "income_statements" in validated_data: is_data = validated_data.pop("income_statements") is_data_timestamps = [x["timestamp"] for x in is_data] is_time_stamp_diff = [ x for x in is_data_timestamps if x not in instance_timestamps ] is_income_statements = [ x for x in is_data if x["timestamp"] in is_time_stamp_diff ] instance_is.extend(is_income_statements) instance.income_statements = instance_is data structure 'income_statements': [ { 'net_income_continuous_operations': '45687000000.0', 'tax_effect_of_unusual_items': '0.0', 'net_income_from_continuing_operation_net_minority_interest': '45687000000.0', 'total_operating_income_as_reported': '60024000000.0', 'basic_average_shares': '5470820000.0', 'reconciled_depreciation': … -
Do I need CSRF-protection without users or login?
I am building a Django application where people can register for events. Everyone can register, there's no user account or login, i.e. no authentication. Verification is done through an an email with a link that has to be clicked in order to activate the registration. I'm unsure whether I need to enable CSRF-protection for these forms. It boils down to the following question: Is CSRF-protection necessary for every POST-request (which doesn't leave the domain) or only for POST-requests by logged-in users? What could be done with a CSRF-attack? I know you can use it to circumvent the same origin policy and post whatever you want in the name of the user, but can you also use it to alter a real post by the user or steal their data? If a malicious site could learn the data the user posted or silently alter their request that would be a reason for me to use it. If it just means that another website can create additional registrations then no, because so can everyone else. (I know that it doesn't cost much to just use it everywhere and I might in fact do that, but I'm trying to understand the principle better) -
Advance Product Filter in django using Ajax
def fetch_data(request): if request.GET['action']: print("yes action") # *********************************************** l = list(); posts=UserPosts.objects.all() for bk in posts: ser = UserPostsSerializer(bk) l.append(ser.data); # print(ser.data); data2 = json.dumps(l) #make json data json_data = json.loads(data2) #convert JSON data in readable form return render(request,'services/all_service_data.html',{'json_data':json_data}) # *********************************************** if request.GET['brand']: print("Brand") return HttpResponse("Brand") json_data = "Yes Brand" return render(request,'services/all_service_data.html', { 'json_data':json_data, } ) else: json_data = "Data not found" return render(request,'services/all_service_data.html', { 'json_data':json_data, } ) <div class="form-group"> <ul class="list-unstyled"> {% for SC in SPCategory %} <li> <label for="option1"> <input type="checkbox" class="common_selector brand" value="{{ SC.ID }}"> {{SC.OccuName}} {{SC.SubOccuName}} </label> </li> {% endfor %} </ul> </div> <!-- start row of display data--> <div class="row filter_data"> </div> <!-- closed row of display data--> <style> #loading { text-align:center; background: url('{% static 'loader.gif' %}') no-repeat center; height: 150px; } </style> <script> $(document).ready(function(){ filter_data(); function filter_data() { $('.filter_data').html('<div id="loading" style="" ></div>'); var action = 'fetch_data'; var brand = get_filter('brand'); // alert(brand); $.ajax({ url:"{% url 'fetch_data' %}", #fetch_data is django function method:"GET", data:{action:action, brand:brand}, success:function(data){ $('.filter_data').html(data); } }); } function get_filter(class_name) { var filter = []; $('.'+class_name+':checked').each(function(){ filter.push($(this).val()); }); return filter; } $('.common_selector').click(function(){ filter_data(); }); }); </script> -
User() got an unexpected keyword argument 'gender'
I have added two new columns 1.gender, 2.pinCode in PostgreSQL auth_user table and now I trying to post data in the table through Sign Up form to create a new user Please let me know how to fix this issue, I'm stuck at this from last few days. error - User() got an unexpected keyword argument 'gender' views.py from django.shortcuts import render, HttpResponse, redirect from django.contrib.auth.models import User def login(request): pass def signup(request): if request.method == 'POST': firstName = request.POST['firstName'] lastName = request.POST['lastName'] mobileNum = request.POST['mobileNum'] emailID = request.POST['emailID'] passFld1 = request.POST['passFld1'] passFld2 = request.POST['passFld2'] gender = request.POST['gender'] pinCode = request.POST['pinCode'] myUser = User.objects.create_user(username=mobileNum, password=passFld1, first_name=firstName, last_name=lastName, email=emailID, gender=gender, pinCode=pinCode) myUser.save() print('User Created Successfully') return redirect('/') else: return HttpResponse('Not Allowed') # return render(request, 'index.html') urls.py from django.urls import path from . import views urlpatterns = [ path('login', views.login, name="login"), path('signup', views.signup, name="signup"), ] models.py from django.db import models from django.contrib.auth.models import User class NewUserModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) new_field_name = models.CharField(max_length=100) HTML <form method="POST" action="signup" id="signUpForm" class="login100-form validate-form"> {% csrf_token %} <div class="login-title mb-5">Create an Account</div> <div class="row"> <div class="col-md-6"> <div class="wrap-input100" data-validate="Invalid Name"> <input class="input100 text-capitalize" onkeypress="return isAlphabet(event)" type="text" maxlength="15" name="firstName" required> <span class="focus-input100" data-placeholder="First Name"></span> </div> </div> <div … -
Django Password Field Not Rendering with Bootstrap Attributes
I was trying to style my password fields in the registration of my Django Accounts App. 'password1': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password', 'required': 'required'}, ), 'password2': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Confirm password', 'required': 'required'}, ), My view renders to the register.html which is in the code below <div class="col-12 mt-4"> {{ form.password1 }} </div> <div class="col-12 mt-4"> {{ form.password2 }} </div> </div> But the result for the Password field is not styled as the other fields. The rendered register page is as shown below rendered register.html page What could be the fix to give the following output expected output -
Add Headers Expires for only two CDNs (django)
I have been searching for a while but couldn't find anything that helped, I am starting out a new website and Yslow gave me a bad reading cuz I don't have expires header, I also found in the report that the website takes 1.5 sec to load jquery and .7 for bt4 All that I want to do is add expires headers for those two ONLY and nothing else as I will be constantly updating the website, but of course, I will rarely be changing jquery or bootstrap4 is there any way to make it possible? (Add Expires Headers to Jquery and bootstrap only) IF NOT is there any way to make jquery load after other HTML elements have fully loaded without putting it at the end of the HTML page? cuz if I did that I won't be able to use it in other templates that extends that base html (django) -
How does Web Browser open offline ip address just like Jupyter notebook?
I was using Jupyter notebook and was wandering how does it works offline. Where does server is? How TCP connection is made? How does htpp request is sent? Similarly when we are working on some website project (eg: making one website in django) when you compile that html code in your terminal, it provides you an output with an ip address and when you run that ip address in your browser, browser will show you your website. So how does this work and how that ip address it generated? Can anybody please explain me? -
I can acces the Django server using Windows 10 but I can't access after running the same code in Ubuntu 20.04 TLS
I started a project in Django using Ubuntu 20.04 TLS (I'm using Multipass). After running 'python manage.py runserver', it seems everything is working well: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 22, 2020 - 07:19:55 Django version 3.1, using settings 'Universidad.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However, when I try to access this address from my browser I can't access to it. I have done some tests: Changed the "127.0.0.1:8000" to "0.0.0.0:8000". It didn´t do anything different. I ran the same code using "virtualenv". It didn´t do anything different. I tested different browsers (Firefox, Brave, Opera). It didn´t do anything different. I ran the same code in Windows and, surprisingly, I can access "http://127.0.0.1:8000/" from my browser. It seems it is different running in Windows and running in Ubuntu. Is there any way to solve this issue to use Ubuntu? I feel the issue comes from using Multipass... Is it possible? -
Creating and Saving Access Tokens simplejwt Django
I've been following this tutorial:https://medium.com/@gerrysabar/implementing-google-login-with-jwt-in-django-for-restful-api-authentication-eaa92e50522d to try and implement a google based login from my front end, so far everything works in terms of the creating the account based on the google token and then creating the token using RefreshToken.for_user(). However, I tried testing my application by making a very simple view to test it via the permission classes as below: class VerifyAuthView(APIView): permission_classes = (IsAuthenticated,) def post(self,request): return Response({"status":"true"}) I get returned a 401 error when I try and access this. I have a couple ideas what it might be such as: I have noticed in the django admin panel under tokens there is none listed even immediately after creation, maybe the token is only being generated and not saving although I can't work out why I've seen a couple of people say it could be to do with rest_framework permissions classes, although changing these hasn't helped so far My Views.py (also contains my VerifyAuthView as above): from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.hashers import make_password from rest_framework.utils import json from rest_framework.views import APIView,status from rest_framework.response import Response import requests from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth.models import User class GoogleView(APIView): def post(self,request): payload = {'access_token':request.data.get("access_token")} #validating token req = requests.get('https://www.googleapis.com/oauth2/v2/userinfo',params= … -
Is Django-REST-framework stateless?
According to REST API principles: Stateless – Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. But django-rest-framework stores tokens in database (in authtoken_token table) and I delete a token to logout a user.If token is stored in server,is it really stateless? Or am I understanding it wrong? Thanks for answering! -
How can i host my django project on my computer and access it from anywhere in the world?
Is there any way to make my computer as a host for my django project and i can access my django project from anywhere in the world?3 -
How to display Instagram Profile Information in a Django Template
I have a model given below: class Listing(models.Model): account_name = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name='Account Name', null=True, blank=True) profile_username = models.CharField('Username', unique=True, max_length=200) class Meta: verbose_name = 'Listing' verbose_name_plural = 'Listings' def __str__(self): return self.profile_username profile_username is Instagram username. So the profile URL is like "https://www.instagram.com/cabinwellnessclinic/". What would be the steps to display the profile from the URL in a Django template? Any help would be much appreciated. -
I can't cut of image using "crop" of "pillow"
Question about django. Posted image from form was saved and cut it using "crop" of "pillow" then resize and save. the program was no problem in local, but it was not cuted as specified after deployed on vps (When I upload 5 images, the one or two images was not cuted as specified) . I just only deployed data of git. I don't understand the cause. Could you tell me, if you know the cause. Code print(int(x)) print(int(y)) print(int(w)) print(int(h)) pp = ImageTable.objects.filter(sort_id = st.sort_id) print(pp[count-1].image) im = Image.open('media/' + str(pp[count-1].image)) #'str(pp[count-1].image)' is for example like 'images/test.png' images path xx = int(x) + int(w) yy = int(y) + int(h) im = im.crop((int(x), int(y), int(xx), int(yy))) im.resize(size=(200, 200), resample=Image.BOX).save('media/' + str(pp[count-1].image)) I Tried About the code above. the code is looped by for function and upload five images. it upload different images for each loop because of count is plus 1 every loop. I confirmed x,y,w,h was as specified value by using print debug. Supplementary information I hardly changed, but I changed database to postgresql from db.sqlite3. Is this relevant. -
How to redirect a user to a different page if he's logging in for the first time after registration in django?
I have created a Getting Started page to which I have to send the users if they are logging in for the first time after registration. I also referred to this question but didn't understand anything If not I have to redirect them to the Home page. I have set the LOGIN_REDIRECT_URL to 'home' in settings.py I have not tried anything yet because I have no idea about how I should do it. Please assume a simple html for both the pages with an <h1> tag containing their respective names -
Posting form data with axios (Vuejs) to django forms.py and then to 3rd party service
As the subject reads above I'm trying to post the fields in a form. each field is bound with v-model and set in export default I can do a submit and then it does a post but when it hits Django it sends hardcoded data to the 3rd party service if I remove the hardcoded data in the payload the 3rd party service bombs out. but if I leave the hard coded data I get a response. views.py from django.views.generic import TemplateView from django.views.decorators.cache import never_cache from rest_framework import viewsets from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .forms import DjangoForm import requests # Serve Vue Application index_view = never_cache(TemplateView.as_view(template_name='index.html')) class TestRest(APIView): def get(self, reqeust, format=None): thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print("GET request received") return Response(thisdict) def post(self, request, format=None): print("POST request received") url = "http://localhost:8080/" payload = "{\r\n \"prefix\":\"thanks dude\",\r\n \"length\":\"100\",\r\n \"temperature\":\"0.7\",\r\n \"top_k\":\"40\"\r\n}" headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) return Response(response.text, status=status.HTTP_200_OK) def store_doPost(request): if request.method == 'POST': doPost = doPost(request.POST) Django_Form = DjangoForm(request.POST, request.FILES) if Django_Form.is_valid(): required_document_form.save() forms.py from rest_framework import serializers from django.db import models from django … -
How to build a nested comment system in django without django-mptt or any other library?
I'm working a blog in django and want to build a nested comment system but I don't want to use any library to achieve it.i want to know how big companies like instagram build comment section in python . I feel like I'm only learning to use libraries not learning to code. -
required with a concept of django user authentication and permissions
i am designing a project on online registration of students for an educational institution. Now that institution is having several schools registered under it. The School has a school id code and school name. Now i want a generalised login system for the school where they have their school id code as their login id and a standard password trend like school_ind@institution and as a second level authentication a sms based otp. Now when the school logs in it can register students for the exam and while registering the school id shown in school choices of student is the only the school id with which login has been done and in list view only students of that particular school shows up. the school login shud have the crud right for that schools student. how to implement this . -
No Access to files in S3 from Centos7 website on EC2
First time using AWS S3 here. I've been trying to figure this out the entire week but I just can't get my Django + NGINX site to display both my CSS and uploaded images from S3. I'm probably missing something but I just don't know exactly. I've looked into this, this, and this but I'm still unable to get things running. I have a Bucket Policy and a CORS Config in my bucket maybe you can take a look. What I have so far: My site works fine only without any CSS or other static files like images CSS and image file URLs are correct. They all direct to my S3 bucket. Image uploading has no problem saving to S3 To test, accessing each CSS/image manually from the browser returns the standard AccessDenied page from S3 I have an IAM role with the AmazonS3FullAccess policy applied to my EC2 instance All public access is blocked in my bucket My Bucket Policy For testing purposes, I created a user with AmazonS3FullAccess along with the role. Not sure if that's necessary... { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::<NUMBERS>:role/<MYEC2ROLE>", "arn:aws:iam::<NUMBERS>:role/<MYUSER>", ] }, "Action": "s3:*", "Resource": [ "arn:aws:s3:::<MYBUCKET>", … -
Editing of django form with primary key fields
I have a django model form for which I allowed partial form save since its a long form. Now I want the user to come back and complete the form later. There is one hindrance however that my database cannot accept duplicate entries with same primary key. So should I remove primary key in my database to solve this or is there another way to make it possible? Suggestions please.