Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why the users are automatically added to likes field in many to many relation
enter image description here enter image description here -
how do i get the sum of my marks in django
@require_http_methods(["POST"]) @login_required def edit_question_parts(request): req = json.loads(request.body) question_id=req["question_id"] part_id= req["part_id"] part_desc = req["part_desc"] part_total_marks = req["part_total_marks"] total_mark = sum([part_total_marks]) #this is wrong models.Questions.objects.filter(pk=question_id).update( qn_total_mark=total_mark, updated_by=request.user.username, ) models.QuestionsPart.objects.filter(part_id=part_id).update( part_desc=part_desc, part_total_marks=part_total_marks ) return success({"res": True}) in my code above what i am trying to get the sum of all the part total marks and update it into questions table above however i am not sure how to get the sum of all the part total marks as i keep getting TypeError: unsupported operand type(s) for +: 'int' and 'str' -
Django - Certain Static Files not loading?
Repo: https://github.com/CmOliveros/encore-v1 Hi all, I may just be too tired to think right now, but in my _Base.html file in my root templates folder, I can load my index.css file, but I can't load my style.css file. They're in the same folder, and I've confirmed that all my static files are collected, but only the index.css file in my "djangoReact1/static/css/style.css" will load. Am I completely missing something here? -
when i am add post then add but not show in dashboard it is show only home page . Post is not add for current user what can i do
when i am add post then add but not show in dashboard it is show only home page . Post is not add for current user . how to add post for current user Post class in Models.py class Post(models.Model): title = models.CharField(max_length=100) decs = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('author-detail', kwargs={'pk': self.pk}) def __str__(self): return self.title + '|' + str(self.user) DASHBOARD code in viwes def dashboard(request): if request.user.is_authenticated: current_user = request.user posts = Post.objects.filter(user=current_user) else: redirect('/login/') return render( request, "dashboard.html", {'posts':posts} ) dashboard HTML Code <h3 class="my-5">Dashboard </h3> <a href="{% url 'addpost' %}" class="btn btn-success">Add Post</a> <h4 class="text-center alert alert-info mt-3">Show Post Information</h4> {% if posts %} <table class="table table-hover bg white"> <thead> <tr class="text-center"> <th scope="col" style="width: 2%;">ID</th> <th scope="col" style="width: 25%;">Title</th> <th scope="col" style="width: 55%;">Description</th> <th scope="col" style="width: 25%;">Action</th> </tr> </thead> <tbody> {% for post in posts %} {% if post.user == request.user%} <tr> <td scope="row">{{post.id}}</td> <td>{{post.title}}</td> <td>{{post.decs}}</td> <td class="text-center"> <a href="{% url 'updatepost' post.id %}" class="btn btn-warning btn-sm">Edit</a> <form action="{% url 'deletepost' post.id %}" method="post" class="d-inline"> {% csrf_token %} <input type="submit" class = "btn btn-danger btn-sm" value="Delete"> </form> </td> </tr> {% endif %} {% endfor %} </tbody> </table> {% else %} <h4 … -
trying to upload a file to django server with post request from spring webClient
I am trying to upload a file to django server with post request from spring webClient. But I noticed that django receives the file and body separately from the request. Like this request.FILES['file'] How do I send a file from Spring then? current webclient code MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("file", file); return webClient.post() .uri("...") .body(BodyInserters.fromMultipartData(builder.build())) .retrieve() .bodyToMono(String.class); -
Why object is not being created while running Django TestCase
I created a simple model test case using TestCase class. I created an object using setUp function and test the count of the object using assertEqual inside another function. The test ran successfully, but when I check the Django admin, there was no object that I just created, and also there was no table named django_test. My test case: class TestContact(TestCase): def setUp(self): self.contact = Contact.objects.create( full_name = "John Van", email = "jon@gmail.com", phone = 9845666777, subject = "My query", message = "test message" ) def test_contact_count(self): self.assertEqual(Contact.objects.count(),1) Also, is setUp, a built in function or we can use any function name while creating the object inside it?? -
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.