Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: is there a simple way to store choices on the database
Seems basic as a need but I cannot find a way to store Django choices (the actual list of tuples) in database. My use case it that I have a Django app with multiple models and fields with choices. At the app level, I can always get the mapping from field value using get_foo_display or accessing the tuple, but it seems that it’s not actually stored on the DB. Considering that I connect to the DB directly for some stats and BI, I’m missing the mapping for my analysis and reports. Unless there’s some technique to do so, I guess I’ll create a « supporting » model to store the mappings. I would really appreciate your inputs/thoughts. Thank you. -
django_rest_framework: how to write an update_partial() method in a nested serializer to add or remove an object
I've been reading all over the internet and cannot find the answer to this question. below I have two datasets, dataset A and dataset B. I need to write a partial_update() serializer method which merges the two of them, drops duplicates based on the datasets timestamp key and results in the final dataset at the bottom of the question. I currently have the code below in the serializers.py section which results in a response 500 error. serializers.py 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_final = instance_is.extend(is_income_statements) instance.income_statements = instance_is_final instance.save() return instance dataset A ( stored in db ) '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': '10505000000.0', ... , ... , ... , 'timestamp': '1475193600.0' }, { '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': '10505000000.0', ... , ... , ... , 'timestamp': '1506729600.0' } dataset B ( sent in requests.patch … -
Run startup code when wsgi worker thread restarts
I have a django project running a wsgi application using gunicorn. Ahhh too much for the python newbie like me. I have a below gunicorn command which runs at the application startup. exec ./env/bin/gunicorn $wsgi:application \ --config djanqloud/gunicorn-prometheus-config.py \ --name "djanqloud" \ --workers 3 \ --timeout 60 \ --user=defaultuser --group=nogroup \ --log-level=debug \ --bind=0.0.0.0:8002 Below is my wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'djanqloud.settings' application = get_wsgi_application() gunicorn command shown from "ps- -eaf" command in a docker container: /opt/gq-console/env/bin/python2 /opt/gq-console/env/bin/gunicorn wsgi:application --config /opt/gq-console//gunicorn-prometheus-config.py --name djanqloud --workers 3 --timeout 60 --user=gq-console --group=nogroup --log-level=debug --bind=0.0.0.0:8002 Their is one simple thread which I create inside django project which are killed when above worker threads are killed. My question is: Is there anyway where I can create my threads AGAIN when the above worker threads are auto restarted ? I have tried to override the get_wsgi_application() function in wsgi.py file but got below error while worker threads are booted: AppImportError: Failed to find application object: 'application'. I am new to python django and wsgi applications so please try to elaborate your answers. Basically I am looking for a location where I can keep my startup code which runs when the … -
using get_absolute_url and showing an error of Reverse for 'article-detail' not found. 'article-detail' is not a valid view function or pattern name
I am using class based views to create a post. I have used get_absolute_url to go to the post page after clicking on post but it is giving an error of no reverse match. this is my modelspy from django.db import models from django.conf import settings from django.urls import reverse # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length = 50 , null=False,blank=False) body = models.TextField(max_length = 5000 , null=False,blank=False) date_published = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('article-detail', args=(str(self.id))) this is my urls.py: urlpatterns = [ path('',views.home,name="home"), path('home2/',HomeView.as_view(),name = "home2"), path('article/<int:pk>',ArticleDetailView.as_view(),name = "article-detail"), path('add_post/',AddPostView.as_view(),name="add_post"), ] this is home2.html: <ul> {%for post in object_list %} <li><a href="{%url 'post:article-detail' post.pk %}">{{post.title}}</a>-{{post.author}}<br/> {{post.body}}</li> {%endfor%} </ul> -
Can't preview the clicked button value
I am trying to preview the values of a bunch of buttons whenever they clicked. I already asked a question here and solved a part of my problem. however there is a small bug which stopped me for long time. This is the mytemplate.html(which almost does what I expect): <div id="preview-items"> </div> <script> $("#id_country").change(function () { var countryId = $(this).val(); // get the selected country ID from the HTML input success: function (data) { $('#preview-items').html(''); for (var i in data.tags) { $('#preview-items').append(` <label class="btn btn-primary mr-1"> <input type="checkbox" id="checklist" value="` + data.tags[i][0] + `"> <span> ` + data.tags[i][1] + ` </span> </label><br />` ); } } }); </script> And this is the script to preview the value of clicked buttons <script> $(function() { $(":checkbox").change(function() { var arr = $(":checkbox:checked").map(function() { return $(this).next().html(); }).get(); $("#preview-items").html(arr.join(', ')); }); }); </script> When I replace the first script with a simple button like below, it works perfectly: <div> <label class="btn btn-primary mr-1"> <input type="checkbox" id="Checklist" value="{{ item.0 }}"> <span> ITEM </span> </label> </div> Please help, I am spending too much to find just a tiny bug. -
Are there alternate methods for Django User authentication?
Can I authenticate users using a 'secret' and a registered IP? For each user I want to have a provide a 'secret' (a simpler password) and registered IPs (their home and work IPs). Then I want to allow access to certain pages only when Logged in using this method? Is this feasible? Any suggestion on how to achieve this is welcome. Bit of background: the Django website allows users to connect to a CRM service that uses OAuth. Users manage multiple CRMs (belonging to multiple clients). They separate clients by creating a separate chrome profile to each client. Right now they have to login to the Django website in each profile to connect to the CRM OAuth. If I can identify users using an IP and secret, they don't need to login in each of their client chrome profiles, so makes the process easier and convenient. Besides they do not need access to the whole site while logged in using the secret, on the page that kicks off the OAuth process and the redirect page. -
How do I change this function which works in normal django to make it work with serializer?
Hey guys I have this feedback create function which I use with my django..but Iam trying to implement the rest api and I am not sure about how to continue and change this function. I am able to list all the feedbacks without any problem but don't know how to implement the create function. Help would be much appreciated. This is my model. class Action(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='actions', db_index=True, on_delete=models.CASCADE) verb = models.CharField(max_length=255) target_ct = models.ForeignKey(ContentType, blank=True, null=True, related_name='target_obj', on_delete=models.CASCADE) target_id = models.PositiveIntegerField(null=True, blank=True, db_index=True) target = GenericForeignKey('target_ct', 'target_id') created = models.DateTimeField(auto_now_add=True, db_index=True) to create the feedback def create_action(user, verb, target=None): now = timezone.now() last_minute = now - datetime.timedelta(seconds=30) similar_actions = Action.objects.filter(user_id=user.id, verb= verb, created__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = similar_actions.filter(target_ct=target_ct, target_id=target.id) if not similar_actions: action = Action(user=user, verb=verb, target=target) action.save() return True return False serializer class GenericActionRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, Post): serializer = PostListSerializer(value) return serializer.data if isinstance(value, Comment): serializer = CommentSerializer(value) return serializer.data class ActionFeedSerializer(serializers.Serializer): #TODO user = UserSerializer(read_only=True) verb = serializers.CharField() target = GenericActionRelatedField(read_only=True) created = serializers.DateTimeField() class Meta: model = Action fields = ['user', 'verb', 'target_ct', 'target_id', 'target', 'created'] Thanks a lot guys! -
Problems posting images from react to Django Rest API using redux
I'm trying to post an image in my Django API from a react form with no luck. I'm also using the image uploader from AntDesign library and redux. Here's the code I've tried so far: -Form Code: class ArticleForm extends React.Component { this.props.onSendNewArticle( fieldsValue.upload.fileList[0]); render() { <Form.Item name="upload" label="Image" onPreview={this.handlePreview}> <Upload accept=".jpeg, .png" beforeUpload={() => false}> <Button> <UploadOutlined /> Choisir une image </Button> </Upload> </Form.Item> } const mapStateToProps = (state) => { return { loading_add_article: state.add_article.loading_add_article, error_add_article: state.add_article.error_add_article, }; }; const mapDispatchToProps = (dispatch) => { return { onSendNewArticle: (image) => dispatch(actions.articleAdded(image)), }; }; export default connect(mapStateToProps, mapDispatchToProps)(CourseForm); -Here's my view.py class ArticleCreateView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): article_serializer = ArticleSerializer(data=request.data) if article_serializer.is_valid(): article_serializer.save() return Response(article_serializer.data, status=status.HTTP_201_CREATED) else: print('error', article_serializer.errors) return Response(article_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -Here's my store/actions/addArticle.js: export const articleAdded = ( image) => { return (dispatch) => { dispatch(articleDispached); axios .post("http://localhost:8000/api/create/", { img: image }) .then((res) => { const course = res.data; dispatch(articleAddSucess(course)); }) .catch((err) => { dispatch(articleAddFailed(err)); }); }; }; Here's the error that I get: POST http://localhost:8000/api/create/ 415 (Unsupported Media Type) -
APScheduler for creating and loading model
I have a recommendation system project made on python/django. Now I have one Main_Trainer file that trains a recommendation model and I have one Main_Recommender file that gives a recommendation. In my apps.py, I am checking whether the recommendation model is present as a pickle file or not. If present, I am loading the pickle file in a variable there so that it can be used by Main_Recommender file for giving recommendations and I don't have to load model again and again and hence performance is enhanced. If recommendation model is not present, before initializing variable I'm calling the main_trainer function in Main_Trainer file and then loading the pickle file in a variable. Now I want to place a scheduler here such that my trainer runs everyday at 11pm so that my model pickle file is replaced and then load the model pickle file again in the variable. By the time model trainer is running at 11pm, I want my project to use existing file for the recommendation and after the model is created, suppose at 11.30pm, I want my model variable to get refreshed. How can we achieve this scenario? -
Validation not ocurring for custom field type in Django
I'm attempting to make a custom type in Django: from django.db.models import DecimalField from django.core import validators from django.utils.functional import cached_property class MinOneHundredDecimalField(DecimalField): @cached_property def validators(self): return super().validators + [ validators.MinValueValidator(100, "Minimum value is 100"), ] And I use this in my model: class MyModel(BaseModel): amount = MinOneHundredDecimalField( decimal_places=2, max_digits=6, ) However when testing, I'm able to set amount to a value less than 100: def test_min_val(self): my_model = MyModel(amount=50) my_model.save() self.assertNotEqual(my_model.amount, 50, "Message here") I also tried adding the validator directly in the model, but I get the same result: amount = MinOneHundredDecimalField( decimal_places=2, max_digits=6, validators=[MinValueValidator(100.0, "Minimum value is 0")] ) Any ideas why this validator isn't working? Ty! -
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= …