Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'gen_filenames'
I am upgrading a django cookiecutter project from django version 2.0.7 to version 2.2.3. I am getting ImportError: cannot import name 'gen_filenames' I can't find anything online for this problem. Can anyone help me out? Highly appreciated! Thanks in advance -
Objects and attribute errors on browser, after server runs
I'm new to Django and I'm working on an app that display the objects of a primary key. The server runs fine but I get an error on the browser that says: 'master_courses' objects has no attribute 'masterCourses_slug' The code looks like this: from django.shortcuts import render, redirect from .models import master_courses, course_category, course_series def single_slug(requests, single_slug): categories = [c.course_slug for c in course_category.objects.all()] if single_slug in categories: matching_series = course_series.objects.filter(course_category__course_slug=single_slug) series_urls = {} for ms in matching_series.all(): part_one = master_courses.objects.filter(course_series__course_series=ms.course_series).earliest("date_added") series_urls[ms] = part_one return render(request, "main/category.html", {"the_series": series_urls}) masterCourses = [ m.masterCourses_slug for m in master_courses.objects.all()] if single_slug in masterCourses: return HttpResponse(f"{single_slug} is a single slug.") The error points to the code below (which is on the last line of the code above: masterCourses = [ m.masterCourses_slug for m in master_courses.objects.all()] if single_slug in masterCourses: return HttpResponse(f"{single_slug} is a single slug.") The error isn't on the code section, but on the browser. Any suggestions on how I could Sol this please. -
Redirect to current page after editing a record
I'm listing 100 of records using a pagination in django. Each page contains 10 records. Suppose i'm on page 6 and selected a record to edit . After editing the record, successful url to redirect list view(which is first page). I need to stay the page where i pick the record to edit. i tried using the {{ request.get_full_path }} which will show the current url. But i cant pass it to edit url, if i passed it will show in the url. I'm using Class Based View. def form_valid(self, form): self.object = form.save(commit=False) now = datetime.now() self.object.updator = self.request.user.username self.object.date_updated = now self.object.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Suppose my on 6th page, a picked a record to edit. After editing the record i need redirect back to 6th page. Please suggest me a way to achieve this. -
How to limit paging in Django admin without changing the results number
I have a Django admin page and i wish to limit the number of pages without changing the number of objects in ChangeList. E.g. I have ChangeList with 1000 results, limit 20 results per page.and i wish to limit paging offset to 10 pages but still present i have 1000 results. So the user will be able to see the count but won't be able to "jump" to the "far" offset. -
best way to restrict update on field
I have a model class MyModel(models.Model): name = models.CharField(max_length=100, blank=False, null=False, unique=True) content = models.TextField(blank=True, null=True) I want to let user create MyModel with name parameters I am using ModelViewset. I want to avoid updating name on PUT request. But model serializer raises required error as blank=False in Model. I face this problem commonly. Yes I can override and update and create and write new serializers. Is there any other way to do it? -
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)