Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make connection between two django apps in two different docker containers?
I have created two apps 'myapi' and 'minombre' where the 'minombre' will make a simple GET request to 'myapi' and put them in two separate docker containers.After I run 'docker-compose up' the containers run but the api don't pass the data. The views.py of the 'minombre' where the GET request is made is given below: def index(request): response = requests.get('http://myapi') print(response) data = response.json() name = data['user'] message = data['message'] return HttpResponse('<h2> {} </h2> <br> <h5> {} </h5>'.format(name, message)) This is the docker-compose.yml that I have used to get the containers running. version: '3' services: myapi: build: ./myapi container_name: myapi ports: - "8001:8001" command: python manage.py runserver 0.0.0.0:8001 minombre: build: ./minombre container_name: minombre ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 depends_on: - myapi This is the exception: Exception Type: ConnectionError Exception Value: HTTPConnectionPool(host='myapi', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused')) Please help me solve this problem. -
Django loop all existing record to save but only one record save
this is my code in html <tr> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Required Documents:</h2></td> </tr>{% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile-{{d.id}}" value="{{d.id}}" style="outline: none;" required/>{{d.id}}{{d.Description}}</td> <td></td> </tr> {% endfor %} what I tried in my views.py myfile = request.FILES['myfile-6'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() I don't have idea on how to loop this myfile = request.FILES['myfile-6'] with the existing id of Table Documents. please help me guys, im stuck on this problem 3days -
Run Django without server
I have a small Django site, mysite. I want to be able to run my Django app without running a web server. Instead of using an HTTP client to make requests, I'd like to write something like: django.run() result = django_request('/foo/bar') So Django would still do URL parsing, etc, just not serve through UWSGI. Is this reasonable? -
How to get user data and user group from Active Directory using Django ? Using LDAP or PYAD
Anyone have idea about how to access the Active directory(AD) using python script in Django ? I need to access AD and fetch user data and user group details. Like add or remove user, assign user to specific groups, delete user data. Access AD database (ntds.dts) How to access AD ? Using LDAP or PYAD - which is better -
Writing xls from python row wise using pandas
I have sucessfully created .xlsx files using pandas but in this the writing of data is done column wise. df = pd.DataFrame({'Data': [10, 20, 30, 40, 50]}) I want to know is there a way by which I can write row wise data to xlsx sheet using pandas only? def gstin_export_xls(request): df = pd.DataFrame({'Data': [10, 20, 30, 40, 50]}) # my "Excel" file, which is an in-memory output file (buffer) # for the new workbook excel_file = BytesIO() writer = pd.ExcelWriter(excel_file, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1_test') writer.save() writer.close() # important step, rewind the buffer or when it is read() you'll get nothing # but an error message when you try to open your zero length file in Excel excel_file.seek(0) # set the mime type so that the browser knows what to do with the file response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') # set the file name in the Content-Disposition header response['Content-Disposition'] = 'attachment; filename=myfile.xlsx' return response Thanks! -
Button in django template doesn't put data in database
I have a app named "mysite". I want to put dummy data in database(add row) for now(originally i will be pulling data from a API) when button is clicked but button is not responding. urls.py path('', views.index), views.py from .fetch_data import get_data def index(request): if (request.method == 'POST' and 'script' in request.POST): get_data() return render(request, 'mysite/index.html') index.html in "mysite/templates/mysite" folder <form method="POST" name='script'> {% csrf_token %} <button type="submit" >Fetch data from source</button> </form> fetch_data.py from .models import Hosts import time, sys def get_data(): print('here in function') p = Hosts(hostname="first data") p.save() But when i click button, nothing happens. View should remain the same even after successful button click. Note: fetch_data.py is on same folder as views.py and urls.py. -
Django/bootstrap datepicker not working in dynamic formset
I cannot get the bootstrap datepicker to load in the new lines of a Django formset. Using inline_formsetfactory and Django-dynamic-formset package, the initial date time fields work fine, but not when adding new lines. Below is the script for adding and removing new lines. I am using the Django-Bootstrap-Datepicker-Plus package. <script type="text/javascript"> $('.formset_row-{{ formset.prefix }}').formset({ addText: '<button class="btn btn-secondary btn-sm">Add History</button>', deleteText: 'Remove', prefix: '{{ formset.prefix }}', }); </script> The calendar icons appears, but the dropdown does not. -
NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. Same url i have tried for another app and that is working
//While rendering this kitty_view I am getting this error. Exactly the same thing I have copied from another app that is working properly. Kindly help. view.py ------------------ def kitty_view(request): kitty_list = kitty.objects.all().order_by('-cretime') code1 = str(request.GET.get('Code')) name1 = str(request.GET.get('nam')) status1 = str(request.GET.get('stat')) if (name1 is not None and name1 != ''): kitty_list = kitty_list.filter(name=name1) if (code1 is not None and code1 != ''): kitty_list = kitty_list.filter(code='K00001') if (status1 is not None and status1 != ''): kitty_list = kitty_list.filter(status = 'A') ctx = {'kitty': kitty_list} return render(request, 'kitty/kitty_view.html', ctx) Url.py ----- urlpatterns = [ path('',views.index,name='index'), path('kitty_view',views.kitty_view,name='kitty_view') ] template --------- <form class="form-signin" action="{% url 'kitty_view' %}" method="get"> {% csrf_token %} <div class="form-row"> <div class="mb-3"> <select class="custom-select center-block" name="code" id="code"> <option value="">Choose Kitty...</option> <!-- <option>{{ kitty1.code }}</option> {% for i in kitty1 %} <option value="{{ i.code }}"> {{ i.code|add:' - '|add:i.name }} </option> {% endfor %} --> <option>K00004</option> <option>K00005</option> </select> </div> <div class="mb-3"> <input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus> </div> <div class="mb-3"> <select class="custom-select center-block" name="stat" id="stat" placeholder="Status"> <option value="">Choose Status...</option> <option>A</option> <option>I</option> </select> </div> <div class="mb-3"> <!-- <a href="{% url 'customer_view' %}" class="btn btn-primary btn-sm" role = "button">Search</a> --> <button type="submit" class=" btn btn-info " role="button">Search</button> </div> </div> </form> <table class="table … -
How could I display the employees information on the modal?
How to make that after clicking the view modal button on my index it will show that specific employee information? And at same time I will be able to edit those in future. -
Stuck on apache2 default page while deploying Django website
I have gone through a few answers on the web and I am still struggling to get past the apache2 default page. The webapp works fine locally and without apache. I am using an AWS EC2 instance for this on an ubuntu machine. The whole code is hosted in /home/ubuntu/sm on the machine, the venv is in /home/ubuntu/sm/venv and running on the ip addr 3.X.X.212 I've tried adding, editing, removing a few variables, to no avail. I got nothing in the error logs either. The 'gracefully restarting' entries are starting to look narcissistic given how long I've been stuck on this. apachectl -S produces the following response: [Tue Nov 05 05:16:52.198045 2019] [alias:warn] [pid 13664:tid 139764718218176] AH00671: The Alias directive in /etc/apache2/sites-enabled/sm.conf at line 33 will probably never match because it overlaps an earlier Alias. VirtualHost configuration: *:80 ip-172-*-*-29.ap-southeast-2.compute.internal (/etc/apache2/sites-enabled/sm.conf:1) ServerRoot: "/etc/apache2" Main DocumentRoot: "/var/www/html" Main ErrorLog: "/var/log/apache2/error.log" Mutex default: dir="/var/run/apache2/" mechanism=default Mutex watchdog-callback: using_defaults PidFile: "/var/run/apache2/apache2.pid" Define: DUMP_VHOSTS Define: DUMP_RUN_CFG User: name="www-data" id=33 not_used Group: name="www-data" id=33 not_used "sm.conf" is the config file used for this, as below: ServerAdmin webmaster@localhost LogLevel info ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /robots.txt /home/ubuntu/sm/website/static/robots.txt Alias /favicon.ico /home/ubuntu/sm/website/static/favicon.ico Alias /static/ /home/ubuntu/sm/website/static Alias /static/ /home/ubuntu/sm/media … -
how call other class base view method in django
I want to make xlsx file per model. There are many models. They had each ListView(Class based view). So, I want to use these view's get_queryset method for making queryset. for example: testView = TestListView() queryset = testView.get_queryset() But, It's not working. I try this: testView = TestListView.as_view()(request) queryset = testView.get_context_data(request) but also didn't work. I need help. -
Django Signals: The QuerySet value for an exact lookup must be limited to one result using slicing
I hope my title is enough to determine what the error is. i have this code in my models.py (post_save) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses) for each in teachers: if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( pk=each.id, Students_Enrollment_Records=instance, Subject_Section_Teacher=teachers.all() ) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) class SubjectSectionTeacher(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) when I used the Subject_Section_Teacher=teachers.first() i received no error but that is not what i want result, then i decide to change it to this Subject_Section_Teacher=teachers.all() i just want the result to become this not this -
Trying to show custom success message and hide default success message in Django admin
<-- In admin.py I have a function it showing my custom message but also showing default success message how to stop default success message ??--> from django.contrib import messages, admin def save_model(self, request, obj, form, change): self.message_user(request, "The message", level=messages.SUCCESS) -
Has anyone tried creating a Web Socket that listens to Django channels web socket API?
I am trying to create a service that will listen to a web socket API from Django channels. I believe direct integration as with socket.io is not possible. Anyone can help me with this problem? I want an angular client to receive a list of coordinate changes and then reflect it to a map in real-time. -
NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. 1 pattern(s) tried: ['kitty$']
//While rendering this kitty_view i am getting this error. Exactly same thing i have copied from another app which is working properly. Kindly help. // Codes that i am using View.py --------- def kitty_view(request): kitty_list = kitty.objects.all().order_by('-cretime') code1 = str(request.GET.get('Code')) name1 = str(request.GET.get('nam')) status1 = str(request.GET.get('stat')) if (name1 is not None and name1 != ''): kitty_list = kitty_list.filter(name=name1) if (code1 is not None and code1 != ''): kitty_list = kitty_list.filter(code='K00001') if (status1 is not None and status1 != ''): kitty_list = kitty_list.filter(status = 'A') ctx = {'kitty': kitty_list} return render(request, 'kitty/kitty_view.html', ctx) URL.py -------- urlpatterns = [ path('',views.index,name='index'), path('kitty',views.kitty_save,name='kitty'), path('kitty_view',views.kitty_view,name='kitty_view') ] Template -------- {% extends 'base.html' %} {% load static %} {% block content %} <form class="form-signin" action="{% url 'kitty_view' %}" method="get"> {% csrf_token %} <div class="form-row"> <div class="mb-3"> <select class="custom-select center-block" name="code" id="code"> <option value="">Choose Kitty...</option> <!-- <option>{{ kitty1.code }}</option> {% for i in kitty1 %} <option value="{{ i.code }}"> {{ i.code|add:' - '|add:i.name }} </option> {% endfor %} --> <option>K00004</option> <option>K00005</option> </select> </div> <div class="mb-3"> <input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus> </div> <div class="mb-3"> <select class="custom-select center-block" name="stat" id="stat" placeholder="Status"> <option value="">Choose Status...</option> <option>A</option> <option>I</option> </select> </div> <div class="mb-3"> <!-- <a href="{% url 'customer_view' %}" class="btn … -
is there any way to convert this ajax call into django api?
This is my login code which was build elrier in ajax call now i want to make API end points for this so i converted this all into class view although this is not correct but i need some help when i am checking this with postman i m getting error this is not post request. i tried (self,request,args,krgws) but did not work class LoginAPIView(APIView): def login(request): """ dashboard login :param request: :return: """ logger.info("inside login") if request.user.is_authenticated() and request.user.is_superuser: return HttpResponseRedirect(reverse('activity:index')) if request.is_ajax(): username = request.POST.get('username', None) password = request.POST.get('password', None) if password is None or username is None: return JsonResponse({'status': 'failed'}) msg = {} try: user = authenticate(username=username, password=password) if User.objects.filter(username=username).exists() and user is not None: groups = Group.objects.all().values('name') check_group = lambda user_group, groups : any(ug in groups for ug in user_group) if (not user.groups or not check_group(user.groups.all().values("name"), groups)) and not user.is_superuser: return JsonResponse({"redirect_url" : "/"}) if user is not None: if user.is_active: auth_login(request, user) msg['status'] = 'ok' user_activity = {"email": user.email, "first_name": user.first_name, "last_name": user.last_name, "activity": 'logged in'} UserActivity.objects.create(**user_activity) else: msg['status'] = 'failed' else: msg['status'] = 'failed' except: msg['status'] = 'failed' return JsonResponse(msg) else: raise Http404('page not found.') -
How to solve admin.E040 in Django?
I have installed rest framework token authentication in Django and every time I run the local server it gives me an error. : (admin.E040) UserModelAdmin must define "search_fields", because it's referenced by TokenAdmin.autocomplete_fields. I -
I'm trying to use django login view and get NoReverseMatch error during rendering base template
Please, help! I'm really stuck, I'm trying to make login page using django login view and time after time I'm getting NoReverseMatch error on rendering base template. In the documentation I read about tag url, but I don't understand how to use it. Here is my base template <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8" /> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="favicon.png" /> <link rel="stylesheet" href="libs/bootstrap/bootstrap-grid-3.3.1.min.css" /> <link rel="stylesheet" href="libs/font-awesome-4.2.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="libs/fancybox/jquery.fancybox.css" /> <link rel="stylesheet" href="libs/owl-carousel/owl.carousel.css" /> <link rel="stylesheet" href="libs/countdown/jquery.countdown.css" /> <link rel="stylesheet" href="css/fonts pariszanka.css" /> <link rel="stylesheet" href="css/media.css" /> </head> <style> *::-webkit-input-placeholder { color: #666; opacity: 1; } *:-moz-placeholder { color: #666; opacity: 1; } *::-moz-placeholder { color: #666; opacity: 1; } *:-ms-input-placeholder { color: #666; opacity: 1; } html { position: relative; min-height: 100%; } body { margin-bottom: 60px; background-color: #d7dad9; } .header{ font-family: IsadoraBold; text-align: center; font-size: 30px; } .top_line{ background-color: #24292E; color: white; } .bottom_line{ background-color: #24292E; color: white; } .top_name{ float: left; list-style-type: none; } .top_nav{ float: right; } .top_nav ul li{ list-style-type: none; display: inline-block; vertical-align: center; padding-right: 40px; } .top_nav a{ color: white; } .top_nav a:hover{ color: #78B0AE; } </style> <body> <div class="top_line"> … -
How to display several employees from mysql on the my index.html?
Code for index in views.py def index(request): employees = Employee.objects.all() schedules = [] for e in employees: s = Schedule.objects.filter(employee_id=e.employee_id, is_active=1) if (s.count() > 0): data = {} data['employee_id'] = e.employee_id data['schedule'] = s schedules.append(data) context = { "employees": employees, "schedules": schedules } print(request.user.username) return render(request, 'index.html', context) Hmtl of Index <div class="col-md-3 parent"> <div class="card card-profile"> <div class="card-avatar"> <a href="#pablo"> <img class="img" src="{% static 'img/faces/marc.jpg' %}"> </a> </div> <div class="card-body"> <h5 class="card-category text-gray">{{ employee.job_title.job_title }}</h5> <h4 class="card-title">{{ employee.first_name }} {{ employee.last_name }}</h4> <h6 class="card-category text-gray">ILO - {{ employee.employee_id }}</h6> <h6 class="card-category text-gray">HOME HEALTH</h6> <p class="card-description" style="font-weight:bold"> My problem is i have several employees on mysql database and i wanted to show those employees on the Index Page, right now only one employee showing up. Thanks if for the help. -
Django loop all existing record to save but only one record save
this is my code in html <tr> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Required Documents:</h2></td> </tr>{% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile-{{d.id}}" value="{{d.id}}" style="outline: none;" required/>{{d.id}}{{d.Description}}</td> <td></td> </tr> {% endfor %} what I tried in my views.py myfile = request.FILES['myfile-6'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() I don't have idea on how to loop this myfile = request.FILES['myfile-6'] with the existing id of Table Documents. please help me guys, im stuck on this problem 3days -
How to make "Group By" query in Django?
I'd like to make the query like this with Django ORM SELECT MAX(`product_item`.`order_value`) AS `max_order_value`, `product`.`title` AS `product_title`, `product`.`thumbnail_url` AS `product_thumbnail_url`, `product_item`.`title` AS `item_title` FROM `product_item` INNER JOIN `product` ON (`product_item`.`product_uid` = `product`.`product_uid`) WHERE ( `product_item`.`state` = 'SALE' AND `product_item`.`hidden` = 'N' AND `product_item`.`latest` = 1 AND `product`.`state` = 'SALE' AND `product`.`last_item_added_date` >= '2019-11-04 10:06:36.640586' AND `product`.`last_item_added_date` < '2019-11-04 10:26:36.640603' ) GROUP BY `product_item`.`product_uid`; And I tried some code below.. ProductItem.objects .filter( state="SALE", hidden="N", latest=1, product__state="SALE", product__last_item_added_date__gte=timezone.now() - timedelta(minutes=20), product__last_item_added_date__lt=timezone.now(), ) .values("product__product_uid") .annotate(max_order_value=Max("order_value")) .annotate( product_title=F("product__title"), product_thumbnail_url=F("product__thumbnail_url"), item_title=F("title"), ) .values( "max_order_value", "product_title", "product_thumbnail_url", "item_title", ) But I kept getting the result which group by with multiple fields that I wrote at last values() function call like this SELECT MAX(`product_item`.`order_value`) AS `max_order_value`, `product`.`title` AS `product_title`, `product`.`thumbnail_url` AS `product_thumbnail_url`, `product_item`.`title` AS `item_title` FROM `product_item` INNER JOIN `product` ON (`product_item`.`product_uid` = `product`.`product_uid`) WHERE ( `product_item`.`state` = 'SALE' AND `product_item`.`hidden` = 'N' AND `product_item`.`latest` = 1 AND `product`.`state` = 'SALE' AND `product`.`last_item_added_date` >= '2019-11-04 10:06:36.640586' AND `product`.`last_item_added_date` < '2019-11-04 10:26:36.640603' ) GROUP BY `product_item`.`product_uid`, product_title, `product`.`title`, `product`.`thumbnail_url`, `product_item`.`title`; How can I fix the orm code to make it work? Thank you -
Get return quote price
We have a quote model that holds details for a quotation and we generate a price based on the from and to location. But it gets messy when you want a return price. Here's the code: def get_price(quote): // do stuff with quote and return the quote object def auto_price(quote): quote = get_price(quote) return_quote = None if quote.is_return: return_quote = deepcopy(quote) return_quote.from = quote.to return_quote.from_place_id = quote.to_place_id return_quote.to= quote.from return_quote.to_place_id= quote.from_place_id return_quote = get_price(quote) I can manually add the values of return_quote in DjangoRest on create() but how do I access this later? There's no return_quote on the original model. Should I make return_quote a JSONField on the model? That will further make things complicated. -
Starting apps on mac with python and pycharm
so im trying to open an app on the terminal on my mac and it says /Users/tiga/PycharmProjects/Pyshop1/venv/bin/python3: can't open file 'manage.py': [Errno 2] No such file or directory what can I do? -
What is the best way to do a matrix style reporting in a Django App?
I have a number of transactions in my model: Transaction Date Category Amount 1 Jan Sales $1000 2 Feb Expense $500 3 Jan Expense $500 4 Mar Interest $100 What is the most efficient way to generate report in view.py that look like this? I know this is an easy questions but I'm curious what is the most efficient way to implement this matrix reporting? Category Jan Feb Mar Sales $1000 Expenses $500 $500 Interest $100 Total $500 -$500 $100 -
Listing foreign key object field in HttpResponse results
I apologize ahead of time, as I'm sure this question has been answered in full, but I must be missing a key component. I'm attempting to list a report's created_by user's first_name field in the existing results. From what I can tell, I have everything set up correctly, but only the Report object's attributes are rendering. In models.py, I have an object "Report" with an FK to the "User" object: created_by = models.ForeignKey(User, related_name='users', on_delete=models.CASCADE) In views.py, I am creating the "reports" object using this: reports = Report.objects.order_by('-created_on').select_related('created_by').all() Running this in a django shell shows the SQL that I would expect, including the first_name field being pulled from auth_user.first_name: >>> print(Report.objects.order_by('-created_on').select_related('created_by').all().query) SELECT "report"."id", "report"."name", "report"."created_on", "report"."created_by_id", "report"."data_source", "report"."report_date", "report"."case_id", "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "report" INNER JOIN "auth_user" ON ("report"."created_by_id" = "auth_user"."id") ORDER BY "report"."created_on" DESC However, I must be doing something wrong in my HTML: {% for report in reports %} <tr> <td>{{ report.name }}</td> <td>{{ report.users.first_name }}</td> <td>{{ report.report_date }}</td> </tr> {% endfor %} I've attempted just about every variation of report.*.first_name that I can think of, but in each case, only the report.name and report.report_date values are coming through. I …