Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create GrapgQL API's with Django and Neo4J Database?
I am working on a project where I need to make GraphQL API's with Django Server (Graphene-Django) and Neo4J database. I have looked quite a lot over the internet, but I wasn't able to find any useful resources. If anyone can give a simple example of the flow or suggest some resources, please help. -
How to get Form data in django using cloud firestore?
Form picture ID is been selected but I'm not getting the values in the form, please check my code files. See in the picture in URL of the browser, update/id is selected, the problem is values are been fetched in the form. HTML: <form id="task-form" name="myForm"> {% csrf_token %} <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-building" placeholder="Building name" name="building" value="{{buildings.building}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-postal" placeholder="Postal Code" name="postalCode" value="{{buildings.postalCode}}"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-town" placeholder="town" name="town" value="{{buildings.town}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-street" placeholder="Street" name="street" value="{{buildings.street}}"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-house" placeholder="House No." name="houseNo" value="{{buildings.houseNo}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-info" placeholder="Additional Information" name="additionalInfo" value="{{buildings.additionalInfo}}"> </div> </div> </div> <div class="text-center mt-3"> <button type="submit" id="btn-task-form" class="btn btn-primary ">UPDATE</button> </div> </form> views.py def update_Building(request, id): docId = id; context = { 'buildings': db.collection('Buildings').document(docId).get() } return render(request,"EmployeeAdmin/updateBuilding.html", context) urls.py path('update/<str:id>/',views.update_Building,name='update_Building'), -
My login register panel disappear when reduced to mobile and tablet size
I am working on a website in which I have an HTML page for login, registration, dashboard. When I reduce the dimension of the website it disappears. I have separate HTML pages for the top and navbar section. Here Desktop View and this is Mobile/Tablet View. Please suggest any solution. This is my topbar.html page <!-- Top header start --> <header class="top-header th-2 top-header-bg"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12"> <ul class="top-social-media pull-right"> {% if user.is_authenticated %} <li> <a href="{% url 'dashboard' %}" class="sign-in"><i class="fa fa-fa-user"></i> Dashboard</a> </li> <li> <a href="javascript:{document.getElementById('logout').submit()}" class="sign-in"><i class="fa fa-sign-out"></i> Logout</a> <form action="{% url 'logout' %}" id="logout" method="POST"> {% csrf_token %} <input type="hidden"> </form> </li> {% else %} <li> <a href="{% url 'login' %}" class="sign-in"><i class="fa fa-sign-in"></i> Login</a> </li> <li> <a href="{% url 'register' %}" class="sign-in"><i class="fa fa-user"></i> Register</a> </li> {% endif %} </ul> </div> </div> </div> This is my navbar.html page <!-- Main header start --> {% load static %} <header class="main-header sticky-header header-with-top"> <div class="container"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12"> <ul class="top-social-media pull-right"> {% if user.is_authenticated %} <li> <a href="{% url 'dashboard' %}" class="sign-in"><i class="fa fa-fa-user"></i> Dashboard</a> </li> <li> <a href="javascript:{document.getElementById('logout').submit()}" class="sign-in"><i class="fa fa-sign-out"></i> Logout</a> <form action="{% url 'logout' %}" id="logout" … -
Django Rest Framework: How to work with Foreign Key in Serializer?
I am new to Django and I have this DB Schema DB Schema I have coded schema in models.py from django.db import models from auth_jwt.models import User class Board(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) board_name = models.CharField(max_length=20) board_desc = models.CharField(max_length=120) def __str__(self): return self.board_name class Column(models.Model): column_name = models.CharField(max_length=100) board = models.ForeignKey(Board, null=True, related_name="board", on_delete=models.CASCADE) def __str__(self): return self.column_name class Todo(models.Model): todo_name = models.CharField(max_length=200) todo_desc = models.CharField(max_length=200) column = models.ForeignKey(Column, null=True, related_name="column", on_delete=models.CASCADE) def __str__(self): return self.todo_name serializers.py from rest_framework import serializers from .models import Board, Todo, Column class BoardSerializer(serializers.ModelSerializer): class Meta: model = Board fields = ["id", "board_name", "board_desc"] class ColumnSerializer(serializers.ModelSerializer): board = BoardSerializer(read_only=True) class Meta: model = Column fields = ["id", "column_name", "board"] depth = 1 class TodoSerializer(serializers.ModelSerializer): column = ColumnSerializer(read_only=True) class Meta: model = Todo fields = ["todo_name", "todo_desc", "column"] depth = 1 But whenever I POST data to Todo Model it returns django.db.utils.IntegrityError: NOT NULL constraint failed: api_todo.column_id Post Data { "todo_name": "satyam", "todo_desc": "dsa", "column": { "column_name": "Todo", "board": { "board_name": "Todo", "board_desc": "Whatta Day!" } } } Views.py class TodoView(ListCreateAPIView): serializer_class = TodoSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user) def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response({"todo": serializer.data}, … -
Django web deployment [closed]
I have this site as a domain http://xxxx-officesuits.com:8000/ how can I deploy my newly created website to that domain? Send help! -
How to get object id before assignment to database in Django
I need an object's id before saving that object in the database. my code return none. -
Databases: Many to Many of a foregin key in a HASHTAG - FOLLOWER relation
Let's think I build Instagram platform. I have 2 models: class Follower(): hastags = ??? class Hashtag(): name = char... I want: To be able to fetch -all specific follower- hashtags. And reverse: fetch -all Followers- of a specific hastags. A Follower don't have to have an hashtag. An Hashtag exist only once a follower is adding it. -
Reverse django admin custom url with two parameters
I have the following custom admin url def get_urls(self): (...) info = self.model._meta.app_label, self.model._meta.model_name urlpatterns = [ path('<path:object_id>/CompareParameters/<int:parameter_id>', wrap(CompareParameters.as_view()), name='%s_%s_CompareParameters' % info), ] and I need to call it from an inline and it takes two parameters (the fact the view's name includes word parameters is just a coincidence) I have tried to do it like so def pair_parameter(self, obj): return mark_safe(f'<a style="padding: 5px; background-color: lightblue;" target="_blank" href="{reverse("admin:agregator_agregatorproduct_compareparameters", args=[obj.ProductId_id, obj.DistributionParameterId_id, ])}">Spárovavat parametr</a>') or like so def pair_parameter(self, obj): return mark_safe(f'<a style="padding: 5px; background-color: lightblue;" target="_blank" href="{reverse("admin:agregator_agregatorproduct_" + str(obj.ProductId_id) + "_" + str(obj.DistributionParameterId_id) + "_compareparameters")}">Spárovavat parametr</a>') and by a few other combinations with no success. What would be the right way to do it? The final URL looks eg like this .../admin/agregator/agregatorproduct/1854146/CompareParameters/9330 where the first arg is obj.ProductId_id and 2nd is obj.DistributionParameterId_id Thank you in advance. -
jsonResponse return id instead of the object name django
i'm trying to fetch data from jsonResponse into ajax , but in the foreign key field it returns object_id instead of the object name my models.py class Product(models.Model): item = models.CharField(max_length=50) class Item(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) active = models.BooleanField(active=True) my views.py def alerts(request): if request.is_ajax: data = Item.objects.filter(active=False).values() print(data) return JsonResponse({'items':list(data)}) #print(data) returns this <QuerySet [{'id': 13, 'item_id': 14, 'active': False}]> i dont know how to return item name instead its id (item_id) $(document).ready(function(){ $('.btn-click').click(function(){ $.ajax({ url:'{% url 'maininfo:alerts' %}', dataType:'json', type:'GET', success:function(data){ var obj = data.items var mainObj = data.items; var k = '<tbody>' for(i = 0;i < data.items.length; i++){ k+= '<tr>'; k+= '<td>' + mainObj[i]["item_id"] + '</td>'; '</td>'; k+= '</tr>'; } k+='</tbody>'; document.getElementById('tableData').innerHTML = k; } }) }) }) <div x-data="{ dropdownOpen: false }"> <button @click="dropdownOpen = !dropdownOpen" class="relative z-10 block rounded-md text-black p-2 focus:outline-none btn-click"> <i class="fas fa-bell"></i> </button> <div x-show="dropdownOpen" class="absolute left-2 top-10 text-right py-2 w-59 grayBG rounded-md shadow-xl z-20 h-48 overflow-y-scroll "> <table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center"> <thead> <tr> <th width="30%">deactive items</th> </tr> </thead> <tbody id="tableData"></tbody> </table> </div> </div> is there something wrong within my json response ? or a better approach to achieve it -
How to properly configure authentication views? (Django)
There are two views index and index1 and my login view is def loginview(request): if request.user.is_authenticated: return redirect('index') else: return redirect('index2') urls.py urlpatterns = [ path('',loginview,name="login"), path('index/',index,name="index"), path('index2/',index2,name="index2"), ] The code works but I want to only access index and index2 after the user is logged on or logged out. When I navigate to localhost:8000/index and localhost:8000/index2, the page directs to the respective pages. How to restrict authorization on these pages? -
objects are not crated through cmd django python
>>> from sabin.models import Task >>> Task.objects.all() <QuerySet []> >>> t=Task(title="dhiraj") error Traceback (most recent call last): File "", line 1, in File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 503, in init raise TypeError ("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg)) TypeError: Task() got an unexpected keyword argument 'title' models.py file from django.db import models class Task(models.Model): title:models.CharField(max_length=200) completed=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title -
Django @ mention user using Django Custom Tags
Hey guys I'm trying to mention a user in the database and have the post return with the username @whatever as a hyperlink in the original post. I seem to be getting an error where I either get the last word of the post only or if I mention just a user I get the url plus the username back as html code the same way I have it in the code. I'm so close to getting but for the life of me can't figure out why it's not returning it correctly. What am I doing wrong? And THANK YOU SO MUCH in advance. I am trying to use the solution that was found here. I get the url with the username but I just want the username plus the original post For example if the post in the database is "hello @faces how are you doing?" I would like to get back the post just as it is but with the user @faces as a hyperlink to the users profile. This is my custom tag from the custom templates that I am using. In the terminal I see that it is finding the user if it's in the database … -
when I run this code and click on signup there is an error
from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages def register(request): if request.method == 'POST': first_name = request.POST['first_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1==password2: if User.object.filter(username=username).exist(): print('username taken') elif User.objects.filter(email=email).exists(): messages.info(request,'email Taken') return redirect('register') else: User = User.objects.create_user(first_name=first_name,username=username,password1=password1,email=email) User.save(); print('user created') return redirect('register') else: print('password not matching') return redirect('register') return redirect('/') else: return render(request,'register.html')[error that I face][1] enter code here enter image description here -
Match Question Mark character in Legacy Path
The following allows me to match surname/Smith and surname.php/surname=Smith but I wish to match surname.php?surname=Smith instead of the latter so as to ensure that people using the old links can still find the info they are after. How should I do this? from django.urls import path, re_path from . import views urlpatterns = [ path('surname/<str:surname>/', views.surname, name="surname"), path('surname.php/surname=<str:surname>',views.surname), ] -
Authentication with google auth , jwt token, django rest framework, nextj
How can I implement authentication system using Django Rest Framework backend and Next js frontend for google oauth (social auth) with jwt token ? -
How to download large file from Cloud Run in Django
I have Django project on Cloud Run. When I download small file from page which has below code. def download_view(request,pk): file_path = f'media/{pk}.mp3' name = f'{pk}.mp3' with open(file_path, 'rb') as f: response = HttpResponse(f.read(), content_type='audio/wav') response['Content-Disposition'] = f'attachment; filename={name}' return response It's works fine. However, when I download a file (50MB). I got this pictures error. Cloud run's log is like this. I couldn't find any log of traceback. 2021-05-06 12:00:35.668 JSTGET500606 B66 msChrome 72 https://***/download/mp3/2500762/ 2021-05-06 11:49:49.037 JSTGET500606 B61 msChrome 72 https://***/download/mp3/2500645/ I'm not sure. Is this error related with download error. 2021-05-06 16:48:32.570 JSTResponse size was too large. Please consider reducing response size. I think this is upload file size error. So this is not related with this subject of download error. When I run Django at local, then download same 50MB file. I can download it. I think this download error related with Cloud run. It's stop after request/response. So I think this error coused by Cloud Run. Which was stoped, when I'm still downloading file. I don't know how to solve this download error. If you have any solution, please help me! -
How to auto create a new row in a table every day or according to date django
modaly.py class User(modals.Modal): name = models.CharField(max_length=30) class Traffic(models.Model): my_user = models.ForeignKey(User, on_delete=models.CASCADE) per_day_user_visit = models.PositiveIntegerField(null=True, blank=True) traffic_date = models.DateField(auto_created=True) id my_user per_day_user_visit traffic_date 1 instance 500 user_visit monday 2 instance 512 user_visit tuesday views.py Auto created a new row, when new day come if newday: Traffic.objects.create(my_user = "1", per_day_user_visit = "512", date=datetime.now()) -
CSRF verification failed in admin panel
I'm deploying my web-site on Apache web-server. Also I have a Single Sign-On authentication with django-remote-auth-ldap library. Everything works directly on the site itself, but when I go to the admin panel and try to change something, an error occurs: 'Forbidden (403) CSRF verification failed. Request aborted'. By the way, in the localhost is working fine. Can you please help me with this thing? I'm actually stuck with this for a week or so. Thank you -
How do I create a multidimensional table in SQL? Or should I use some other DBMS?
I want to use a DB for creating languages (as a hobby), and I went with SQLite. Of course, to save myself some trouble, I decided to write myself a user-friendly interface in the form of a web-app using Django. I already got sa few pages up. Then I stumbled upon this issue that I need to be able to somehow store in my DB that, e.g., a verb has the categories of Mood, Tense, Gender, Person and Number, with Number only relevant for Indicative Mood; Person only relevant for Indicative Mood, Present and Future Tenses; and Gender only relevant for Indicative Mood, Past Tense, Signular Number. Basically, I need to be able to check the values of each category (like Mood, Tense, Gender, Person, Number, so forth) against the values of every other category, and I need this to be as flexible as possible because grammatical geometry of every language is very differnet and I want to be able to reflect that in my DB. I guess what I'm looking for is a multidimensional table, where every dimension is a separate category, but I'm not sure how to do that using SQLite, with the means of Django no less. … -
How i can manage Chat system between my React(front-end) and Django (back-end)
I am working on a chat application, in which I'm gonna use React for the Front-end and Django as the back-end. Note: Both are on different servers. Everything will work through the APIs. I want to know how I can establish a connection between React and Django so I can get real-time messages and display them to the user. Should I use socket.io-client in my React app and Django-channels in my Django app.??? or is there any other way to do this?? And Instagram and other Companies that are using these both stack, how they are doing this stuff??? Please answer ... Kind Regards, Huzaifa -
Error while changing a Char field to Array Field in Django
I am trying to change a existing CharField in a django model (it also allows null and contains null values in db currently) now I am trying to change it to an Array Char Field, but it throws the below error "django.db.utils.IntegrityError: column "tags" contains null values" From tags= models.CharField(max_length=255, blank=True, null=True) To tags = ArrayField(models.CharField(max_length=255, blank=True, null=True)) I have selected option 2 while before running migrate -
Django Redirect: No errors, but no redirect
I POST some data via an HTML form using AJAX to modify data in my database. The data is successfully modified by executing stored procedures on the DB. Final line of the view.py function call is return redirect('Home'). The redirect is successfully executing, but I am not being redirected. I can overcome this by adding window.location.href = 'http://127.0.0.1:8000/ in the success function of the AJAX call. The problem is, I want to use messages.success(request, 'Data Successfully Updated'), which only appears after refreshing the AJAX-originating redirect. Is there a reason why return redirect('Home') is not working here, and is there a way to overcome this? Home is the name of my path in urls.py [06/May/2021 17:23:52] "POST /search/ HTTP/1.1" 302 0 // submitting changes to database [06/May/2021 17:23:55] "GET / HTTP/1.1" 200 4750 // The page I am intending to redirect to Ajax Call function updateCards(){ ajaxUpdCard().done() function ajaxUpdCard() { return $.ajax({ type: 'POST', url: '', data: {csrfmiddlewaretoken: window.CSRF_TOKEN, Action: 'Card', CardID: $('#currentCardID').val(), BCard: $('#sr-bad_card').val(), CNum: $('#sr-card_number').val(), CPin: $('#sr-pin_number').val(), Bal: $('#sr-balance').val()} }) } } views.py if request.method == 'POST' and request.POST['Action'] == 'Card': cardID = request.POST['CardID'] Bcard = int(request.POST['BCard']) CNum = int(request.POST['CNum']) CPin = int(request.POST['CPin']) if request.POST['CPin'] != '' and request.POST['CPin'] … -
string data can't be updated without changing the image in vue js
I have a problem with updating data using vue js as the frontend and django as the backend when updating the data with the data image is changed successfully. but when updating data without an image with an error. i've fire test using postman and managed to update data without changing image. please find a solution this is the method for updating the data ubah() { let datapengajarstaf = new FormData(); datapengajarstaf.append("nama", this.datapengajarstaf.nama); datapengajarstaf.append("nip", this.datapengajarstaf.nip); datapengajarstaf.append("jobs", this.datapengajarstaf.jobs); datapengajarstaf.append("picture", this.gambar); _.each(this.datapengajarstaf, (value, key) => { datapengajarstaf.append(key, value); }); axios .put("http://127.0.0.1:8000/api/Detailpengajarstaff/"+this.id, datapengajarstaf, { headers: { "Content-Type":"multipart/form-data" } } ) .then(response => { this.$router.push("/indexpengajarstaff"); this.$q.notify({ type: "positive", message: `Data berhasil ditambah.` }); }) .catch(err => { if (err.response.status === 422) { this.errors = []; _.each(err.response.data.errors, error => { _.each(error, e => { this.errors.push(e); }); }); } }); } this is for form-data when the data is updated -
Conditionally authenticate users to DRF view
I have a DRF view as such: class DocumentsView(generics.ListCreateAPIView): permission_classes = () authentication_classes = () # I typically enforce authentication with # authentication_classes = (JWTCookieAuthentication,) def list(self, request): pagination_class = None if request.user.is_authenticated: ... return protected data ... else: ... return generic data ... I want to allow both users sending a valid token and those not sending a valid token to both get a response from this endpoint. However, request.user.is_authenticated returns False, even when a valid token is sent (I understand why). How can I try to authenticate the user, but still allow them to proceed even if not presenting a token? Or is better practice to not have the same view to authenticated an unauthenticated users? -
Could not parse the remainder: '[loop.index0]' from 'query_results_course_id[loop.index0]'
I have used django to develop a web app. In frontend, I want to access the object through the loop like in the html template. <label class="radio-inline"> {% for course_for_select in query_results_2 %} <input type="checkbox" name="course_select" value="{{course_for_select}}">&nbsp; {{course_for_select}} {{ query_results_course_id[loop.index0] }} <br> {% endfor %} </label> However, error occurs: Could not parse the remainder: '[loop.index0]' from 'query_results_course_id[loop.index0]'