Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, django, html: I made a booking form and I would like to set this page to login access only without inheriting 'LoginRequiredMixin'
In other words, user can not access this booking_form.html without login. <a href="/booking_form/">Booking</a> or <button onclick="location.href='/booking_form/'">Booking</button> If user hit the button, then they need to login first to access that page. if login successfully, then they would be on the page of booking_form automatically This one has to be done without inheriting 'LoginRequiredMixin'... -
how to show total number of rows on top of table (template) in Django
I'm using Djnago as backend, PostgresSQL as DB and HTML, CSS, Javascript as frontend. I want to show number of rows count on the top of the bootstrap table. Just Like this Here is my code views.py def product(request): product = Product.objects.all() page = request.GET.get('page', 1) paginator = Paginator(product, 25) try: product = paginator.page(page) except PageNotAnInteger: product = Paginator.page(1) except EmptyPage: product = Paginator.page(paginator.num_pages) return render(request, 'product.html', {'product': product}) product.html <h4> {{}} Compatible Products</h4> <- want to show here -
How to check object level permission efficiently in DRF?
Scenario: In DRF I had to write following lines of code to check permission for the user class RetrieveCampaignListView(APIView) : authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get(self, request , *args, **kwargs): if request.user.has_perm('campaign.view_campaign'): try: #some view code except: return Response({"status":False}, status=status.HTTP_404_NOT_FOUND) else: return Response({"status":"Sorry User is not permitted"}) But I want to shorten the request.user.has_perm('campaign.view_camapign') and it's else condition into something like this. @check_permission('campaign.view_campaign') Any Help Would be highly appericiated. -
Any change to the customized Django User Model is completely ignored in the Admin
I customized the User model by extending AbstractUser, not AbstractBaseUser, because I don't need to remove the username, I just need to authenticate users by email and I still want to use the authentication system that comes with Django. Therefore I just defined the email address as the username and I extended AbstractUser before any migration. But the Admin doesn't recognize this and completely ignores what I specify in admin.py, except the register instruction. Here's the content of my admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import User as CustomUser from .forms import UserChangeForm, UserCreationForm # from django.utils.translation import ugettext_lazy as _ # I obviously tried by extending UserAdmin too, no result class CustomUserAdmin(admin.ModelAdmin): add_form = UserCreationForm form = UserChangeForm model = CustomUser fields = ('email') # commenting or uncommenting the following doesn't change anything """ list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) exclude = ('first_name',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) """ admin.site.register(CustomUser, BaseUserAdmin) I tried everything and nothing works. I can't add … -
django-import-export Export specified field data
My project is separated from the front and back ends. The current requirement is for the front end to pass the specified fields to me. I export data to excel through django-import-export. How can this be achieved? -
I am trying to set up a virtual environment on Windows 10 so I can run Python and Django. What do I need to do?
I am reading a book on Python. It said to set up a directory "learning log" and then on the command line enter "learning_log$ python -m venv ll_env" which I did, and got an error "learning_log$ is not recognized as an internal or external command, operable program, or batch file". What do I need to do that I have not done? Thanks for any help. -
Django error when creating superuser django.db.utils.OperationalError: no such table: auth_user
I am pretty new to django. All of a sudden I ran into this error when trying to create a superuser from windows command prompt using python manage.py createsuperuser When I enter it, I get this error django.db.utils.OperationalError: no such table: auth_user I created a brand new virtual environment and project but I keep getting this issue. Has anyone seen this before? -
Django create or update from list to model
Newbie's problems here: This is my model: class ring(models.Model): size= models.DecimalField(verbose_name='Ring Size', default=0, max_digits=5, decimal_places=1) the existing data are: [2.2, 2.5, 3.0, 3.2, 4.2, 4.5, 4.8, 5.5, 5.8, 6.0] user edited the initial data from template and generate these: [2.1, 2.5, 3.0, 3.2, 4.2, 4.5, 4.8, 5.5, 5.7, 6.1, 6.5, 7.5, 8.0, 9.0, 11.0, 13.0, 15.0, 16.0] I want to do this: If those numbers are not existed, create a new one. If user update the number lets say from 2.2 to 2.1 , 5.8 to 5.7 then just update the existing. What is the best way to achieve this ? Thanks in advanced -
I get in django Page not found
I have a problem with my Django project so I tried to fix but I couldn't and when I go to localhost, I just get a page not found. this is the URL. from django.urls import path from . import views app_name="carro" urlpatterns = [ path("agregar/<int:producto_id>/", views.agregar_producto, name="agregar"), path("eliminar/<int:producto_id>/", views.eliminar_producto, name="eliminar"), path("restar/<int:producto_id>/", views.restar_producto, name="restar"), path("limpiar/", views.limpiar_carro, name="limpiar"), ] this is another page called widget on this page I redirect to other colled shop. <table class="table table-bordered" style="color: white;"> <thead> <tr> <th colspan="3" class="text-center"> Carro compras </th> </tr> <tr> <th>Producto</th> <th>Cantidad</th> <th>Suma</th> </tr> </thead> <tbody> {%if request.session.carro.items%} {%for key, value in request.session.carro.items%} <tr class="text-center"> <td>{{value.nombre}}</td> <td>{{value.cantidad}}</td> <td> <a href="{%url 'carro:agregar' value.producto_id%}" class="btn btn-sm btn-success">+</a> <a href="{%url 'carro:restar' value.producto_id%}" class="btn btn-sm btn-success">-</a><br> {{value.precio}} $ </td> </tr> {%endfor%} {%else%} <tr> <td colspan="3"> <div class="alert-danger text-center">Sin Productos</div> </td> </tr> {%endif%} </tbody> <tfoot> <td colspan="3"> Total:{{importe_total_carro}} $ </td> </tfoot> That's my incovenient -
Stripe subscription cancel: KeyError 'HTTP_STRIPE_SIGNATURE'
I'm trying to configure Django Stripe Subscriptions for WebApp. I want to let Subscribed users cancel the subscription themselves. The code below is to delete user's information from StripeAPI and Django StripeCustomer model. Here is view.py import stripe from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http.response import JsonResponse, HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import get_user_model from subscriptions.models import StripeCustomer @login_required @csrf_exempt def cancel_subscription(request): if request.user.is_authenticated: endpoint_secret = settings.STRIPE_ENDPOINT_SECRET payload = request.body event = None sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) session = event['data']['object'] stripe_customer = StripeCustomer.objects.get(user=request.user) stripe.api_key = settings.STRIPE_SECRET_KEY sub_id = stripe.Subscription.retrieve(stripe_customer.stripeSubscriptionId) client_reference_id = session.get('client_reference_id') user = get_user_model().objects.get(id=client_reference_id) try: #delete from stripeapi stripe.Subscription.delete(sub_id) #delete from StripeCustomer model StripeCustomer.objects.delete( user=user, stripeCustomerId=stripe_customer_id, stripeSubscriptionId=stripe_subscription_id, ) print(user.username + ' unsubscribed.') except Exception as e: import traceback traceback.print_exc() return JsonResponse({'error': (e.args[0])}, status =403) return render(request, 'home.html') When I excecute the code error occuerd at sig_header = request.META['HTTP_STRIPE_SIGNATURE'] The error message is below Exception Type: keyError Exception Value: 'HTTP_STRIPE_SIGNATURE' I don't understand why the error occurs at request.META['HTTP_STRIPE_SIGNATURE'],because other part of this view can execute this code. I just mentioned the above settings in this question but still if more … -
URL not matching url pattern in Django
I'm trying to learn Django, went through the official tutorial and giving it a try on my own. I've created a new app and can access the index page but I can't use pattern matching to go to any other page. Here is my monthlyreport/url.py from django.urls import path from . import views #app_name = 'monthlyreport' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), ] and my monthlyreport/views from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.contrib.auth.mixins import LoginRequiredMixin from django.views import generic from .models import Report def index(request): report_list = Report.objects.all()[:5] template = loader.get_template('monthlyreport/index.html') context = { 'report_list': report_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) The debug for http://127.0.0.1:8000/monthlyreport/0 is showing Using the URLconf defined in maxhelp.urls, Django tried these URL patterns, in this order: monthlyreport [name='index'] monthlyreport <int:question_id>/ [name='detail'] polls/ admin/ accounts/ The current path, monthlyreport/0, didn’t match any of these. Again, using http://127.0.0.1:8000/monthlyreport/ to go to index works fine, but I cant match the integer. I would really appreciate any suggestions, I am very, very confused at this point. -
Django whitespace from textarea into a list of dictionary
I hope someone here can help me out of this. I have a request.POST from textarea, for example: <QueryDict: {'Animal':['Fish Dog Cat Bird']}> I want to convert to something like this: {'Animal': ['Fish', 'Dog', 'Cat', 'Bird']} Thanks in advanced -
How can I change my python path permanently?
I recently just installed Inkscape to my Windows 10 computer, and it changed my python path. C:\Users\Chinyere\Documents\Django Files\Commercial>python Python 3.8.9 (default, Apr 13 2021, 15:54:59) [GCC 10.2.0 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print(sys.path) ['', 'C:\\Program Files\\Inkscape\\lib\\python38.zip', 'C:\\Program Files\\Inkscape\\lib\\python3.8', 'C:\\Program Files\\Inkscape\\lib\\python3.8\\lib-dynload', 'C:\\Program Files\\Inkscape\\lib\\python3.8\\site-packages'] I can't run my Django files. When I try, it pops-up error C:\Users\Chinyere\Documents\Django Files\Commercial>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 12, in main raise ImportError( 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? Please, how can I change it to the default python path without uninstalling Inkscape. -
Submitting a new records via form to my django database
I am trying to create new objects in my database and if all goes well send the user to a table where all records are being posted, but for some reason the form is seems to be submitting successfully but no new records are being added to my database. Here are my codes: models.py: from django.db import models class clearance(models.Model): vessel_imo = models.ForeignKey(vessel, on_delete=models.PROTECT) vessel_name = models.CharField(max_length=30,blank=True,) email = models.EmailField(default='john@doe.com') location = models.CharField(default='PACCT',max_length=30,choices=LIST_OF_PORTS) clearance_file1 = models.FileField() status = models.CharField(max_length=20,choices=CLEARANCE_STATUS,default='PENDING') requestdate = models.DateTimeField(default=timezone.now,auto_created=True,editable=False) def __str__(self): return self.vessel_name class Meta: ordering = ['-id'] form.py: from django.forms import ModelForm from . models import clearance, vessel class ClearanceForm(ModelForm): class Meta: model = clearance fields = '__all__' views.py: def new(request): form = ClearanceForm(request.POST) if form.is_valid(): form.save() return render(request,'new.html',{'form':form}) new.html: {% extends 'dashboard.html' %} {% block title %} <h2> REQUEST FOR CLEARANCE</h2> {% endblock title %} {% block content %} <form action="pendings.html" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock content %} What I am trying to get is the user to add a new records in the database and be sent to the dashboard.html where he can see all records including the just added. -
how to break lines for a value from database
i want to break line between command and result : outputs.append(output) outputs.append(request.POST.get("cmds")) device.config = outputs device.save() i added the value 'outputs' in device.config and this is my template i use {{device.config|linebreaksbr}} but this is the result -
How do i integrate my create new post url ,with detail view and list view so that users can create new post on the same page like that of facebook
What am trying to accomplish is for users to be able to create post and add pictures as on Facebook, but somehow in Django am having a challenge with that, create post has to be on a separate URL as detail and list view has separate URLs how do I integrate all of the URL to be on one template, so that very post works on one page like that of Facebook. here is my views... class PostListView(ListView): model = Post template_name = 'feed/feed.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: liked = [i for i in Post.objects.all() if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked return context class UserPostListView(LoginRequiredMixin, ListView): model = Post template_name = 'feed/feed.html' context_object_name = 'posts' paginate_by = 10 def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username.get_full_name')) liked = [i for i in Post.objects.filter(user_name=user) if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked return context def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username.get_full_name')) return Post.objects.filter(user_name=user).order_by('-date_posted') @login_required def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) user = request.user comments = post.comments.filter() is_liked = Like.objects.filter(user=user, post=post) new_comment = None if request.method == 'POST': comment_form = NewCommentForm(request.POST) if form.is_valid(): … -
Proper way of inputting questions in a quiz web application
I am trying to build a quiz web application in Django and React. Each time user takes a quiz, questions are randomly picked from a list of thousand questions. Without doing it manually, what could be the proper way of inputting the questions? -
Django How To initialize an Instance of Class Only Once using for all requests?
I'm just a beginner. I have a custom Package Module, so for now every time users request to the Server It takes like 30 seconds to initialize(load data for the Class) and then do the actual work. Is there any so I can only initialize only one Instance of this Module and using for all requests from users? I tried to follow a few ways but no hope Thanks in advance, By the way, I deployed it on Ec2 with Nginx Gunicorn. Django - execute code at start-up. Django: Run a script right after runserver -
Get a single value from user database django
im new on django, and i want to get a single value from a queryset, te query would be something like this: select last_task from User where user_id=1 I tried with values() and only() but it doesnt work. worker = request.user Worker.objects.filter(user=worker.id).values("last_board") values() return me a dictionary and i cant extract the single value from it to use. -
Django template language "If" statement with many "and"
Basically i want to add a class to a div based on whether some variables have content or not. This is the If statement: <div class="search__container {% if images == true and blogs != True and parks != True %} only-images {% elif blogs == true and images != True and parks != True %} only-blog {% elif parks == true and blogs != True and images != True %} only-parks {% elif parks == true and blogs == true and images != True %} only-parks-blogs {% elif parks == true and images == true and blogs != True %} only-parks-images {% elif images == true and blogs == true and parks != True %} only-images-blogs {% endif %}" > This way it's not adding any class under any circumstances. If instead i remove the == and replace the != with is not it'll always take the first if as True and add the class only-images -
Dúvida sobre Django Queryset
Gostaria de saber se alguém consegue me ajudar na seguinte questão: last = Jogos.objects.all().filter(concurso = 2248) Nesse código acima a variável fica com o valor <QuerySet [<Jogos: 2248>]> porém eu gostaria de imprimir não isso e sim os valores do concurso 2248, o que estou fazendo errado ? -
How to add missing Months in Django Python List of Dictionary
<QuerySet [{'month': datetime.datetime(2021, 4, 1, 0, 0, tzinfo=), 'total': 1}, {'month': datetime.datetime(2021, 6, 1, 0, 0, tzinfo=), 'total': 1}]> How to add Missing Month of May (5) in which 'total' is equal to Zero in above? -
How to pass 'pk' to class-based view
This is my urls.py: urlpatterns = [ path('<int:pk>/', views.PortfolioDetailView.as_view(), name='index'), ] And my views.py: class PortfolioDetailView(DetailView): queryset = Project.objects.get(pk=pk) template_name = 'portfolio/index.html' context_object_name = 'projects' I'm obviously missing something (and I'm sure it's a silly one) because I get error: queryset = Project.objects.get(pk=pk) NameError: name 'pk' is not defined What is it? -
ImportError at / cannot import name 'register_new_org_view' from 'users.views' (/home/ubuntu/xyz/users/views.py)
I am having trouble with my gunicorn, nginx deployed django application. Everything runs smoothly on my local development and python manage.py check does not throw any errors. However, as soon as I deploy my application to my server this error is thrown:ImportError at / cannot import name 'register_new_org_view' from 'users.views' (/home/ubuntu/xyz/users/views.py) I have defined the view and import it correctly... other views from other apps are working perfectly fine... what can be the reason? Thank you so much for your help! -
Django - ModuleNotFound
Currently trying to implement a script within a Django application, however I am getting a module not found error when trying to execute the Django app. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line …