Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add field when the user click the button
Is it possible to add field in models depends on how many times the user click the button? example: original samplemodel class samplemodel(models.Model): username=models.CharField(max_length=500) category=models.CharField(max_length=500) date=models.DateField(max_length=500) html <input type="text" name="category"> <input type="date"> <input type="submit"> if the user click the submit button twice the samplemodel will look like this class samplemodel(models.Model): username=models.CharField(max_length=500) category=models.CharField(max_length=500) category1=models.CharField(max_length=500) /user add category2=models.CharField(max_length=500) /user add date=models.DateField(max_length=500) date1=models.DateField(max_length=500)/user add date2=models.DateField(max_length=500)/user add -
How to test a Queryset in Django
I'm quite new to Django and need help with testing my view module. Right now the view only returns all the objects from the DB: return people.objects.all() I want to test that the view returns all the objects. I know that I should use assertQuerysetEqual and I have read about it but still not sure how to implement it because I couldn't understand much from the documentation. Would appreciate it greatly if someone could show some examples or explain. -
Setting up django with docker on VM
I'm new to Docker. I'm trying to set up django with docker by following this documentation: https://docs.docker.com/compose/django/ I'm on Windows 10 Home running Docker with DockerToolbox (using a VM). My problem is when I run docker-compose run web django-admin startproject composeexample . I can't see the Django files created, even though the docker image has been successfully built. PS: • When I check the container in Kitematic, the path is /usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin • When I go to the Volumes tab, the local folder is empty. -
How to search for other user in ldap and put user model in Django
I want search user in ldap and give access to certain part of website. To achieve this, how to do I search ldap directory using username or full name? Once I have person found on ldap than how can I push that information in user model of Django? -
Order queryset by a method in django
I am trying to order QuerySet by a method defined in my class Class EgzampleClass(models.Model): somefield = models.ForeignKey(User) otherfield = models.CharField() @property def mymethod(self): countsth=1 return countsth I would like to do a thing like this EgzampleClass.objects.all().order_by('mymethod') Does anyone have an idea how can I do it? Thanks in advance -
request.GET.get('q', None) always returns None
# my .views def search_view(request): query = request.GET.get('q', None) print(query) context = {"query": query} return render(request, 'view.html', context) # .urls path('search/', search_view) # my view.html {% if query %} <p>Your query {{ query }}</p> {% else %} <form method="GET" action='/search/'> <input type="search" name='q' placeholder="Search" aria-label="Search"> <button type="submit">Search</button> </form> {% endif %} I'm new to Django and I'm following the docs, I looked over and over and seems right to me but I keep getting query=None. When I input a value in the search bar goes to http://127.0.0.1:8000/search/?q=value, but the query is always None. Please help a noob getting started. -
Is Django the best web framework to use?
I want to build a small web application in which you can upload a database in SQL or SQLite and it will convert the data into an XML file. I will like to include minimal settings to decided if child tags or attributes are used for different parts of the XML file. I took some online courses in Python some time ago and I started learning Django recently. I am afraid I will spend time learning Django when it might not be the right/best framework to use. I will appreciate any advice or suggestions on how to go about my project. Thanks Bennett -
Chrome automatically downloading PDF
<div align="justify" style="height: 500px; border: 1px solid #ccc; overflow: auto;"> <object data="/policy/download/#zoom=65,65,720" type="application/pdf" width="100%" height="500"></object> </div> thats piece of code, am using django 2.2 and python 3.6.7. So that code is for sake of viewing https://chrome.google.com/webstore/detail/pdf-viewer/oemmndcbldboiebfnladdacbdfmadadm/related?hl=en via pdf viewer extension. However, chrome is causing problem by auto downloading the pdf. Only chrome not firefox. -
django oscar create offers
i want to create product package with quantity to give bulk offer. as example my product package has two products, product A has 2 quantity product B has 1 quantity if this product package added to basket, then its need to check product with quantity not only product item, then only i need to add this offer to basket. and another thing is, if product A has another single offer and if in basket, product A has 3 quantity (2 quantity from product package, 1 quantity from standalone) then, this single offer also need to be apply. sample data product package = [ { product : A, quantity: 2, each_price: 100 }, { product : B, quantity: 1, each_price: 200 }, benefit: { type: Absolute, value: 10 } ] product A has single offer { type: Absolute, value: 20 } if basket has following products and quantity, i need to add these two offers, { lines: [ { product : A, quantity: 3, each_price: 200 // without discount }, { product : B, quantity: 1, each_price: 100 // without discount } ], offer_discounts:[ { offer_name: product_package, offer_discount: 10 }, { offer_name: prdocut_a_single, offer_discount: 20 } ] } in my basket … -
How to return 5 database 5 row, two rows with nearest upper value and two rows with nearest lower value of a given value?
How to return 5 database 5 row, two rows with nearest upper value and two rows with nearest lower value of a given value? e.g - points are , 22, 25, 27, 30, 20, 22, 23, 42, 15, 18, 28, Suppose the given value is 23, so, the return values would be - 22,22,23,25,27 sort by modified date. I am using Django and postgres. Currently What I have done is - separately - returning nearest upper and lower 2 row. total_points = user.total_points # userData = PointLeaderboard.objects.filter(user=user).first() leaderObj = [] upperRanks = reversed(PointLeaderboard.objects.filter( Q(total_points__gt=total_points) | Q(total_points=total_points, pk__gt=user.id) ).order_by('-date_modified', 'total_points')[:2]) for upperRank in upperRanks: print(upperRank.user.id) print(upperRank.total_points) row = { 'username':'', 'email': upperRank.user.email, 'total_points':upperRank.total_points, 'point_difference': '+'+str((upperRank.total_points - total_points)), 'is_current_user':False } leaderObj.append(row) row = { 'username': '', 'email': user.email, 'total_points': total_points, 'point_difference': '0', 'is_current_user': True } leaderObj.append(row) lowerRanks= PointLeaderboard.objects.filter( Q(total_points__lt=total_points) | Q(total_points=total_points, pk__lt=user.id) ).order_by('-total_points', 'date_modified')[:2] for lowerRank in lowerRanks: row = { 'username': '', 'email': lowerRank.user.email, 'total_points': lowerRank.total_points, 'point_difference': str((lowerRank.total_points - total_points)), 'is_current_user': False } leaderObj.append(row) But the problem is when the given point is same with multiple value, I need to sort by oldest first. What will be the right approach to over come this challenge? -
I am new to django ,how to allow the users to access the homepage only after logging in?
pmmvy urls.py(I am redirecting to pmmvapp.urls from here) from django.contrib import admin from django.urls import path,include from users import views as user_views from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('register/',user_views.register,name='register'), path('profile/',user_views.profile,name='profile'), path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('', include('pmmvyapp.urls')), ] pmmvyapp urls.py(I tried using a few things to redirect to login page as homepage but couldn't) from django.urls import path from .views import ( PostListView,PostDetailView,PostCreateView,HomeView PostUpdateView,PostDeleteView,UserPostListView) from . import views urlpatterns = [ path('',views.HomeView.as_view(),name='pmmvyapp-home'), path('user/<str:username>', UserPostListView.as_view(),name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(),name='post-detail'), path('post/new/', PostCreateView.as_view(),name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(),name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(),name='post-delete'), path('about/', views.about,name='pmmvyapp-about'), ] settings.py (I've installed all the apps and given the login redirect) INSTALLED_APPS = [ 'users.apps.UsersConfig', 'pmmvyapp.apps.PmmvyappConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] CRISPY_TEMPLATE_PACK='bootstrap4' LOGIN_REDIRECT_URL='pmmvyapp-home' LOGIN_URL='login' pmmvyapp views.py from django.views.generic import ListView,DetailView,CreateView,UpdateView, DeleteView from django.shortcuts import render,get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin from django.http import HttpResponse from .models import Post def home(request): context={ 'posts':Post.objects.all() } return render(request,'pmmvyapp/home.html',context) class PostListView(ListView): model = Post template_name='pmmvyapp/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name='pmmvyapp/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User,username=self.kwargs.get('username')) … -
ModuleNotFoundError: No module named 'config' - Tethys
I am on Catalina (Mac) using Python 3.7 I also have the following installed - Homebrew/Miniconda/Pyenv/Pipenv I am running into this error while running some Django projects as well as this project called Tethys which utilizes Django. I cannot if this has anything to do with .zsh or my env. What is the best approach to diagnosing the following issue? Thank you conda create -n tethys -c tethysplatform -c conda-forge tethys-platform conda activate tethys tethys db configure File "/Users/user/opt/miniconda3/envs/tethys/bin/tethys", line 10, in <module> sys.exit(tethys_command()) File "/Users/user/opt/miniconda3/envs/tethys/lib/python3.7/site-packages/tethys_cli/__init__.py", line 66, in tethys_command args.func(args) File "/Users/user/opt/miniconda3/envs/tethys/lib/python3.7/site-packages/tethys_cli/db_commands.py", line 384, in db_command options = process_args(args) File "/Users/user/opt/miniconda3/envs/tethys/lib/python3.7/site-packages/tethys_cli/db_commands.py", line 348, in process_args db_settings = settings.DATABASES[args.db_alias] File "/Users/user/opt/miniconda3/envs/tethys/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/user/opt/miniconda3/envs/tethys/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/user/opt/miniconda3/envs/tethys/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/user/opt/miniconda3/envs/tethys/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
How to test admin change views?
I got a rather complex admin change view for my Django model. There is a lot of resources about how to test the admin list views (e.g. here), but not for the change view. How can I create a test cases for it? -
Get id of nonexistent object for tests - django
I'm using DjangoModelFactory to create custom objects needed for tests. The issue is that I would like to write test for situation where there is a request for nonexistent object. Is there any elegant way to automatically generate such ID. One idea I have had was to use really big number, as test suite should never reach such number. Another idea is to create object, store ID and then delete the object. Both those solutions are somewhat hacky - firs has rather risky assumption that the big number will not be assigned as ID as part of tests, the other is based on additional logic which makes tests more dependent on non-related logic. Is there any simple and out-of-the box solution to get id which is not assigned to any object? -
Django and bootstrap and django crispy forms error
I have created a sign in page for my blog, using bootstrap and django. I recently imported crispy forms and when I try and go to the page I get the following error: TemplateDoesNotExist at /register/ how ever all my redirects and urls are setup correctly, on the Django debug It says that the error is in my base HTML file, under the head section where I imported bootstrap CSS, I can provide any code nessicary. It says this on my server: django.template.exceptions.TemplateDoesNotExist: bootsrap4.4.1/uni_form.html -
Return function data to django template
I feel like I'm probably over-complicating this... I'm retrieving data from an external source and trying to display it within a Django template. I have created a quick .py script and i can print the data inside the function. However, i can't seem to access the data outside the function. I have also tried accessing the data by overwriting the 'get_context_data' method in a CBV. Again, I can see the data when I print it. But it won't seem to store outside the function for me to use in the template. Example: def get_context_data (self, **kwargs): def event_notification(source, event): peers = [] for i in event: peers.append(i) print('notify-send "%s" "%s"' % (event.name, str(event))) return peers client.add_event_listener(EventListener(on_event=event_notification)) kwargs['test'] = event_notification return super ().get_context_data (**kwargs) The only way I can see to do it is to store each 'event' inside a list and use that data outside the function. As mentioned above, the print statement runs fine. But I can't seem to access any of the data outside the function. I've also tried adding a property to the model. I can't seem to work out the best method to achieve it. Any help would be much appreciated. *Ignore indentation as it's not … -
Way to pass information from a GET parameter to a POST form in django?
I have a mailing list system in which a user can click a link to unsubscribe. This link contains the user's email in a GET parameter and the page it points to contains a short form to ask for feedback. This feedback needs to point to the email of the user who submitted it. The way I tried to achieve this is: take the email from the GET parameter put it as initial value in a hidden field on the feedback form retrieve it from form data when the form is sent The problem is that if this hidden field is not disabled, the user can meddle with its value and dissimulate his own identity or even claim that the feedback came from another user. But if I set the field as disabled, the request.POST dictionary does not contain the field at all. I also tried keeping the field enabled and checking for its presence in form.changed_data, but it seems to always be present there even if its value does not change. This is the form class: class UnsubscribeForm(forms.Form): reason = forms.ChoiceField(choices=UnsubscribeFeedback.Reasons.choices) comment = forms.CharField(widget=forms.Textarea, required=False) user_email = forms.CharField(widget=forms.HiddenInput, required=False, disabled=False) This is how I populate user_email in the view … -
Disallowed host
**> DisallowedHost at / Invalid HTTP_HOST header: 'hobin505.pythonanywhere.com'. You may need to add 'hobin505.pythonanywhere.com' to ALLOWED_HOSTS. Request Method: GET Request URL: http://hobin505.pythonanywhere.com/ Django Version: 2.2.10 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: 'hobin505.pythonanywhere.com'. You may need to add 'hobin505.pythonanywhere.com' to ALLOWED_HOSTS. Exception Location: /home/hobin505/my-first-blog/myvenv/lib/python3.8/site-packages/django/http/request.py in get_host, line 111 Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.0 Python Path: ['/var/www', '.', '', '/var/www', '/home/hobin505/my-first-blog/myvenv/lib/python38.zip', '/home/hobin505/my-first-blog/myvenv/lib/python3.8', '/home/hobin505/my-first-blog/myvenv/lib/python3.8/lib-dynload', '/usr/lib/python3.8', '/home/hobin505/my-first-blog/myvenv/lib/python3.8/site-packages', '/home/hobin505/my-first-blog'] Server time: 목요일, 20 2월 2020 23:31:37 +0900** I don't know what should I do... I haven't yet scratched the surface of django, so would you appreciate some help as to how to fix this? -
how to resolve 'CSRF verification failed' of the bootstrap modal in django
I have a button that opens bootstrap modal to fill a form: <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">add site</button> Also, I have a modal form to add some data and send it to a function: <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h5 class="modal-title" id="exampleModalLabel">Add the monitor</h5> </div> <div class="modal-body"> <form style="float: left;" method="POST" action="{% url 'addhttp' %}"> {% csrf_token %} <div class="form-group"> <label for="name">site name: </label> <input type="text" name="name" id="name" /> <label for="url">address: </label> <input type="text" name="url" id="url" /> <label for="interval">Interval: </label> <input type="number" min="2" name="interval" id="interval" /> <input class="btn btn-primary" type="submit" value="add" /> </div> </form> </div> </div> </div> </div> This is according to this link: Varying modal content And this is the method that works on the form data: @login_required def addhttp(request): """Add a URL for monitoring in user panel""" if request.method == 'POST': if request.POST['name'] and request.POST['url'] and request.POST['interval']: httpmonitor = HttpMonitor() httpmonitor.name = request.POST['name'] if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'): httpmonitor.url = request.POST['url'] else: httpmonitor.url = 'http://' + request.POST['url'] httpmonitor.interval = int(request.POST['interval']) httpmonitor.user = request.user httpmonitor.save() httpsites = HttpMonitor.objects.filter(user=request.user) return render(request, 'pages/dashboard.html', {'httpsites':httpsites, 'info':'Done'}) else: httpsites = HttpMonitor.objects.filter(user=request.user) return render(request, 'pages/dashboard.html', … -
Django if record is already exist()
I hope my title is enough to understand what my problem is, I have this code in my views.py section = request.GET.get('section') subject = request.GET.get('subject') teacher = request.GET.get('teacher') grade = request.GET.get('grade') period = request.GET.get('period') if studentsEnrolledSubjectsGrade.objects.filter(Subject_Section_Teacher__Employee_Users = teacher).filter(Subject_Section_Teacher__Sections = section).filter(Subject_Section_Teacher__Subjects = subject).filter(grading_Period=period).exist(): update = studentsEnrolledSubjectsGrade.objects.filter(Subject_Section_Teacher__Employee_Users = teacher).filter(Subject_Section_Teacher__Sections = section).filter(Subject_Section_Teacher__Subjects = subject).filter(grading_Period=period) return render(request, 'Homepage/result.html',{"update":update}) else: teacherStudents = studentsEnrolledSubjectsGrade.objects.filter(Subject_Section_Teacher__Employee_Users = teacher).filter(Subject_Section_Teacher__Sections = section).filter(Subject_Section_Teacher__Subjects = subject).filter(grading_Period=period) return render(request, 'Homepage/result.html',{"teacherStudents":teacherStudents}) it doesnt work, please help me guys to fix my code, thanks in advance -
Is there a way to resolve "Call was rejected by Callee" error during Dispatch of PowerPoint in Python?
I have a Django app and my view tries to convert pptx to pdf using Win32Com. It was giving error to open multiple instances so I used DispatchEx (and have even tried gencache and dynamic dispatch). I am even using subprocess for each request to my view but I keep getting an error "Call was rejected by Callee" when multiple requests are sent simultaneously. Surprisingly, the error does not happen if I dont quit and close the powerpoint presentation and application. It has been hours since I am trying to make it work to simply handle different client requests and make pdfs for them from a pptx template, but all in vain. Please help! import shutil import sys import subprocess as subp import win32com.client import pythoncom from datetime import datetime import os import time def do_powerpoint(filename): """run external copy of self to do powerpoint stuff""" # sys.executable is the python.exe you are using, __file__ is the # path to this module's source and filename you pass in return subp.call([sys.executable, __file__, filename]) def _do_powerpoint(filename): try: rundate = "Quote_{:%d%m%Y_%H%M%S%f}".format(datetime.now()) pythoncom.CoInitialize() APPLICATION = win32com.client.DispatchEx("PowerPoint.Application") APPLICATION.Visible = True # I think False is better so you dont see it pop up path_ppt = shutil.copy(filename, … -
Django - linking multiple ChoiceField's
I need to have user inputing his address by first select country, then city, then district, and then sub-district. How do I best implement this functionality in django Form? The models are similar to this: `Class Country(models.Model): name = models.CharField(max_length=30) Class City(models.Model): name = models.CharField(max_length=30) country = models.ForeignKey(Country) Class District(models.Model): name = models.CharField(max_length=30) city= models.ForeignKey(City) Class Subdistrict(models.Model): name = models.CharField(max_length=30) district= models.ForeignKey(District)` -
Get list of field names from a ModelSerializer class
If I have a serializer such as: class RandomSerializer(serializers.ModelSerializer): class Meta: model = Random fields = ["id", "field_a", "field_b"] Is there a way to access Meta.fields without creating an instance of the serializer? -
Django datepicker issue, $ is not recognised
Hi fully aware that this looks like a duplicate, but it's not, the fixes for the other questions did not solve this issue. I'm trying to add a datepicker to my django forms, but I've never used jquery before, but now it seems I have to, but can't get it working. I'm trying to follow this guide https://simpleisbetterthancomplex.com/tutorial/2019/01/03/how-to-use-date-picker-with-django.html#fengyuan-chens-datepicker and trying to use the fengyuanchen_datepicker. I can't get it working at all and I think it is because of the cdn links at the top of the page. Here is the header: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Project Portal+ :: sidev</title> <link rel="shortcut icon" href="{% static 'project_portal/images/favicon.ico' type='image/x-icon' %}"> <link rel="stylesheet" href="{% static 'project_portal/css/project_portal.css' %}"> <link type="application/javascript" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/i18n/datepicker.en-GB.min.js"> <script src="jquery-3.4.1.min.js"></script> </head> and here is the html I am trying to get it working in: <!DOCTYPE html> {% extends "project_portal/base.html" %} {% block detail %} <div class="project_setup"> <h1>Project Setup</h1> <form class="update" method="POST"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" class="btn" value="Submit"> <a href="{% url 'project-list' %}">Cancel</a> </form> </div> <script> $(function () { $("#id_date").datepicker({ format: 'dd/mm/yyyy', }); }); </script> {% endblock %} I'm assuming the "$" is a jquery thing, which i personally would rather … -
Django Management Command best practice for additional file location
I am writing a Django management command. The command itself is located under myapp/management/commands/mycommand.py. I need to write an additional class which I would like to place in an extra file. Should this file live in myapp/extrafile.py or myapp/management/commands/extrafile.py What would be a recommended location. The class is only need for the management command, not elsewhere in the app.