Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run command inspectdb from python code
In my project I need to create a schmea python file. Now I know that I can do that with the following line of code in the command line: python manage.py inspectdb --database=blah > you_app/models.py Now I need to add a shema in my python code. The problem is i cant stop the server and start a script. I need run that command from my python file. Here is my current def and my first try: def trigger_after_extract(request): # inspectdb print(request.GET.get('project')) name = request.GET.get('project') # conn = name.connect(connect='postgres', user='postgres', password='g7mN5da1e2') # connection.ensure_connection(); test = connect_to_db(name) command = 'python manage.py inspectdb --database ' + name + ' > api_manager/schemas/' + name + '.py' os.system(command) # append to __init__.py in project.schemas # with open(--path--, 'a+') as file: # file.write(--thing-- + "\n") # pass return JsonResponse({'json': test, 'oldJson': 'RESULT'}) -
On The Fly Validating and Manipulating Dictionary by Django-Rest Serializer (NO MODEL)
I have some data (dict) and I want to validate its data structure at the first and ensure about validation, after that I want to change fields name (CamelCase to snake_case), that's all it! I had lots of searches and I know about re_presentation method (it seems it calls only when using ModelSerializer as a parent class) and also read about ListSerializer. Any helps will be appreciated :) -
Create an undo button in my crud operations
So I've created a simple crud operation, but the only difference is that when you delete data entered the deleted data gets deleted from the original data list but gets saved in a separate table which is in a different URL. Now I need to create an undo function where the user has done a mistake of deleting the content and in order to retain the content he can go to the deleted table URL and click undo. from django.shortcuts import render, redirect from employee.forms import EmployeeForm from .models import * # Create your views here. def emp(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) def show(request): employees = Employee.objects.all() return render(request,"show.html",{'employees':employees}) def edit(request, id): employee = Employee.objects.get(id=id) return render(request,'edit.html', {'employee':employee}) def update(request, id): employee = Employee.objects.get(id=id) form = EmployeeForm(request.POST, instance = employee) if form.is_valid(): form.save() return redirect("/show") return render(request, 'edit.html', {'employee': employee}) ''' def destroy1(request,id): i= Employee.objects.get(id=id) if request.method==='POST': if POST.objects.filter(ename=request.POST['ename']) and POST.objects.filter(eid=request.POST['eemail']) and POST.objects.filter(econtact=request.POST['econtact']): print(employee.ename,employee.eemail,employee.econtact) i.deleted=True i.save() return redirect("/show") else: print("Nothing here") return HttpResponse("Nothing") else: retrun redirect('/show/') ''' def destroy(request,id): employee= Employee.objects.get(id=id) x=Deleted() x.eid= employee.eid x.ename=employee.ename x.eemail=employee.eemail x.econtact=employee.econtact x.save() employee.delete() return redirect ('/show') def … -
Convert query MySQL to query Django
I have a query in MySQL SELECT COUNT(app_warnings.id) AS num_warning, MONTH(app_warnings.date_created) AS month FROM app_warnings WHERE app_warnings.date_created BETWEEN '2019-04-01' AND '2019-07-31' GROUP BY month I wish I could convert to query in Django -
directly able to access the page which is after login
in respect to my previous Question, i modified my code and added the decorators and modified urls.py but the error i m encountering are:- A) The error provide valid credential is appearing on the login page even if the user does't enters anything (like some static text) B) I m able to access the localhost/Automation page directly using the url (without authentication needed) even though i added @login_required decorator. In views.py #some more imported stuff from django.urls import reverse import csv from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required # Create your views here. def login_view(request): context = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: context["error"] = "Provide valid credentials" #this message is displayed as it is. return render (request,"first_app/login.html", context) else: return render (request,"first_app/login.html", context) @login_required def user_logout(request): if request.method == "POST": logout(request) return HttpResponseRedirect(reverse('login')) @login_required def form_name_view(request): if request.method == "POST": #Automation page view #even without login i m able to access it using url only and i want to restrict that login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login</title> </head> <body> <h1> Please Login</h1> <form method="POST" action="{% url 'login' … -
Django list comapre in views
I have two models from different apps. I'm fetching one field of each of the models which is fetched as a list. I am converting the said lists elements into string through a for loop. My question is how do I compare these two strings with this method. That the element from model B are to be compared with model A elements, something like this. model A element 1 value : '923' model A element 2 value : '9253' model B element 1 value : '9256' model B element 2 value : '92356' if the last character of the string of element B 1 is matched the save the result somewhere if it's not move to the next character and so on. def LCR(request): template = "LCR\LCR.html" dest = Destination.objects.values_list('dest_num', flat=True) ven = RateFile.objects.values_list('ven_des_num', flat=True) for i in dest: str(i) print i for x in ven: str(x) print x context = {"dest":dest,"ven":ven} return render(request, template,context) -
QuerySet object has no attritube
I got a problem when I select the distinct value from DB. Here is my model => class Shift(models.Model): shiftid = models.CharField(max_length=15) shiftdesc = models.CharField(blank = False, null= False, max_length=20) dayname = models.CharField(blank = False, null= False, max_length=20) class Meta: unique_together = ('shiftid','dayname') Data structure will be like that=> shiftid shiftdesc dayname shift1 desc1 1 shift1 desc2 1 shift1 desc1 1 My requirement => shiftid shiftdesc dayname shift1 desc1 1 shift1 desc2 1 I am trying to select the records like that => @action(methods=['get'], detail=False) def shiftsum(self, request): newest = self.get_queryset().order_by('shiftid','dayname').values('shiftid','dayname').distinct() serializer = self.get_serializer_class()(newest) return Response(serializer.data) When I try like that I always got this "'QuerySet' object has no attribute 'shiftid' and May I know how to select the distinct value? -
Login page in python django
Hi i'm just trying to create my login page but i have an error. i want to import the Login View and use the username and password from the admin that i created. i tried this code but i have an error. urls.py from django.contrib import admin from django.urls import path from gomo_websys.views import login_page, home_page from django.contrib.auth.views import LoginView urlpatterns = [ path('' , LoginView, {'template_name': 'login/Login.html'}), path('home/' , home_page, name='home_page'), Login.html {% extends 'base.html' %} {% block head %} <title>Login</title> {% endblock %} {% block body %} <h1>Welcome</h1> <p> You can log in here! </p> <h2>Login</h2> <form method="post"> {% crsf_token %} {{ form.as_p }} </form> {% endblock %} views.py from django.http import HttpResponse from django.shortcuts import render def login_page(request): return render(request, "login/Login.html") i have an error result. -
Django has multiple databases and each database has its own group of applications
I have a group of Django applications need to be placed in its own Postgres database instance Let say I have app1, app2, app3, app4, app5, app6. And I have multiple database instances for them DATABASES = { "default": env.db("DATABASE_URL", default="postgres://postgres:postgres@localhost:5432/th_life"), "analytic": env.db("ANALYTIC_URL", default="postgres://postgres:postgres@localhost:5432/th_life_analytic"), "product": env.db("PRODUCT_URL", default="postgres://postgres:postgres@localhost:5432/th_life_product"), "customer": env.db("CUSTOMER_URL", default="postgres://postgres:postgres@localhost:5432/th_life_customer"), } For sake of simplicity I will give an short example default and customer I need app1, app2, and app3 go to customer database instance class DBRouter(object): def __init__(self): print(f"Customize router") super().__init__() def db_for_read(self, model, **hints): # customer information if model._meta.app_label in ['app1', 'app2', 'app3']: return 'customer' return None def db_for_write(self, model, **hints): if model._meta.app_label in ['app1', 'app2', 'app3']: return 'customer' return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): return True After I tried migrate app1. It is not apply schema to the target database. It goes to default database instance Question: What is the correct way to group my applications to particular database instance? References: I had tried some of them and many of them are outdated or no answers Official docs multiple databases and multiple models in django Django Database router based on user selection django database routing with transactions Dynamic … -
django restframework how to get the filtered queryset
This is an example code. In the real environment there are a lot of query params. views.py class EavValueViewSet(PandasMixin, viewsets.ModelViewSet): serializer_class = serializers.EavValueSerializer queryset = models.EavValue.objects.all() pagination_class = None filter_backends = (filters.DjangoFilterBackend, OrderingFilter, SearchFilter,) search_fields = ('value',) filter_class = EavValueFilter ordering_fields = ('timestamp',) ordering = ('-timestamp',) I searched the value , url is http://localhost:8000/api/eav_value/?search=test , and I want to something then return another Response. How to get the filtered queryset. -
How to Display subcategory under Category in Django?
I have some issue with displaying subcategory under Category in Django, I have already Displayed category but I am unable to display Subcategory under Category, Please Help me to display these Subcategory under category. Here is my Models.py File class WebCategory(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name='Category name') slug = models.SlugField(verbose_name='Slug') title = models.CharField(max_length=165, null=True) metadesc = models.TextField(max_length=165, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'WebCategory' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(WebCategory, self).save(*args, **kwargs) def __str__(self): return self.name class WebSubCategory(models.Model): category = models.ForeignKey('WebCategory', related_name='subcategory', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Select category') name = models.CharField(max_length=50) slug = models.SlugField(unique=True, null=True) title = models.CharField(max_length=100, null=True) metadesc = models.TextField(max_length=165, null=True) description = RichTextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'WebSubCategory' def __str__(self): return self.name Here is my views.py file def home(request): context = RequestContext(request) category_list = WebCategory.objects.order_by('-created_at')[:5] subcategory_list = WebSubCategory.objects.order_by('-created_at')[:5] context_dict = {'webcat': category_list, 'websubcat':category_list} return render_to_response('home.html', context_dict, context) And here is my header.html file, where i want to diplay category and subcategory <ul class="nav nav-pills" id="mainNav"> {%if webcat %} {% for category in webcat %} <li class="dropdown dropdown-mega"> <a class="dropdown-item dropdown-toggle" href="JavaScript:void()"> {{category.name}} </a> {% if websubcat.webcat %} <ul class="dropdown-menu"> <li> <div class="dropdown-mega-content"> … -
How to not accept one email address for multiple registration accounts in django?
I made a registration page in django but the problem is that it should not accept one email address for multiple accounts. How to resolve this issue? If you need code then let me know. -
How do I implement a toaster message on success function of ajax in django?
I am working on a problem where I have to delete entries from the list. I need tp display a toaster message when item is deleted and I want to remove the deleted element without refreshing? How am I supposed to do it? I have tried a lot of links on the web but none of them worked for me. views.py def centre_delete(request): if request.is_ajax(): id = request.POST.get('id') Centre.objects.get(pk=id).delete() message = "Deleted Successfully" else: message = "Not Ajax" return HttpResponse(message) centre_list.html <script type="text/javascript"> $(document).ready(function() { $(".del").click(function(){ swal(Delete centre?); $.ajax({ type: "POST", url: "/NewApp/centredelete/", data: { 'id': $('#cendel').val() }, success: function () { #what should go here? } }); return false; }); }); </script> <body> {% for c in centres %} <tr> <td>{{ c.name }}</td> <td>{{ c.address }}</td> <td>{{ c.contact }}</td> <td>{{ c.phone }}</td> <td> <a href="{% url 'NewApp:centreupdate' slug=c.slug %} " style="color:black; margin-left:8px"><span class="glyphicon glyphicon-edit"></span></a> <input type="hidden" id="cendel" value="{{ c.id }}"> <a class="btn btn-primary del" type="button" id="del">Delete</a></td> </tr> {% endfor %} </body> -
Extra fields in UserAdmin for AbstractUser
I am not able to add custom fields defined in MyCustomUser to add form in admin. I can only add user with 2 basic fields - username and password. How can I extend the form with extra_field? from django.contrib.auth.models import AbstractUser class MyCustomUser(AbstractUser): extra_field = models.CharField(max_length=10) admin.site.register(MyCustomUser, UserAdmin) I have already tried other stack overflow suggestions but they are overdated or simply does not work for me. -
How to import an excel file using Django without admin access?
I am building a web page using Django. I have many users login. I need to provide an option for all users to import excel files from the web page that inturn will hit my database. I think Using Django-import-export we can upload files through admin access only. But I need to provide the same option for users. How can I achieve this? Thanks -
Python Email lib message_from_bytes function error
I'm trying to get emails from my gmail account using python. but whenever I call the email.message_from_bytes. an error is generated. I searched but I couldn't find the answer please check it. import imaplib , email, os def reademail(): con = imaplib.IMAP4_SSL("imap.gmail.com") username = 'xyz@gmail.com' password = 'xyz' con.login(username, password) def get_body(msg): if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True) con.select('INBOX') result, data = con.fetch(b'340', '(RFC822)') raw = email.message_from_bytes(data[0][1]) # print data print (get_body(raw)) print reademail() error Traceback (most recent call last): File "pyt.py", line 25, in <module> print reademail() File "pyt.py", line 18, in reademail raw = email.message_from_bytes(data[0][1]) AttributeError: 'module' object has no attribute 'message_from_bytes' -
how to send two parameters in url on django template language?
approve Like the above code, I am trying to send two model id but I don't know the right structure for it. and above code wouldn't work. path('start/', views.start, name="start"), def start(request,post_id): and also if i get two parenthesis, how should i modify the above url and view code? -
How to populate some form fields according to the value selected from a combo box (select box)
I have a form with "Reference Number" as a select box. I also have several text boxes in read only mode, which needs to be populated (from the database) according to the selected "reference number" I also have several other text boxes to input new details to go with the selected reference number, so that by clicking a "submit" button, I need to be able to save (edit existing record in the table) those new data values. How can I achieve this task? Fairly new to web form and also new to python and django, so haven't done much, i have the interface created, models already created. -
how to show the div when clicked on the link and how to get value from input?
i have a django template that uses for loop to print comments i want to show the input field and a button when the edit link is clicked how do i do that. and also when the edit button is pressed i wanna get the value from that specific input field. how do i do that? {% for comment in comments %} <div class="comment mdl-color-text--grey-700"> <header class="comment__header"> <img src="images/co1.jpg" class="comment__avatar"> <div class="comment__author"> <strong>{{comment.User_name}}</strong> <span>{{comment.date}}</span> </div> </header> <div class="comment__text"> {{comment.text}} </div> <!-- FAB button , class "mdl-button--fab"--> <a href="javascript:delete_comment('{{comment.text}}','{{comment.blogslug}}')"> <button class="mdl-button mdl-js-button mdl-button--fab"> <i class="material-icons">delete</i> </button> </a> <!--when this link is clicked bellow edit_comment div should appear --> <a href=""> <button class="mdl-button mdl-js-button mdl-button--fab"> <i class="material-icons">edit</i> </button> </a> <!-- and also when i click the edit button how can i get value from the input --> <div id="edit_comment" style="visibility: hidden;"> <input type="text" name="edit_comment"> <button>edit</button> </div> </div> {% endfor %} so the problem is there are going to many other comments of this type because they are printed using a loop. -
django how to get return value as a model's value in another model
i want to transfer the return value as another model's value in a database. Do i need to put it in a view or it can be done inside model's def function? def total_keluar(self): keluar = self.stok_keluar keluar.total=Gudangatas.objects.aggregate(Sum('stok_keluar')) keluar.total.save() return keluar.total i tried this code but not working column=model(keluar.total) -
I can't get my files to save to my database and then be able to be dispalyed in my basic django api
I'm building a basic http api from scratch in django and I can't get my files that are created with my POST method to save to my database and then be able to be called up and displayed with file/file_id in Postman. THIS IS MY VIEWS.PY def file(request): if request.method == "GET": print("a GET request is being made to this route") all_names = list(File.objects.values('name')) for file in all_names: print(file) return JsonResponse(dict(files=all_names)) elif request.method == "POST": print("******", request.META) files = resquest.File["filename"] name = request.META["HTTP_NAME"] newFile = File( name = name, uploader = request.META["HTTP_UPLOADER"], content = files.read(), size = 10 ) newFile.save() return JsonResponse({"file_id": name}, safe=False) TypeError: Object of type 'QuerySet' is not JSON serializable -
How to print an error when getting a wrong format input (datetime format) in a submit form in Django?
I'm building an application streaming object detection on web browser, the data (datetime, object info, etc.) is saved in mysql database, the app has a web page for filtering the data based on datetime, now it only works when the format is proper datetime format (e.g. 2019-07-24 12:00:00), if it's incorrect (e.g. 2019-07-123), web browser will return an error page. search.html <input id="from_date" type="text" name="from_date" placeholder="From Date..." > <input id="to_date" type="text" name="to_date" placeholder="To Date..." > views.py def search(request): if request.method == 'GET': from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') "code to detect if from_date and to_date are incorrect formats???" I want to know how can I detect that case then print an error in my web template. -
Is there a parameter to change the order of reactions for an activity with stream?
For a certain activity id (postid) I have an API endpoint that will return the list of reactions (comments) for that activity. It appears to me that the way in which the reactions are returned from stream is that the newest is at the top? I want the newest at the bottom like how facebook is. As far as what I've seen or tried I just see what the documentation has: https://getstream.io/docs/python/#reactions_retrieve-reactions I do see that it seems to support pagination which I also need so that's great. class ListCommentsForPost(ListAPIView): permission_classes = (IsAuthenticated,) def get(self, request, postid, *args, **kwargs): response = stream_client.reactions.filter( activity_id=postid, kind="comment", ) serializer = CommentSerializerStream(response['results'], many=True) return Response(serializer.data) Ultimately, I just expect to be able to change the order of how reactions are returned chronologically. When stepping the code I do see it is indeed an OrderedDict so maybe the answer is to just try to manually reorder it? Should probably still be a query parameter though. -
Optimize Django for loops with filter inside the loop
If i have model like this class User(models.Model): name = models.CharField(max_length=255) organization = models.ForeignKey( "organization.Organization", on_delete=models.CASCADE ) school = models.ForeignKey( school, on_delete=models.CASCADE,) And then I receive and input of list of lists of user ID. Like this: list_of_lists_of_user_id = [ [11,21,23] , [12, 324] , [909,2,12,444,242] , ....... ] I want to return the same kind of list but not with just ID, instead I want the other value like "name" and "school" too. So I want to return the list of queryset of User's name and School I would have to loop through like this: return_list_of_query_set = [] for group in list_of_lists_of_user_id: query_set = User.values("name","school").filter( id__in=group ) return_list_of_query_set.append(query_set) How would I optimize this for loop and don't make 1000s queries -
How to setup django rest framework to only allow user that creates an object to GET,PUT,DELETE
I'm setting up a Django REST API that involves families, parents, and children. I want to setup permissions so that Admins can send a GET request to the /api/parents/ endpoint and see a list of all Parents, but User's GET requests only return the list of Parent objects that they created, or "own". I'm building an app with a React.js frontend and a Django REST backend. When a User Signs Up, they are issued a JSON Web Token using the open source simplejwt package that django has. The application involves parents and children in families. When the User tries to create a Parent object, they need to be able to retrieve the unique hyperlinked URL to their personally created Parent object in order to create a linked Child object for their children and associate it only to their Parent object. Right now, when I make a POST request to the endpoint for the Parent router, Anyone can create a Parent object as long as they are logged in. Only GET requests from admins succeed(with the attached JWT as a Bearer in Authorization in the request). Admin GET requests succeed with a list of all Parent objects in the database. If …