Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why do I solve this connection refuse error in postgres database
what to do to solve this operational error issue? hi,sir i have deployed my django website and i have some issues with db connection my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'avc', 'USER': 'postgres', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT':'5432' } } i am using postgres 10 this is the error database refused the client request, error -
SQL instr equivalent in Django
I want to check if given text contains in a sub string present in db, ex:- string to search - "my name is john" string in db- "john". SQL query select * from `demo` where instr('my name is john','column_name') > 0 What is the Django Equivalent of above query? -
How to add dynamic mega menu in Django app with generic views
My project need dynamic mega menu links in all pages. In function view I have to query the model for each views. Can I reduce the line of code using django generic views and inherit form one class view. -
How to put all the db data in redis while making POST call? The below code just stores the data which was posted but not all
The code is attached as an image. Need to store whole data from db to redis after post but my code only POSTs the current data -
Data are not being retrieved form database ..Django Todol List app
class TodoModel(models.Model): enter code herecontent = models.TextField(max_length=500) enter code herecontent_date = models.DateTimeField() enter code hereuser = models.ForeignKey(User, enter code hereon_delete=models.CASCADE) `enter code hereobjects = models.Manager() `enter code todolist = CustomManager() import datetime from django.db import models class CustomManager(models.Manager): enter code heredef get_today_list(self): enter code herecurrent_date = datetime.datetime.today() enter code herereturn super().get_queryset().filter(content_date=current_date) enter code here enter code here def get_next_day_list(self): enter code herenext_day_date = datetime.datetime.today()+ enter code heredatetime.timedelta(days=1) enter code herereturn super().get_queryset().filter(content_date=next_day_date) def schedule(request): hereif request.user.is_authenticated: enter code hereif request.method == 'POST': enter code herefm = enter code hereTodoForm(request.POST,instance=request.user) enter code hereif fm.is_valid(): enter code herecon = fm.cleaned_data['content'] enter code herecon_date = fm.cleaned_data['content_date'] enter code herescd = TodoModel(content=con, enter code herecontent_date=con_date, enter code hereuser=request.user) enter code herescd.save() enter code herefm = TodoForm() enter code hereelse: enter code here`fm = TodoForm() `enter code here`my_day = TodoModel.todolist.get_today_list() `enter code here`my_next_Day = `enter code here`TodoModel.todolist.get_next_day_list() `enter code here`current_date = `enter code here`datetime.datetime.today().strftime("%B %d, %Y") `enter code here`nex_day_date = datetime.datetime.today() + `enter code here`datetime.timedelta(days=1) context = { 'form': fm, 'myday': my_day, 'my_next_day': my_next_Day, 'current_date': current_date, 'next_day_date': nex_day_date, } return render(request, 'ultratodo/profile.html', context) else: return HttpResponseRedirect('/userlogin/') #and this is what I have written in html file <tr> {% for day in myday %} <td>{{day.content}}</td> {% endfor … -
Bootstrap elements not showing in a row (class="row")
what it looks like what it's supposed to look like I'm trying to get them to fit in one row <form method="POST" class="row"> {% csrf_token %} <label class="col-lg-4">Your tasks for today?</label> <input type="text" class="form-control col-lg-6" name="task" id="exampleFormControlInput1" placeholder="New Task?"> <button type="submit" class="btn btn-primary col-lg-2">Add task</button> </form> "col-lg-6" on the input is not working , the size doesn't change even if I give a different number. -
how to return json response from html fragment stored in a dictionary key
courseware_context['fragment'] = self.section.render(self.view, section_context) the above written line is returning an html fragment in courseware_context['fragment'].here section is a variable defined in class. can anybody please help me out how to return json response from this line of code. -
Queryset on Django
I want to retrieve data from 10 data from largest to smallest, I use a queryset like this and it runs smoothly. similarity_scores = Similarity.objects.all().order_by('-similarity_score')[:10] but when i want to fetch data first_movie with word "Innocence (2014)" and sort it from data 10 from largest to smallest, i use queryset just add .filter() like this and get error similarity_scores = Similarity.objects.all().filter(first_movie ="Innocence (2014)").order_by('-similarity_score')[:10] Error invalid literal for int() with base 10: 'Innocence (2014)' did I make mistake? I really appreciate all the answers even if they are explanations, because I've read the docs from Django I can't understand them yet. Thank you -
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.