Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions'
Error Occurs while using router if i avoid router it didnt raise Error urls.py ''' from rest_framework.routers import SimpleRouter from django.urls import path,include from . import views router = SimpleRouter() router.register('view-client', views.Client_view.as_view(), base_name='view') urlpatterns = [ path('', include(router.urls),), path('<int:pk>/create-client', views.Client_view.as_view()), path('<int:pk>/delete-client', views.Client_view .as_view()), path('auth/login/', views.LoginView.as_view()), path('auth/logout/', views.LogoutView.as_view()), ] ''' View.py ''' class Client_view(generics.ListCreateAPIView, generics.RetrieveUpdateDestroyAPIView): authentication_classes = [SessionAuthentication, BasicAuthentication, TokenAuthentication] permission_classes = [IsAuthenticated] queryset = Client.objects.all() serializer_class = ClientSerializer ''' -
how i can appear all my search result using Paginator in django?
i have added Paginator to search result in django okay ? and i put show 2 item in page and i have 8 item in page but when i do a search in website it's show 2 item okay and show to me 4 pages i can move to it but when i press on page 2 or 3 or 4 it's doesn't show anything why ? view.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidapk_database= AndroidApks.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidgames_database= AndroidGames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) antiruvs_database= Antivirus.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) systems_database= OpratingSystems.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcgames_database= PCgames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database)) paginator = Paginator(results, 2) # Show 25 rows per page page = request.GET.get('?q={{ request.GET.q }}&submit=Search') results = paginator.get_page(page) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') html file : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1> <small> Results for <b><i>{{ request.GET.q }}</i></b></small> … -
New Relic for Heroku Django App - No data Sent to the New Relic
After Installing New Relic add-on and python client on Heroku (Django app), no data sent out to new relic even after making a lot of transactions and waiting more than one hour. Can any one support by listing down the exact steps to be followed in order to setup new relic apm successfully on Heroku for dajngo app, starting from adding the add-on till checking the transaction on New Relic. Below is the result of new relic diagnostic tool: ./nrdiag Check Results Info Base/Env/CollectEnvVars [Gathered Environment variables of current shell.] Success Base/Config/Collect Success Base/Config/Validate Failure Base/Log/Copy Success Base/Config/LicenseKey Info Base/Env/HostInfo [9dc9844b-15bd-4801-8cea-b59be8adee41] Info Base/Config/RegionDetect [1 unique New Relic region(s) detected from config.] Success Base/Collector/ConnectUS Success Python/Config/Agent Info Python/Env/Version [3.7.0] Info Python/Env/Dependencies [Collected pip freeze. See pipFreeze.txt for more i...] Success Python/Requirements/Webframework Error Base/Env/InitSystem Failure Python/Requirements/PythonVersion 61 results not shown: 61 None See nrdiag-output.json for full results. Issues Found Failure - Base/Log/Copy Log File not found, please check working directory See https://docs.newrelic.com/docs/new-relic-diagnostics#run-diagnostics for more information. Error - Base/Env/InitSystem Unable to read symbolic link for /sbin/init: lstat /sbin/init: no such file or directory Failure - Python/Requirements/PythonVersion Python version is not compatible. See https://docs.newrelic.com/docs/agents/python-agent/getting-started/compatibility-requirements-python-agent#basic for more information. -
How can i get comment pk in reply form.is_valid() in same DetailView page
models.py ''' class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=120) created_date = models.DateTimeField(auto_now_add=True) approved_comment = models.BooleanField(default=False) class CommentReply(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_replay') author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) Reply = models.TextField(max_length=120) created_date = models.DateTimeField(auto_now_add=True) approved_reply = models.BooleanField(default=False) ''' #Views.py ''' elif request.method == 'POST' and 'replypost' in request.POST: print('reply form') form = ReplyForm(self.request.POST) if form.is_valid(): form.instance.author = self.request.user form.instance.post = Post.objects.get(pk=self.kwargs['pk']) form.instance.comment = Comment.objects.get(pk=self.kwargs['pk?']) form.save() return super(PostDetailView, self).form_valid(form) ''' In detailview page reply form validation fail to get instance of comment Note:In the template Under the Article having comment and reply form in the same page.Take reference of the image replay 29 takes same comment pk into the reply form validation in views.py -
Create object only if other object is successfully created
I am fairly new to Django and unfamiliar with the best practices for this situation (in any framework/language, not just python/django). The situation is that when a user first registers on my site, I want to create an "organization" for them if it doesn't exists, and then subsequently create a user for them, which references the organization. I never want to insert one without the other, but I need to create the organization first so that the organization UUID can be saved for each user. Right now, organizations will still be created even if there is an issue with the creation of the user. This is obviously a problem because then I have an organization with no users attached. I don't exactly know how to check that the user will be properly created before creating the organization, but something along these lines seems to be what I need to do. Using commit=false on the organization object creation wouldn't seem to work because I need to get the UUID. So I am not sure the best way to proceed. I am overwriting the save method in the serializer of the popular authentication package django-allauth models.py class Organization(models.Model): alphanumeric_plus_underscore = RegexValidator(r'^[\w]+$', 'Only … -
How To Fix name 'post' is not defined in django in comment
How To Fix name 'post' is not defined in django in comment when i comment in my django website then if i disapprove comment i get this error: NameError at /comment/1/remove/ name 'post' is not defined i want to reject comment but i get error please help me i'm wating for you! Here is my app Urls.py from django.urls import path,re_path from blog import views urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), path('register/',views.user_register,name='user_register'), path('post/<int:pk>',views.PostDetailView.as_view(),name='post_detail'), path('post/new/',views.CreatePostView.as_view(),name='post_new'), path('post/<int:pk>/edit/',views.PostUpdateView.as_view(),name='post_edit'), path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'), path('drafts/',views.PostDraftListView.as_view(),name='post_draft_list'), re_path('^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'), path('comment/<int:pk>/approve/',views.comment_approve,name='comment_approve'), path('comment/<int:pk>/remove/',views.comment_remove,name='comment_remove'), path('post/<int:pk>/publish/',views.post_publish,name='post_publish'), ] Here is my views.py from django.shortcuts import render , get_object_or_404,redirect from django.utils import timezone from blog.models import * from blog.forms import * from django.contrib.auth.decorators import login_required from django.urls import reverse_lazy from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here.\ #...................... ########################## ########################## @login_required def post_publish(request,pk): post = get_object_or_404(Post,pk=pk) post.publish() return redirect('post_detail',pk=pk) @login_required def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail',pk=post.pk) else: form = CommentForm() return render(request,'blog/comment_form.html',{'form':form}) @login_required def comment_approve(request,pk): comment = get_object_or_404(Comment,pk=pk) comment.approve() return redirect('post_detail',pk=comment.post.pk) @login_required def comment_remove(request,pk): comment = get_object_or_404(Comment,pk=pk) post_pk = comment.post.pk comment.delete() return redirect('post_detail',pk=post.pk) Here is my Models.py class Comment(models.Model): post … -
Is there any method or procedure to prevent jQuery to apply all the same classes except current class?
I have situation to apply some jQuery to current class which should not apply to remaining classes of having same name. I want to apply jQuery code to apply to first "img_click" div but not to next "img_click" Please find example code below: <div> <div class="img_click"> <img src="image1.jpg" /> </div> <div class="info"> <h2>Image Heading</h2> <div>Posted on..</div> </div> </div> <div> <div class="img_click"> <img src="image2.jpg" /> </div> <div class="info"> <h2>Image Heading</h2> <div>Posted on..</div> </div> </div> -
Should i be using my views.py do load data instead of Jquery/Ajax?
I am working on a Django based webapp where i pull some JSON data from an external api into a html bootstrap modal. From there I do some calculations on the data and select certain entries, change their html class etc. Currently i am using an Ajax get request to retrieve the data and then straight javascript to show it in the modal and do the class changes and calculations. I am thinking that it might be better to do this from my Django views.py file instead What i have done so far Ajax Get Call $.ajax({ cache: false, method: 'GET', url: url, success: function(data){ console.log(data) console.log("success") showTable(data) $('#total').text(doSum(".price>span")) }, error: function(error_data){ console.log("error") } }) Showing the Data in a table in the modal function showTable(data) { $("#food_table tbody").html('<tr class="contentRow">' +data.map(v=>'<td>'+v.pk+'</td><td>' +v.Description+'</td><td class="price">R<span>' +v.Price+'</span></td></tr>' ).join('')); } My Bootstrap Modal and Table <div id="firstModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="firstModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="firstModalLabel">Table 1</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="container"> <div class="table-responsive"> <table class="table table table-borderless" id="food_table"> <thead> <tr> <th>#</th> <th>Description</th> <th>Price</th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> <div class="modal-footer"> <div class="container"> <div><h3 class="h3total">You Owe: … -
How to create individual views for individual category in django
i m working on resturent management system in django and I have categories like pizza, chowmin, dumplings, etc. And i want individual list of food items related with its category, whenever i clicked on the for example in pizza then it must show only the list of pizzas that are stored in database like, pizza : chicken pizza cheese pizza,etc in a new page with separated view for each category please help me with this thank u -
How can I fill up a form field from views.py in Django?
I am using a function to record the time between which the page is loaded and the user submits the data. In that form, I have created a hidden field so that the admin can see it. However, I am unable to implement my idea since I don't understand how I can submit the time to the form from views.py. If someone can suggest an easier and simpler alternative methods to achieve what I am trying to do, that would be very helpful to me as well. My code is as follows. models.py class Responses(models.Model): question1 = models.TextField() question2 = models.TextField() question3 = models.TextField() timespent1 = models.TextField() forms.py class Question1Form(forms.ModelForm): question1 = forms.CharField() timespent1 = forms.TimeField(widget=forms.HiddenInput()) class Meta: model = Responses fields = ('question1','timespent1') views.py def qone(request): if request.method =="GET": starttime = my_timer() elif request.method == "POST": form = Question1Form(request.POST) if form.is_valid(): endtime = my_timer() timespentstr = '{0} seconds'.format(endtime-starttime) #Do something to set timespent1 field = timespentstr here form = form.save() else: form = Question1Form return render(request,'question1.html',{'form':form}) -
How to fix 'str' object is not callable in django
Hi Everyone I made A Blog but when i delete post i get this error i'm using django latest version: TypeError at /post/(?P3\d+)/remove/ 'str' object is not callable' Here Is My Views.py class PostDeleteView(LoginRequiredMixin,DeleteView): success_url = reverse_lazy('post_list') model = Post Here is my app Urls.py from django.urls import path from blog import views urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), path('register/',views.user_register,name='user_register'), path('post/(?P<pk>\d+)',views.PostDetailView.as_view(),name='post_detail'), path('post/new/',views.CreatePostView.as_view(),name='post_new'), path('post/(?P<pk>\d+)/edit/',views.PostUpdateView.as_view(),name='post_edit'), This line i think error is path('post/(?P<pk>\d+)/remove/',views.PostDeleteView.as_view(),name='post_remove'), path('drafts/',views.PostDraftListView.as_view(),name='post_draft_list'), path('post/(?P<pk>\d+)/comment/',views.add_comment_to_post,name='add_comment_to_post'), path('comment/(?P<pk>\d+)/approve/',views.comment_approve,name='comment_approve'), path('comment/(?P<pk>\d+)/remove/',views.comment_remove,name='comment_remove'), path('post/(?P<pk>\d+)/publish/',views.post_publish,name='post_publish'), ] -
replacing django_background_task with APScheduler in Django?
Now I made code that removes temp folder after 5 seconds when users download the file with django_background_task library. I have to replace it with APScheduler library because heroku only supports APScheduler. But I have no idea how to schedule jobs that runs after 5 seconds when I call it. Here is the code. @background(schedule=5) def task_delete_zipfile(filePath): if os.path.exists(filePath): shutil.rmtree(filePath) logging.info("successfully deleted") else: logging.info("unable to delete") zipdir = condown(idx)#returns directory after creating the temp directory if os.path.exists(zipdir): with open(zipdir, 'rb') as fh: response = HttpResponse(fh.read(), content_type="multipart/form-data") response['Content-Disposition'] = 'inline; filename*=UTF-8\'\'%s' % urllib.parse.quote(os.path.basename(zipdir).encode('utf-8')) task_delete_zipfile(os.path.dirname(zipdir)) return response raise Http404 Thanks in advance! -
How to load a comment form in DetailView?
I was able to load the comments that were added through the admin page but I am not able to make a form in the DetailView itself I have tried adding a form in the detailview template but I still don't see the form in the site #views.py class MessageDetailView(DetailView): model = Message template_name = "messaging/detail.html" #queryset = Message.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(message=self.object) return context #detail.html <form method="POST"> {% csrf_token %} <h3>Write a New Comment</h3> <div class="messagebox"> {{ form|crispy }} <button class="btn" type="submit"> Post Comment </button> </div> </form> #forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ("comment") #models.py class Comment(models.Model): message = models.ForeignKey(Message,on_delete=models.CASCADE) comment = models.TextField(max_length=50) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return "Comment on {}".format(str(self.date_posted)) The comments loaded in the site, but the form didn't load, any way to solve this problem? Please provide some code in the answer instead of just linking me to a documentary. -
How to write correct test with pytest-django?
I am getting started with pytest. I try test my ListView with predefined data, but response.context_data['object_list'] is empty. What wrong? This is my code: from http import HTTPStatus from django.test import RequestFactory from django.urls import reverse_lazy from mixer.backend.django import mixer import pytest from career.constants import THREE_FIVE_YEARS from career.constants import WITHOUT_EXPERIENCE from career.models import Employment from career.models import Schedule from career.models import Vacancy from career.views import VacancyList pytestmark = pytest.mark.django_db(transaction=True) class TestVacancyView: """Testing vacancy views.""" list_url = 'vacancy_list' list_path = reverse_lazy(list_url) factory = RequestFactory() def test_list_get(self, client): first_schedule = Schedule.objects.first() last_schedule = Schedule.objects.last() employment_first = Employment.objects.first() employment_last = Employment.objects.last() mixer.blend( Vacancy, city='New York', salary_max=30000, experience=WITHOUT_EXPERIENCE, schedule=first_schedule, employment=employment_first ) mixer.blend( Vacancy, city='London', salary_max=40000, experience=THREE_FIVE_YEARS, schedule=first_schedule, employment=employment_first ) mixer.blend( Vacancy, city='New York', salary_max=50000, experience=THREE_FIVE_YEARS, schedule=last_schedule, employment=employment_last ) request = self.factory.get(self.list_path) response = VacancyList.as_view()(request) assert response.context_data['object_list'].count() == 3 I expected 3 records in database, but the actual output is 2. -
Django - Adding a part of a string onto a new line not working correctly
In my Django project, If the user makes a mistake when signing up, then an error is sent to my template and then displayed. Some of my error messages I send to the user are a bit lengthy, and therefore I want to start a new line within the text. I attempt to add \n within my text, however a new line isn't started. Here's my code: views.py: return render(request, 'users/signup.html', {'error': 'Username field must be \n a minimum of 5 characters'}) signup.html: {% if error %} <span class="errorspansignup"> {{ error }} </span> {% endif %} The text I pass as error stays all on one line. Does anybody know what the issue is? Thank you. -
Error occured in django when i run a command `python manage.py runserver`.after i changed python version
everyone here in stackoverflow. I had successfully completed few django projects few month ago. Now, due to some reason i changed the python version. And when i try to run old django projects it throws the error like following (myDjangoEnv) E:\django_project\thirdpolehandicraft\myDjangoEnv\thirdpolehandicraft>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "E:\django_project\thirdpolehandicraft\myDjangoEnv\lib\site-packages\django\__init__.py", line 1, in <module> from django.utils.version import get_version File "E:\django_project\thirdpolehandicraft\myDjangoEnv\lib\site-packages\django\utils\version.py", line 1, in <module> import datetime ModuleNotFoundError: No module named 'datetime' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Actually when i create new project and run it works fine. But when i activate old virtualenv and try to run the server then above error occurs. Even I did python uninstall completely and installed fresh python again but did'nt work for me. Any body know how to solve this? Thanks in advance! -
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\...\\AppData\\Local\\Temp\\tmp24xoaa7g'
I am having a weird problem with tests regarding testing with temporary images and compressing images in models.py and I've been stuck for about 7 hours now. There seems to be a problem with permissions: ERROR: test_has_light_images (realestate.tests.test_view_listing.RealestateListingViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Storm\Envs\btre\lib\site-packages\django\test\utils.py", line 373, in inner return func(*args, **kwargs) File "C:\Users\Storm\Dev\btre_project\realestate\tests\test_view_listing.py", line 72, in test_has_light_images create_listing(title='listing_sample', address='sample', realtor_num=1, city='sample', state='sample', zipcode='1234', price='555555', bedrooms='1', bathrooms='1', garage='1', sqft='123', lot_size='123', image_sample=image_sample.name) File "C:\Users\Storm\Dev\btre_project\realestate\tests\test_view_listing.py", line 37, in create_listing return Listing.objects.create(title=title, address=address, realtor=realtor, city=city, state=state, zipcode=zipcode, price=price, bedrooms=bedrooms, bathrooms=bathrooms, garage=garage, sqft=sqft, lot_size=lot_size, photo_main=image_sample, photo_1=image_sample, photo_2=image_sample, photo_3=image_sample, photo_4=image_sample, photo_5=image_sample, photo_6=image_sample) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\db\models\query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "C:\Users\Storm\Dev\btre_project\realestate\models.py", line 69, in save new_image = compress(self.photo_main) File "C:\Users\Storm\Dev\btre_project\realestate\models.py", line 11, in compress im = Image.open(image) File "C:\Users\Storm\Envs\btre\lib\site-packages\PIL\Image.py", line 2774, in open fp.seek(0) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\core\files\utils.py", line 20, in <lambda> seek = property(lambda self: self.file.seek) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\db\models\fields\files.py", line 43, in _get_file self._file = self.storage.open(self.name, 'rb') File "C:\Users\Storm\Envs\btre\lib\site-packages\django\core\files\storage.py", line 36, in open return self._open(name, mode) File "C:\Users\Storm\Envs\btre\lib\site-packages\django\core\files\storage.py", line 224, in _open return File(open(self.path(name), mode)) PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Storm\\AppData\\Local\\Temp\\tmp24xoaa7g' test.py from django.test import TestCase from django.urls import reverse, resolve from django.utils import timezone … -
django 'set' object is not reversible
When I use the passed parameters, I always report an error, but If change this { % url , this error will be gone. please help me solve the problem. views.py is: def mmmm(request): return render(request, 'test3.html') def gettime(request, year, day, month): return HttpResponse("time is %s-%s-%s" % (year, month, day)) urls.py is: app_name = "four" urlpatterns = [ re_path(r'mmmm', views.mmmm, name='mmmm'), re_path(r'gettime/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', views.gettime, name='gettime'), ] test2.html is: <a href="{% url 'mmmm' %}">mmmmm</a><br> <a href="{% url 'gettime' year=2019 month=12 day=18 %}">cmdb/userinfo/tom/tomnickname/10</a><br> this error is : Error during template rendering In template /Users/jumporange/PycharmProjects/HelloDjango/templates/test2.html, error at line 15 'set' object is not reversible 5 <title>Get student</title> 6 </head> 7 <body> 8 <ul>{% for student in students %} 9 <li>{{ student.s_name }}</li> 10 {% endfor %} 11 </ul> 12 {#<a href="/FOUR/index">mmm</a>#} 13 14 {#<a href="{% url 'mmmm' %}">mmmmm</a><br>#} 15 <a href="{% url 'gettime' year=2019 month=12 day=18 %}">cmdb/userinfo/tom/tomnickname/10</a><br> 16 </body> 17 </html> -
can retrieve data from a search feature in my django project
i don't know what exactly the isssue is but in my blood bank management when ever i search for o postive and the desired location i'll get the result but when i tried to retrieve Ab positive blood group with a particular location it says there is no particular donor to that given location even though there is a data with that given location views.py def detail(request): blood_type = request.POST['blood_group'] city = str(request.POST['city']).capitalize() for i in DonarDetail.objects.all(): i.refresh() i.save() list2 = DonarDetail.objects.all().filter( blood_group=blood_type, city=city, number_month=-1, ) | DonarDetail.objects.all().filter( blood_group=blood_type, city=city, number_month__gt=2, ) number = len(list2) print(number) if number > 0: return render(request, 'login/details.html', {'list': list2, 'number': number}) else: error = 1 return render(request, 'login/check.html', {'error': error}) models.py class DonarDetail(models.Model): Male = 'Male' Female = 'Female' choice = (('Male', 'Male'), ('Female', 'Female'), ) choice1 = (('O Positive', 'O Positive'), ('O Negative', 'O Negative'), ('A Positive', 'A Positive'), ('A Negative', 'A Negative'), ('B Positive', 'B Positive'), ('B Negative', 'B Negative'), ('AB Negative', 'AB Negative'), ('AB Positive', 'AB Positive'), ) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20, blank=True) name = models.CharField(max_length=50, default=' ') id_no = models.CharField(max_length=20, unique=True) gender = models.CharField(max_length=20, choices=choice, default='Male') age = models.IntegerField(validators=[MinValueValidator(18)]) blood_group = models.CharField(max_length=20, choices=choice1, default='O Positive') email = models.EmailField(blank=True) … -
Password Reset issue with Django 2.2.5
I am trying to figure out an issue I'm having with what happens after submitting the password reset form supplied by django.contrib.auth.urls. When hitting the button to request the submit button an email is sent properly to the email associated with the user account, but a 505 error page is displayed. In looking at the error log the error given is: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. In myproject/urls.py I have the following line as part of the urlspattern: path('accounts/', include('accounts.urls', namespace = 'accounts')) In accounts/urls.py I have the following lines as part of the urlspattern: path('', include('django.contrib.auth.urls')) I think the issue is with django attempting to use the equivalent of url 'password_reset_done' instead of url 'accounts:password_reset_done'. Any help in tracking this down would be appreciated. -
I have a problem to run the manage.py with runserver_plus, the error is in the sintaxis in ```from exc```
my proble is in the manage.py when i try to run the sudo python manage.py runserver_plus --cert-file i serch a similar problems, but i can solve the problem this is the code of manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'necesitoayuda.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
Pulling several Django models together into a single list
I have a database with four related tables: project, unit, unit_equipment, and equipment. A project can have many units; a unit can have many related equipment entries. A single unit can only belong to one project, but there is a many-to-many between equipment and unit (hence the unit_equipment bridge table in the DB). I'm using Django and trying to create a view (or a list?) that shows all 3 models on the same page, together. So it would list all projects, all units, and all equipment. Ideally, the display would be like this: Project --------- Unit ------------- Equipment Project 1 first_unit some_equipment1, some_equipment2 Project 1 second_unit more_equipment1, more_equipment2 Project 2 another_unit some_equipment1, more_equipment1 Project 2 and_another_unit some_equipment2, more_equipment2 but at this point I'd also be happy with just having a separate line for each piece of equipment, if comma-separating them is a pain. I am very new to Django, and although it seems straightforward to create a form where I can add a new project, and add related unit and equipment data (using the TabularInline class), I cannot for the life of me figure out how to bring this data together and just display it. I just want a "master … -
Checking a value of single cell on uploaded excel file on Django via openpyxl
I am currently taking an excel file as an input from Django. From the uploaded excel, I would like to check a value in one cell and decide on what to do with the entire workbook. But my syntax for load_workbook must be wrong as I am getting 'stat: path should be string, bytes, os.PathLike or integer, not UploadFileForm' What would be the simplest way to interpret the uploaded file as an excel file and check a value of the single cell? From the upload function, if self.request.method == 'POST': form = UploadFileForm(self.request.POST, self.request.FILES) if form.is_valid(): # edit workbook = load_workbook(filename=form, read_only=True) uploadable(workbook) I cannot change the part above the edit tag as it is being used by many different working functions. The snippet of the uploadable function: def uploadable(wb = None): firstws = wb[0] if firstws['X1'] == 1: return render_to_response('check/wrongfile.html') -
Server Error (500) | Django + Nginx & Gunicorn. No Nginx error log or Django debug output
Here is my settings.py: """ Django settings for real_estate_platform project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'listings', 'django_cleanup', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'real_estate_platform.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'real_estate_platform.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'dbuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '' } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] … -
Is it possible to fill a form in a test?
I want to test a form. It is working, but the test doesn't. One field of this form is popolated by a javascript function. I can use selenium to do so, but I don't want because it's giving problems and also I want isolate the test. So I'm calling the form in my test, then I'm creating the choices (this is what javascript should do), then I'm setting the fields values. My models.py: class Name(models.Model): name = models.CharField(_('nome'), max_length=50, default='') namelanguage = models.ForeignKey( NameLanguage, related_name='%(app_label)s_%(class)s_language', verbose_name=_('linguaggio'), on_delete=models.PROTECT) nametype = models.ForeignKey( NameType, related_name='%(app_label)s_%(class)s_tipo', verbose_name=_('tipo'), on_delete=models.PROTECT) gender = models.ForeignKey( Gender, related_name='%(app_label)s_%(class)s_gender', verbose_name=_('sesso'), on_delete=models.PROTECT, blank=True, null=True) usato = models.PositiveSmallIntegerField(_('usato'), default=0) approved = models.BooleanField(null=True, blank=True, default=False) def save(self, *args, **kwargs): self.name = format_for_save_name(self.name) to_save = check_gender_name(self) if not to_save: return else: super(Name, self).save(*args, **kwargs) def format_for_save_name(name): myname = name.lower().strip() if myname[0] not in "abcdefghijklmnopqrstuvwxyz#": myname = '#' + myname return myname My form.py: class NameForm(forms.ModelForm): class Meta: model = Name fields = ['namelanguage', 'nametype', 'gender', 'name', 'usato', 'approved'] widgets = { 'gender': forms.RadioSelect(), 'usato': forms.HiddenInput(), 'approved': forms.HiddenInput(), } My test_form.py: def test_form_validation(self): maschio = Gender.objects.create(name_en='Male', name_it='Maschio') nome = NameType.objects.create(name_en='Name', name_it='Nome') romani = NameLanguage.objects.create( name_en='Romans', name_it='Romani') romani.sintassi.add(nome) form = NameForm() form.fields['nametype'].disabled = False form.fields['nametype'].choices = …