Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why bootstrap 3 is not loading
Why bootstap is not loading I have provided the template code. {% extends "posts/base.html" %} {% load bootstrap3 %} {% block content %} <h4>Create New Post</h4> <form method="POST" id="postForm"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Post" class="btn btn-primary btn-large"> </form> {% endblock %} This is showing like this : enter image description here why bootstrap is not loading. How can I do it? -
serializer = objectserializer (data = request.data) how to add initial data for one field of serializer
I have a post method that I defined this on it: serializer = objectserializer(data = request.data) I want to give an initial data to one of the fields of serializer inside my put class(not in serializers.py) because I want each time user want to change user profile username shows by default. how can i do it? -
Display Manytomany
I have a little problem with a Django feature with the Manytomany. I explain myself I can add, to read the sobost stored in my manytomany. only downside when I try to display them, I can only in the console. I enclose my code so that you can enlighten me on the way that I should follow in order to successfully integrate them into my templates. this is my Views.py: def profil(request,id): parcour = [] Myarticle = Article.objects.filter(author=request.user) All = Article.objects.all() UserProfil=User.objects.get(id=id) get_parcours = Parcours.objects.filter(author=request.user) for i in get_parcours: p = Parcours(id=int(i.id)) article_in_parcours = p.articleList.all() parcour.append((p,article_in_parcours)) print(parcour) return render(request, 'blog/profil.html',{ 'Article_by_author' : Myarticle, 'All_article' : All, 'Profil' : UserProfil, 'Parcours_by_author' : get_parcours, 'Article_in_parcours' : article_in_parcours }) This my template : <h2>Mes parcours</h2> <div class="container"> <div class="row"> {% for i in get_parcours %} <div class="col-4" style="border:solid 1px;"> {% for item in parcour %} {{item}} {% endfor %} </div> {% empty %} <p>Aucun Parcours</p> {% endfor %} </div> </div> Thanks in advance ! -
Django - Sending OPTIONS request second time will append body data to request method
The issue is when there's content inside body with OPTIONS method, the second request will always fail with message Method Not Allowed. Printed the log and showed that the method became "{"username":"test","password":"test"}POST /member/login/ HTTP/1.1" 405 111. Problem is when the server has restarted, the first OPTIONS request will pass normally. Have tried with only POST and it works fine. Only OPTIONS has this issue. ENV details: python:3.6.5, django:2.1.3, drf:3.9.0, django-cors-headers:2.4.0 -
Django session_key not generating when saprating the frontend file from the server
I am creating a chatbot. and to manage the flow of chat, i am using request.session. When i am running the project directly from the server then it is working fine, session are properly managed and session key is also generating. But when i am saperating the frontend files form the django project and running the html file with the same base url, the project is running fine but session_key not generating. and the flow breaks. I am not getting what the problem is. so please help me to solve that problem. if there is any other alternative for session then please tell me how to use it. -
how to detect div value (Django rendered) change with MutationObserver
I am rendering a value from django backend to frontend, and I am trying to detect the div value change with MutationObserver. Below is my current code: MutationObserver part: window.addEventListener('load', function () { var element = document.getElementById('myTaskList'); var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; var observer = new MutationObserver(myFunction); observer.observe(element, { childList: true }); function myFunction() { console.log("this is a trial") console.log(element); console.log(element.innerHTML); } // setTimeout(function(){ // element.innerHTML = 'Hello World!'; // }, 1000); // // setTimeout(function(){ // element.innerHTML = 'Hello Space!'; // }, 2000); }); html part: <div hidden id="myTaskList">{{resultList | safe}}</div> I am rendering a string "dummyValue" to the div, but just don't see the value from the console.log() statements inside function. Thanks for the help. -
How does one pass arguments from the URL to a view before rendering a new page?
I am creating a stock portfolio app. The user has a list of stocks each of which has a link which looks something like 'http://127.0.0.1:8000/search/symbol=TSLA'. What I want to do is pass the stock symbol 'TSLA' to one of my views and simply print that string on the next page (for now). What I have done so far (did not include it in the code below) is to simply have some method in my SearchPageView called get_symbol and I tried to get the url from there and in my search.html template, I tried accessing that via {{ view.get_symbol }}. But this displays nothing. My set-up: views.py: class SearchPageView(TemplateView): template_name = 'search.html' urls.py: from django.urls import path, re_path from .views import SearchPageView urlpatterns = [ path('search/<string>', SearchPageView.as_view(), name='search_stock'), ] search.html: {% extends 'base.html' %} {% block content %} {% endblock content %} I know there's nothing above, all i'm asking for is how to pass the string 'TSLA' to my view then to 'search.html' then I can do what I need to do with it. I appreciate any help. -
django error while searching in unaccent way
models.py class KeySkills(models.Model): skills = models.TextField() versions = models.DecimalField(decimal_places=3,null=True,blank=True,max_digits=10,default=None) experience = models.DecimalField(decimal_places=3,null=True,blank=True,max_digits=10,default=None) user = models.ForeignKey(access_models.SeekerRegister,on_delete=models.CASCADE,related_name='key_skills',null=True,blank=True) def __str__(self): return "KeySkills" query: KeySkills.objects.filter(skills__unaccent__icontains='python') KeySkills.objects.filter(skills_text__search='python') error: File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 844, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 862, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1263, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1287, in _add_q split_subq=split_subq, File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1225, in build_filter condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1080, in build_lookup lhs = self.try_transform(lhs, name) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1126, in try_transform (name, lhs.output_field.__class__.__name__)) django.core.exceptions.FieldError: Unsupported lookup 'unaccent' for TextField or join on the field not permitted. Here i am trying to search using django ORM queries. And tring using above two way of queries but i am getting above error . Please have a look into my code. -
how overwrite Response class in django rest framework ( DRF )?
I want to overwrite Response class of django rest framework so that response back responsive dictionary contain three parameter message, status and data Hello dears all I try to change Response Class in DRF to pass two extra parameter ( message, status ) plus data provide by DRF serializer. message pass the message like Done, User Created or etc and status pass the message like fail or success or etc message and this message useful for reserve special code between frontend and backend. I want to if don't set this parameter return empty character or null result back to client side for example in success mode: { 'data': { 'value_one': 'some data', 'value_two': 'some data', 'value_three': [ 'value', 'value', 'value' ], }, } 'message': 'Done', 'status': 'success', } and in failure mode: { 'data': ['any error message raise by serializer',] 'message': 'Create User Failed', 'status': 'failure', } I search about my question and found this solution: if i inheritance DRF Response Class in my class and overwrite __init__ method and get message, data and status in this method and call init of parent with own data structure and use this responsive class in my functionality like this implement: from rest_framework.response … -
Django project deployment without API rate limit
Can I know if there is any free server for Django project deployment without API rate limit? -
Field \"createUaction\" of type \"CreateUaction\" must have a sub selection."
This is the first time I am using graphene, ain't have a good grasp over it. So basically making a blog, where the user can like posts, comments and add posts to his favourite, and follow each other. I have made a separate model for all user actions class user_actions(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) liked_post = models.ForeignKey(Post, related_name='post_likes', on_delete=models.CASCADE) liked_comments = models.ForeignKey(Comment, related_name='comment_likes', on_delete=models.CASCADE) fav = models.ForeignKey(Post, related_name='fav_post', on_delete=models.CASCADE) target = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE, null=True, blank = True) follower = models.ForeignKey(User, related_name='targets', on_delete=models.CASCADE, null = True, blank = True) def __str__(self): return self.user.username So I have made a mutation for all the actions, I am trying to follow the DRY Principe and sum them all in one, I might be doing something wrong here, New coder trying my best :D class UactionInput(InputObjectType): liked_post_id = graphene.Int() fav_post_id = graphene.Int() comment_id = graphene.Int() target_id = graphene.Int() follower_id = graphene.Int() class CreateUaction(graphene.Mutation): user = graphene.Field(UactionType) class Arguments: input = UactionInput() def mutate(self, info, input): user = info.context.user if not user.is_authenticated: return CreateUaction(errors=json.dumps('Please Login ')) if input.liked_post_id: post = Post.objects.get(id=input.liked_post_id) user_action = user_actions.objects.create( liked_post = post, user = user ) return CreateUaction( user = user ) if input.liked_comment_id: comment = Comment.objects.get(id=input.liked_comment_id) user_action = user_actions.objects.create( … -
For loop Count in django template
i want to display number of count in django template in sequence. Like if for loop iterate 5 time then it should print 1,2,3,4,5 in django template. users container string which i pass from views.py {% for users in users %} <tr> <td> FOR LOOP ITERATE COUNT </td> <td> {{ users.first_name }} </td> {% endfor %} -
Py 3.6 // Django 2.1.4 : Accessing User Profile mysteriously changes the status of user.is_authenticated to True
i have been having this problem for 2 weeks now i can't seem to solve it. i have a social website where user's can upload their resumés for recruiters to see. and when i access some user's profile, the Navbar acts as if i am logged in, which i am not. i tried fixing this issue by using get_queryset() but i couldn't manage to display user's profile data. so i stuck with get(). Here's a visual explanation: As you can see the navbar says Home/Login/Signin Now if i access John Doe's Profile, the navbar will switch to Home/Profile/Logout : Here's my code ! views.py: class HomeProfile(ListView): "Di splays all active users in db" template_name = 'profile/home_profile.html' queryset = MyModel.objects.filter(is_active=True) class Get_Profile(DetailView): "fetches user's profile" def get(self, request, pk): user = MyModel.objects.get(pk=pk) return render(request, 'profile/profile.html', {'user':user}) urls.py urlpatterns = [ path('homepage/profiles/', user_view.HomeProfile.as_view(), name='homepage'), path('homepage/profile/<int:pk>/', user_view.Get_Profile.as_view(), name='user-profile'), ] base_test.html <nav class="navbar navbar-expand-sm navbar-dark bg-dark sticky-top"> <a class="navbar-brand" href="{% url 'home' %}">Navbar</a> <button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="collapsibleNavId"> <ul class="navbar-nav ml-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="{% url 'homepage' %}">Home<span class="sr-only">(current)</span></a> </li> {% if not user.is_authenticated %} <li class="nav-item"> <a … -
I want to import a variable from another python file(Django)
I have an apps.py file in Django project where I have written some and I want to import a variable from there to another file. I want to import archive variable -
How to configure AWS ELB to use CDN as domain for Django admin static files from
This might be a very basic question but I am not able to find a solution. So problem is as follows: PROBLEM: I have a Django application running on AWS ECS clusters with gunicorn application behind it. Some of the static files in my app is being served by EC2 server and rest of them is migrated to CDN, where we manually set the domain of all static files to CDN host name. Now the problem is to migrate Django admin static files, for which neither I can manually change the host name, nor I can apply global STATIC_URL to use CDN, because some static files still need to be served from EC2 until we found a solution to migrate them to CDN as well. I tried redirecting static URLs to CDN at AWS ELB level but that's not working. I know the solution using nginx server putting in ECS library, that is my last resort because then I need to update my Docker Image, which I am not thinking to touch. I am looking for a clean solution, without changing my existing docker image. -
Django REST Framework - empty request body
I've just started messing around with Django REST today and wanted to create a PUT endpoint for a photo upload. The image is then to be saved to a local folder. I'm using the MultiPartParser but request.data and request.FILES are both empty? Anyone know how why that might be? Views.py: class ImageUploadView(APIView): queryset = Image.objects.all() parser_classes = (MultiPartParser,) def put(self, request, filename, format=None): print(request.FILES) return Response(status=204) models.py class Image(models.Model): file = models.ImageField(upload_to=user_directory_path) date_added = models.DateTimeField(auto_now_add=True) Here is my postman test enter image description here -
Heroku deployment API rate limit exceeded
I have one django project and try to deploy it on heroku server. There is one function in the project to save the processed data into sql db by for loop. It's ok for the first loop, but in the second loop, There is the error to show "list index out of range". I try to adjust the list so that if list length is not that long, the saving will be "NA". I just found that the last saving shows such text:{"error":"API rate limit exceeded","api-key":"54.204.136.114","count":"4","limit":"3"} Is this problem due to the API query limit of heroku? When I apply such function in local server, the function is just fine. So, how could I deal with it? -
django: test case development to check: a logged in user is redirected to different views based on staff status
I am a testing a Django Library application, for two types of Users: customers and library staff. In my views.py, this is the Class-based view for login, wherein if the logged in user is a customer, then on successful login, the customer is redirected to dashboard_customer else if the logged in user is a library staff member, then dashboard_staff class CustomerLoginView(View): def post(self, request): username_r = request.POST['customer_username'] password_r = request.POST['customer_password'] user = authenticate(request, username=username_r, password=password_r) if user is not None: # how to write test case to check the below LOC login(request, user) if user.is_staff: return HttpResponseRedirect(reverse('dashboard_staff', args=[])) else: return HttpResponseRedirect(reverse('dashboard_customer', args=[])) else: return HttpResponseRedirect(reverse('customer_login')) def get(self, request): return render(request, 'catalog/customer_login.html') This is the test case for Signing up a user(both customer and library staff): class CustomerLoginTestCase(TestCase): """ Test case for User Log in """ def test_login_view_get(self): # get request response = self.client.get(reverse('customer_login')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'catalog/customer_login.html') def test_login_view_post_success(self): # post request data = { 'customer_username': 'testuser1', 'customer_password': '1X<ISRUkw+tuK', } response = self.client.post(reverse('customer_login'), data) self.assertEqual(response.status_code, 302) """ how to check on successful login, the user is redirected to the appropriate dashboard(dashboard_customer/dashboard_staff) based on if user.is_staff or not? """ How to develop test case for checking that on successful login, the … -
How to run django app in allen NLP environment?
I want to use allenNLP to gather output by passing some value(create an API). But the problem is I don't know how to effectively do it. Note: If it's possible I want the allenNLP files in a utils folder in django project. -
Django and Ajax; Do I have to include parameters in url?
I'm beginner in Jquery. what I want to do is just pass parameter to views. What I did is like this. js function aFunction(this) { var $this = $(this) var groupId = $group.data('id')[0] var userId = $group.data('id')[1] $.ajax({ url:'/groups/' + groupId + '/do_something', data: { 'user_pk': userId, }, method: 'POST', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } and this code doesn't work (URL cannot be found) even though I set url like /groups/<group_pk>/do_something in urls.py But this code did work js function acceptRequest(group) { var $group = $(group) var groupId = $group.data('id')[0] var userId = $group.data('id')[1] $.ajax({ url:'/groups/' + groupId + '/do_something/' + userId, method: 'POST', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } and I set url like groups/<group_pk>/do_something/<user_pk> in urls.py What is wrong with the first code? I just want to pass userId to views and don't want to include it in urls if possible. -
Rendering error: Reverse for 'ph' with no arguments not found. 1 pattern(s) tried: ['(?P<answer>[^/]+)/ph\\-data/$']
I'm new to coding and here I'm trying to build website that simply take in what the user wants to see from selected range, as I run the server I'm face with this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'zigview'] Installed 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'] Template error: In template C:\Users\user\Desktop\Frouniter\FrounterWeb- postgreDB\zigview\templates\FrounterWeb\index.html, error at line 12 Reverse for 'ph' with no arguments not found. 1 pattern(s) tried: ['(?P<answer>[^/]+)/ph\\-data/$'] 2 : <html lang="en"> 3 : <head> 4 : {%load staticfiles%} 5 : <!-- Mobile resizing and bootstrap --> 6 : {%include 'FrounterWeb/Lib-includes/Mobile-Response.html'%} 7 : 8 : <!-- Javascript action--> 9 : {%include 'FrounterWeb/Lib-includes/JavaScript-action.html'%} 10 : 11 : <!-- Libary of chart and gage --> 12 : {%include 'FrounterWeb/Lib-includes/Gr aphs-files.ht ml'%} 13 : 14 : <link rel="shortcut icon" type="image/png" href="{% static 'FrounterWeb/img/Logo.png' %}"> 15 : <title>Frounter-Agrotech monitoring</title> 16 : 17 : 18 : 19 : 20 : </head> 21 : 22 : <body class="body" style="background-color:#f6f6f6"> Traceback: File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 156. response = self.process_exception_by_middleware(e, request) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 154. response = response.render() File … -
Django Model reverse relationship having a string with the name of it
I want to implement a Django Rest Framework view that returns the dependencies tree of a model instance object. This is the code for such view: class RoomTypeDependencies(viewsets.ViewSet): def list(self, request, pk): room_type = models.RoomType.objects.get(pk=pk) dependency_tree = self.get_object_dependencies(room_type) return Response(dependency_tree) def get_object_dependencies(self, instance): fields = instance.__class__._meta.get_fields() dependencies_to_return = [] for field in fields: print(field.name) if field.__class__.__name__ == 'ManyToOneRel': dependency_to_return = [] dependent_instances = getattr(instance, field.name) for dependent_instance in dependent_instances: dependency_to_return.append(self.get_object_dependencies(dependent_instance)) dependencies_to_return.append({field.__class__.__name__: dependency_to_return}) return Response({str(instance): dependencies_to_return}) Everything seems to work, but I expected getattr(instance, field.name) to return the dependent instances corresponding to the reverse relationship, just like using model_object_instance.reverse_relationshio_name pattern, but it returns a RelatedManager object instead. The problem in my case is that I have the reverse relationship name in a string variable (field.name). -
VueJS app can't access protected API endpoint on mobile browser
I'm having an issue with my Vue app regarding usage on mobile browsers. I have a protected API route on a Django backend that uses JWT for authentication/permission. When I authenticate, I save the JWT to localStorage and Vuex and pass it along as a header on each request (using axios) from the Vuex store. This all works fine on my laptop, but it does not work when accessing my site on mobile. I see 401 unauthorized error codes in my logs when accessing the site with my phone (iOS 12), so I assume that token is not being added as a header. Here's the code that I use to attach the header: import axios from 'axios'; import store from '../store'; const apiCall = axios.create(); apiCall.interceptors.request.use( config => { if (store.getters.isAuthenticated) { // Take the token from the state and attach it to the request's headers config.headers.Authorization = `JWT ${store.getters.getToken}`; } return config }, error => { Promise.reject(error) } ) export default apiCall; Here are my dev dependencies: "devDependencies": { "@vue/cli-plugin-babel": "^3.0.5", "@vue/cli-plugin-e2e-nightwatch": "^3.0.5", "@vue/cli-plugin-eslint": "^3.0.5", "@vue/cli-plugin-pwa": "^3.0.5", "@vue/cli-plugin-unit-jest": "^3.0.5", "@vue/cli-service": "^3.0.5", "@vue/eslint-config-airbnb": "^3.0.5", "@vue/test-utils": "^1.0.0-beta.20", "babel-core": "7.0.0-bridge.0", "babel-jest": "^23.0.1", "node-sass": "^4.11.0", "sass-loader": "^7.0.1", "vue-template-compiler": "^2.5.17" }, Is there something … -
What is django cleaning and validating when you're using form.is_valid, and form.cleaned_data?
So I'm creating a user registration form from a tutorial: def RegisterView(request): form = RegisterForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") new_user = User.objects.create_user(username, email, password) but the tutorial doesn't explain how django is cleaning the data, and how it knows the data is valid. -
How to acces a non returned CharField from models in my views?
Before I start, i want to clarify that I'm a beginner in django and so I'm learning.. This is my models.py class MyNote(models.Model): title_of_note = models.CharField(max_length=200) date_created = models.DateTimeField('Created') details_note = models.TextField(max_length=2500, default="") def __str__(self): return self.title_of_note and this is my views.py def index(request): notes_list = MyNote.objects.order_by('date_created') context = {'notes_list' : notes_list} return render(request, 'note/index.html', context) def detail(request, note_id): note = get_object_or_404(MyNote, pk=note_id) return render(request, 'note/detail.html', {'request' : note}) My goal is to have a main page /note/ where I can chose from all my notes by the title_of_note. And after I chose one of the notes and click the link to one (/note/1/) it displays me the title_of_note as a title and underneath the title, I can see my details details_note. Till now, I managed to do the main page with the title of the notes as a link, ordered by the date of creation. It works all fine, but I can't figure it, out how to add the details under the title to the /note/1/ page. So far I understand, I could add details_note to the return in my models.py. But I do not know how to really do that, I know I can't just do return self.title_of_note, …