Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting filtered list of items in admin changelist_view()
I need to enrich the changelist_view page with some statistics for the items that are shown, id est after the filters have been applied. But I've found no straightforward way. I can get queryset and parse request URL for the filters, but it's ugly. I can first get super().changelist_view(request), and then I have context_data['cl'].queryset, but that's double work, since I'll need to make HTML again with my added data. Is there some better way? I think the closest question was Django admin change_list view get ChangeList queryset - better solution than my monkey patch, but there was no answer there… -
How to get notification on template using django signals?
I'm a beginner's level Django developer and I'm making a hospital system. In the hospital system, I want to add a notification system whenever any patient uploads a report against the doctor id I want to inform the doctor to the doctor notifications template that the report of patient(with name) has been submitted. I was trying it to work for 2 days and used signals to create a message but I'm unable to show it on the doctor's side. Please anyone can tell me how can I make it easier or Should I use something else instead of signals. The Previous Code that I tried. from django.shortcuts import render, HttpResponse,request from hospital.models import Patient ,Doctor,Report from django.db.models.signals import post_save,pre_save def save_report(sender,instance,**kwargs): instance = Patient.objects.get(id=1) dr_id= instance.assignedDoctorId patient=models.Patient.objects.get(user_id=request.user.id) doctor=models.Doctor.objects.get(id=dr_id) notifications=print("New report has been submitted") mydict={ 'doctor':doctor, 'patient':patient, 'notifications':notifications } return render(request,'temp/doctor_Notifications.html',context=mydict) post_save.connect(save_report,sender=Report) -
Vendor Permission in Django
How to set permissions in Django so that a Vendor can delete or update their own product, not others. This means if they log in from their account then they can only update or delete their own product, not others. -
Django ImportError at/ boards doesn't look like a module path
first of all, I'm a junior programmer and this is the first question in this communicate so, I have a problem when I configure the HTML file with Django this error comes on my face, please guys help me ImportError -
Tempus dominus form input not valid
Im using tempus dominus widget to pick a date and time in my django project. I realised that particular line made the form return False for form.is_valid(). The is_valid() function only returns false when I add that date field with the tempus dominus widget in my forms.py. views.py @require_http_methods(["POST"]) def saveBooking(request): form = BookingForm(request.POST, request.FILES) print(form.is_valid()) <--returns False forms.py from tempus_dominus.widgets import DateTimePicker class BookingForm(forms.ModelForm): # Next line gives error date = forms.DateTimeField(widget=DateTimePicker(options={ 'useCurrent': True, 'collapse': False, }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ), label="" ) models.py class Booking(models.Model): date = models.DateTimeField(default=timezone.now,null=False) -
Play the uploaded video(One video in one page) in detail page
After clicking watch Home page Code structure If any one can help me with this, It will be very kind of you, Stuck for weeks in this Source used in html file <source src='{{ MEDIA_URL }}{{ movie_file }}' type='video/mp4'> views.py def Movie_detail(request, pk): lastvideo = Postmovie.objects.last() movie_file = lastvideo.movie_file post = Postmovie.objects.filter(Published_date__lte=timezone.now()).order_by('-Published_date') #movie = Postmovie.objects.all() stuff_for_frontend = {'post': post, 'movie_file': movie_file} return render(request, 'Movie_Management_System/Movie_details.html', stuff_for_frontend) # render movie details Here last video is only shown knowingly because the video was not playing and i came up with this logic but i want to play those videos which are uploaded in form Post_list.html <div class="card" style="width: 18rem;"> {% if post.Thumbnail %} <img class="card-img-top" src="{{post.Thumbnail.url}}" alt="Card image cap"> {% endif %} <div class="card-body"> <h5 class="card-title">{{post.movie_title}}</h5> <p class="card-text">Released: {{post.release_date}}</p> <a href="{% url 'Movie_detail' pk=post.pk %}"class="btn btn-primary">Watch</a> </div> </div> above i wanted to show the source how On clicking watch site is directed to detail page [Home pageAfter clicking watch -
how do i pre fill a form field with a models object in django
i have two pages profile and add notes. i want to fill the patient field in the add notes form with the users first name whenever i click add notes on any users profile will i need to change the url path? if yes, how do i get the data from the url and fill it in the form. urls.py urlpatterns = [ path('', dashboard, name='dashboard'), path('profile/', profile, name='profile'), path('profile/<str:slug>/<int:pk>', profile, name='profilepk'), path('edit_profile/<int:id>/', edit_profile, name='editprofile'), path('addnotes/', addnotes, name='addnote'), ] views.py def addnotes(request): profile = Profile.objects.get(user_id=id) form = PatientNotesForm(request.POST or None) if form.is_valid(): form.save() return redirect(f'/dashboard/profile/{user.profile.slug}/{user.pk}') return render(request, 'core/addnotes.html', {'form': form}) def profile(request, slug, pk): profil = Profile.objects.get(slug=slug) profile = Profile.objects.get(pk=pk) context = {'profile': profile, 'profil': profil} return render(request, 'dashboard/profile.html', context) models.py class Note(models.Model): illness = models.CharField(max_length=1000, blank=True) patient = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='patientnote', null=True) Doctor = models.CharField(max_length=100, blank=True) Description = models.CharField(max_length=10000, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.illness}" forms.py class PatientNotesForm(ModelForm): illness = forms.CharField(max_length=100, help_text='First Name') patient = forms.CharField(max_length=100, help_text='Last Name') doctor = forms.CharField(max_length=100, help_text='address') description = forms.CharField(max_length=100,widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['illness'].widget.attrs.update( {'placeholder': ('illness')}) self.fields['doctor'].widget.attrs.update( {'placeholder': ("Doctor's name")}) self.fields['patient'].widget.attrs.update( {'placeholder': ("Patient's name")}) self.fields['description'].widget.attrs.update( {'placeholder': ("Description")}) self.fields['illness'].widget.attrs.update({'class': 'log'}) self.fields['doctor'].widget.attrs.update({'class': 'log'}) self.fields['patient'].widget.attrs.update({'class': 'log'}) self.fields['description'].widget.attrs.update({'class': 'textarea'}) class Meta: model = … -
channel_layer.group_send not working properly
I'm going along with the channels tutorial and I have the exact same code as mentioned in the documentation's tutorial. It's a simple chat application which echos the message to other connection in the same room. here is my consumer class: # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) the problem is the consumer is sending all messages only to the last connection of the same group. for example if i open 2 browser tabs with /chat/room1/, only the second tab will be able to see the messages. -
Using the user_username instead of user_id to access a user profile
How can I access a model object by their username instead of their id or how can I convert the username into an id that can then be used to access a model object? I have a view like below where the argument that is being passed in is the user_username: views.py def profile_page(request, user_username): form = FollowUserForm(request) profile = Profile.objects.get(user=user_username) return render(request, "network/profilePage.html", { "form": form, "profile": profile }) I know that we can't put the user equal to user_username so is there a way of converting the username somehow into an id which I can then use to access the relevant Profile object? I'm doing it like this because in my urls.py I want the url to show the user's username rather than just a number id. urls.py path("profile/<str:user_username>", views.profile_page, name="profile"), -
How to integrate Zoom services into a django website?
With a website project under construction, the need for 1-to-1 video calls arose. I have decided to use Zoom services for this purpose but I struggle to implement it. Although their docs are extensive, for me it is not clear how to implement it with this framework. I would appreciate any general step by step guidance on this implementation process as well as any links to articles/videos/ etc on this topic. Any guidance will be a great help. -
divide items that belongs to two query sets in django
I have created two querries in django . One that returns number of handled calls per agent and second returns the missed calls per agents. I would like to know how to combine the two queries in order to get a percentage of handled calls par agent, which means take the total from the query3 and divide it on the total of query2 grouped by agent , Of course i will render the result to the web page Here are the two queries Thanks # A query that returns total calls that has been handled queryset2 = CsqAgentReport.objects.values('agentname').filter(Q(originatordnhandeled__contains='1') | Q(missedcallshandeledy_n__contains='1')).exclude(agentname__contains='None').annotate(total=Count('nodeid_sessionid_sequenceno', distinct=True)).order_by('agentname') # A query that returns total calls that has been missed queryset3 = CsqAgentReport.objects.values('agentname').filter(originatordnnothandeled__contains='1').filter(ringtime__gt = '00:00:00').exclude(agentname__contains='None').annotate(total=Count('nodeid_sessionid_sequenceno', distinct=True)).order_by('agentname') -
upstream sent no valid HTTP/1.0 header
I have made a Django project in which I have created a Django-channels app. My chat app is working when I run manage.py run server 0.0.0.0:8000 on the server and works fine but on my IP address i.e. on the website it doesn't work while in Nginx error logs it says - *13 upstream sent no valid HTTP/1.0 header while reading response header from upstream, client: 132.154.xxx.xxx, server: www.website.com, request: "GET /ws/chat/room_id/ HTTP/1.1", upstream: "http://0.0.0.0:6379/ws/chat/room_id/", host: "www.website.com" this is my nginx conf. file- server { server_name www.website.com website.com; client_max_body_size 4G; keepalive_timeout 5; charset utf-8; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/saurabh/thinkgroupy; } location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location /ws/ { proxy_pass http://0.0.0.0:6379; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/website.com/fullchain.pem; # manag> ssl_certificate_key /etc/letsencrypt/live/website.com/privkey.pem; # man> include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot } server { if ($host = www.website.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = website.com) { return 301 https://$host$request_uri; } # managed by … -
Cannot run unit tests in django project. ModuleNotFoundError: No module named 'xxxx'
I started developing some time ago in new project written in django. In tests directory there is Dockerfile, but it takes some time to build everything and run. I Would like to run my tests locally in pycharm, but when i do this then i get it: error description Line in code which raises error looks like that from project.settings import *, but pycharm is ok with it. Structure of the project I suppose that pycharm is ok because src directory is marked as root - thanks to that imports work, but when pytest runs tests it doesn't see src as root. pytest config Theoretically i could change all paths to start from src like from src.project.settings import *, but hundreds of them are in the project, so i think there is better way to resolve this problem -
Keep getting "Page not found". What to do?
**Can someone please help me solve this problem I just started learning Django. I keep getting getting "PAGE NOT FOUND " whenever i open/click the list/entries In my "entries" folder i have Css.md Django.md Git.md Python.md HTML.md** urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry" views.py from django import forms class NewEntryForm(forms.Form): title = forms.CharField(max_length=100) content = forms.CharField(widget=forms.Textarea) def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, entry): entries = util.get_entry(entry) if entries is None: return render(request, "encyclopedia/error.html", { "message1": "Sorry", "message2": "your requested page was not found " }) return render(request, "encyclopedia/index.html", { "content": entries, "form": NewEntryForm }) index.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia - {{title}} {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href="{{entries}}"></a></li> {% endfor %} </ul> {% endblock %} entry.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia - {{title}} {% endblock %} {% block body %} <div class="container"> <div class="row"> {% if not content%} <div>Sorry, your requested page was not found </div> {% else %} {{ content | safe }} <div><a href="{% url 'edit' entry %}>Edit this entry</a></div> {% … -
no reverse math in django
in veiws.py def updateTask(request, pk): task = Tasks.objects.get(id=pk) return render(request, 'update.html') in urls.py urlpatterns = [ path('', views.index, name='list'), path("update_task/<str:pk>/", views.updateTask, name='update'), ] in templates : {% for task in tasks %} <div> <p> {{ task }}<p> <a href="{% url 'update_task' task.id %}">update</a> </div> {% endfor %} but i am receiving error of NoReverseMatch -
Why does django server startup fails after deprecation warning?
I installed django-dash library in my app and tried starting the server but I keep running into the below error during launch : Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\dash\models.py", line 10, in <module> from nine import versions File "C:\Users\Adnan\Documents\myapp\simple-django-login-and-register-master\env\lib\site-packages\nine\versions.py", line 7, in <module> DeprecationWarning DeprecationWarning: The `nine` namespace is … -
send_email() Display attach in the mail
At the current stage the email is fully working, however, when receiving the actual mail the image is not attached, rather is name is displayed. I wold like to display che attachment in order to be able to download it. ''' def publication(request): if request.method == "POST": inputImmagine1 = request.POST['inputImmagine1'] send_mail( 'Richiesta di pubblicazione - Condoglianze', #subject inputImmagine1, #message inputEmail, # from email ['XXX@gmail.com'], # to email ) return render(request, 'publication.html', {'inputImmagine1': inputImmagine1}) else: return render(request, 'publication.html', {}) ''' -
How to customize SearchHeadline in django full text search?
I want to highlight search terms with SearchHeadline. My code is somethink like this: query = SearchQuery('cat') vector = SearchVector('caption') Post.objects.annotate( search=vector headline=SearchHeadline( 'caption', query ) ).filter(search=query) This code works well and for example the headline of the first result is: 'My <b>cat</b> breed is Persian. Persian cats are the most beautiful breed.' As you can see cat is highlighted but cats is not, and I want to highlight all of cat string in the caption, like this: 'My <b>cat</b> breed is Persian. Persian <b>cat</b>s are the most beautiful breed.' -
Django Migrating DB django.db.utils.ProgrammingError: relation "django_site" does not exist
Doing a site upgrade for Django, now pushing it to the server when I try python manage.py makemigrations I get this error (kpsga) sammy@kpsga:~/webapps/kpsga$ python manage.py makemigrations Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ The above exception was the direct cause of the following exception: ... File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/sammy/webapps/kpsga/kpsga/urls.py", line 27, in <module> path('blog', include('blog.urls')), ... File "/home/sammy/webapps/kpsga/blog/urls.py", line 2, in <module> from blog.views import LatestBlogEntries, blog_archive, blog_entry_by_id, blog_entry File "/home/sammy/webapps/kpsga/blog/views.py", line 10, in <module> class LatestBlogEntries(Feed): File "/home/sammy/webapps/kpsga/blog/views.py", line 11, in LatestBlogEntries current_site = Site.objects.get_current() File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/contrib/sites/models.py", line 58, in get_current return self._get_site_by_id(site_id) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/contrib/sites/models.py", line 30, in _get_site_by_id site = self.get(pk=site_id) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 425, in get num = len(clone) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 269, in __len__ self._fetch_all() File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return … -
Should I create an app for every page? (Django)
I'm new to Django. I am currently trying to bring my static html/css website to Django (mainly for learning). My only doubt is: should I use a new app for every page I have? The doubt comes from the fact that the title which I'll give to the pages are different, hence making page_title variable requires me to write in views.py, but I can't (maybe I'm wrong) write multiple page_title variables inside the same app's views.py. Thanks for your time! -
Django Filter SearchForm by a Category
My Django application has a search function. To give the user a more accurate search result its also possible to filter by a category before sending the search request. To get the Category object the user can select from at a drop-down menu, I have a form like this: class CategorySearchForm(forms.ModelForm): class Meta: model = Post fields = ['category'] def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(CategorySearchForm, self).__init__(*args, **kwargs) self.fields['category'].required = False self.fields['category'].empty_label = 'All Categories' Currently this is working but to me this is ugly as I reference my category objects by my Post model: category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) Now my Question: How can I get all Category objects at my CategorySearchForm directly by the Category model instead of the Post model? This is how my Category Model looks like: class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(verbose_name="Title", max_length=40, validators=[MinLengthValidator(5)]) description = models.TextField(verbose_name="Description", max_length=3000, validators=[MinLengthValidator(150)], blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title def publish(self): self.published_date = timezone.now() self.save() -
unsupported operand type(s) for +: 'QuerySet' and 'int'
models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nickname = models.CharField(max_length=50) user_test_point = models.IntegerField(default=0) views.py : def test_result(request): user_test_point = Profile.objects.values('user_test_point') test_word = request.GET['test_word'] test_mean = request.GET['mean'] flag = "flag" if test_mean == test_word: flag = "correct" Profile.objects.values('user_test_point').update(user_test_point + 1) context = {"flag": flag} return render(request, 'test_result.html', context) else: flag = "wrong" context = {"flag": flag} context['mean'] = test_mean return render(request, 'test_result.html', context) I created user_test_point in enter code heremodels.py. Then, I want to add point 1 if user's answer is correct. I wonder can I modify this code "Profile.objects.values('user_test_point').update(user_test_point + 1)"? I want to know how to fix this error "unsupported operand type(s) for +: 'QuerySet' and 'int'". -
Problem when trying to migrate from Django to Heroku
I am currently trying to deploy my Django project on to a free Heroku server. When I try to execute the following command I get an error heroku run python3 manage.py migrate. The error is as follows: Running python3 manage.py makemigrations on ⬢ samstaskmanager... up, run.5214 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, … -
Extracting particular columns of a specified row
Hello Guys i am new to this kindly help me out. I have a table like - now i want a button on click i should get names of all children for that my code is - views.py - def view(request): datas=Table.objects.all().values('Parent_Name').distinct() for data in datas: childrennames = datas.filter(Parent_name = data['Child_Name']).values('Child_Name') return render (request,'t.html',{'datas':datas},{'childnames':childnames}) html- {% for data in datas %} <li><span><button>{{data.parent_name}}</button></span> <ul class="nested"> <li><span><button>{{childrenname.child_name}}</button></span> <ul class="nested"> </ul> </li> </ul> </li> {% endfor %} but this is not working please help where am i wrong ? kindly ignore the capital and small letter issue in code. my Database is PostgresSQL. is the query fault or data base fault ? -
Problem in creating Login Function based on Custom ModelForm DB in Django
I didn't want to use Django's inbuilt form, so I made a ModelForm and I was able to implement registering a user based on my ModelForm. But now I want to login using the ModelForm DB to authenticate the user. Is there any way to make a custom authentication based on the ModelForm that I made? I have added code snippets of models.py, forms.py and views.py! hope its enough! models.py from django.db import models # Create your models here. LEVELS = [ ('AD', 'ADMIN'), ('VU', 'VIEW AND UNLOCK'), ('V', 'VIEW ONLY') ] class Clients(models.Model): name = models.CharField(max_length=200, null=True) phone = models.IntegerField(null=True) pswd = models.CharField(max_length=200, null=True) access_level = models.CharField(max_length=2, choices=LEVELS) def __str__(self): return self.name class Meta: verbose_name_plural = "Clients" forms.py from django import forms from django.forms import ModelForm from iot.models import Clients class Clientsform(ModelForm): class Meta: model = Clients fields = '__all__' widgets = {'name': forms.TextInput(attrs={'class': 'form-control', 'required': 'True'}), 'phone': forms.NumberInput(attrs={'class': 'form-control', 'required': 'True'}), 'pswd': forms.PasswordInput(attrs={'class': 'form-control', 'required': 'True'}), 'access_level': forms.Select(attrs={'class': 'form-control', 'required': 'True'})} views.py def register(request): form = Clientsform() if request.method == 'POST': form = Clientsform(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('name') messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form': form} return render(request, "form.html", context) …