Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to combine a django app and a javascript app into one app?
I'm looking for ideas on how to implement the following requirement. I have 2 different applications one being a python Django app and the other one being a pure javascript app. I can get both the apps running on different ports but I need to be able to integrate the js app into the Django app. I.e. I want to add the js app into the Django app such that when you navigate to djangoapp.com/admin/js_app you go to the landing page of the js_app application. the 2 apps are https://github.com/CodeForAfrica/gmmp and https://github.com/OpenUpSA/wazimap-ng-ui any ideas will be appreciated -
Django template : sorting by value of __str__
I am using django 3 and I have surcharged the str function for my model : class SubSubCategory(models.Model): subCategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE) name = models.CharField("Nom du sous sous category" , max_length=200, ) description = models.CharField("Description du sous sous category" , max_length=200, null=True, blank=True) def __str__(self): description_locale = self.name + " : " + self.description if self.description else self.name hierarchie = [str(x) for x in [self.subCategory.category, self.subCategory, description_locale]] description_totale = " > ".join(hierarchie) return description_totale How could I ask my template to order my list according to this str representation ? I would like to do something like : {% for SubSubcategory in object_list|dictsort:'str' %} but it obviously doesn't work, as "str" is nothing. How do I call the string representation of an object in a template ? to pass it as an ordering order ? -
How to display particular stuff of the registered person in profile page - Django
I have a member table, I want to fetch and display some of the fieldsets like fullname , email and phone number in the profile page. here is the views.py def index(request): if request.method == 'POST': member = Member( fullname=request.POST.get('fullname'), companyname=request.POST.get('companyname'),Email=request.POST.get('email'),password=request.POST.get('password'),contactno=request.POST.get('contactno'),role=request.POST.get('role'),) member.save() return redirect('/') else: return render(request, 'web/index.html') here is the models.py class Member(models.Model): fullname=models.CharField(max_length=30) companyname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30,default='anything') -
Auto login in django webapp opened in an iframe inside microsoft dynamics
Situation: I have a developed a webapp using django which uses the default authentication middleware.All the views are login_required. Now client wants when he will login into CRM then webapp will open in an iframe and he should be auto logged inside django webapp as well. Issues: Opening webapp inside an iframe in CRM can be done. But how can django webapp create a session for the user logged in inside CRM? Django uses its own authentication, CRM uses its own. Even If i link Django authentication with azure active directory , still username and password has to be entered in the iframe.I cannot figure out how auto login will be done. Please suggest -
how to serialize a dictionnary using Composite fields
I am trying to develop a POST API. I am trying to use a dictionnary to store social links of an actor model socials links should be stored in a variable socials in the Actor model. socials= {"facebook":"www.facebook.com/" , "instagram":"www.instagram.com/" ,"linkedin":"www.linkedin.com/" } Here is the actor model model.py class Actor: name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) bio = models.TextField() created = models.DateTimeField(default=timezone.now ) updated = models.DateTimeField(auto_now=True) socials = models.CharField(max_length=1024 , blank=True) class Meta: app_label = 'actors' verbose_name = _('Actor') verbose_name_plural = _('Actors') ordering = ('name',) def __str__(self): return self.name serializer.py class ActorSerializer(serializers.ModelSerializer): added_by = serializers.ReadOnlyField(source='added_by.username') socials = serializers.DictField( child=serializers.URLField(max_length=200, min_length=None, allow_blank=False) ) class Meta: model = Actor fields = '__all__' views.py class ActorListView(generics.ListCreateAPIView): queryset = Actor.objects.all() serializer_class = ActorSerializer This is my code. But there is something missing in order to do what I want (I got an error). Could any one suggest a solution ? bold italic -
Django, Archery System
This is more a plea for guidance rather than any hard coding example. I have set myself a problem to write an archery recording system using Django. I have got the recording system working well and the system can register users, record their scores, show their scores filtered by round, show the users scores who have shot a particular round etc. This issue I have got is when it comes to classifying the score. I will explain: In archery scores are recorded against the round you shoot. These vary so you have 60+ rounds to choose from each having different criteria and different maximum scores. Archers are grouped according to gender and age (10 sub groups) The classification system works by taking the round shot and the sub-group that the archer falls into and looking across a table of values. The classification gained is the one that the score falls into i.e. if you are male and over 18 you are grouped as a 'Gentleman' The round you shoot is called a 'York' and you score 550 The table you would consult would look like this Round | 3rd Class | 2nd Class | 1st Class | Bowman | Master … -
creating notification using django
how to create a simple notification page using django. I have tried with many codes but none of the concept worked for my project. Suggest me a simple and accurate concept. whenever we click on the notification page notification like post created at a particular time should get displayed. I will be kindful if you could suggest the needful code. Thankyou in advance. -
MYSQL Django Login
login page def logins(request): if request.method == "POST": email = request.POST.get('email') password2 = request.POST.get('password2') print email print password2 ------------runfine --------- user = authenticate(email=email, password2=password2) if user is not None: login(request, user) messages.success(request, 'Welcome' + request.POST.get('username')) return redirect('index') else: messages.info(request, 'Invalid Credentials') return render(request, "login.html") setting I had connected it with MySQL DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'as', 'USER':'root', 'PASSWORD':'', 'HOST':'127.0.0.1', 'PORT':' 3306', 'OPTIONS':{ 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } URLs page path("logins/", views.logins, name="logins"), HTML page <form action="/logins/" method="post">{% csrf_token %} <div class="content"> {% for message in messages %} <h3 style="color:red"> {{message}} </h3> {% endfor %} </div> <div class="field"> <input type="text" name="email" required> <label>Email ID</label> </div> <div class="field"> <input type="password" name="password2" required> <label>Password</label> </div> <div class="content"> <div class="checkbox"> <input type="checkbox" id="remember-me" > <label for="remember-me">Remember me</label> </div> <div class="pass-link"> <a href="#">Forgot password?</a></div> </div> <div class="field"> <input type="submit" value="Login"> </div> <div class="signup-link">Not a member? <a href="/signup">Signup now</a> </div> </form> it does not execute if statement in the login it always showing me the else Part and do not give any error and also created a database in my SQL name as and I had also migrated the files I store the data inside my MySQL using Django but I … -
Django project template doesn't exist
Hi i'm just getting started with Django and i'm running a project, I have created an HTML file and this is the views.py def index(request): return render(request, "hello/index.html") and this is the urls.py inside the maine file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include("hello.urls")) ] and this is the urls.py inside the project file from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] and i got this error view from my project -
django list_filter is not scrollable
I have a long list of elements (50 elements) and I wanted to use that as a list_filter in django admin panel. But when I use this list, on very right side where FILTER panel appears I can see only 20 items and it is not scrollable so rest of 30 is hidden. How can I get those 30 items in FILTER section or How scrolling will be possible so that all 50 items can be viewed. -
FlatPicker in Django Edit custom form showing time, only days
I have a Django app, with new template where datetimepicker works well. I created an edit template but the widget do not load automatically, so I added them. But for some reason, i do not know how to bring the datetimepicker, I can only get the datepicker. Does anybody knows please ? The precise line in the edit template looks like: <div> <input id="Restriction_Start_Date_id" type="text" name="Restriction_Start_Date" value="{{ restricted_name_obj.Restriction_Start_Date|date:'n/j/Y G:i' }}" class="form form-control datepicker" > </div> While on the new template I have : <div>{{ form.Restriction_Start_Date.label_tag }}</div> <div> {{ form.Restriction_Start_Date.errors }} {{ form.Restriction_Start_Date }} </div> -
django auto decrement an IntegerField
models.py class Dispositivo(models.Model): fornitore= models.ForeignKey(Fornitore, on_delete=models.CASCADE) codiceProdotto = models.CharField(max_length=100, verbose_name="Codice prodotto") quantita = models.IntegerField(blank=True, default="1", verbose_name="quantità") class Fattura(models.Model): dispositivo = models.ManyToManyField(Dispositivo, related_name='fattura_disp', default='0', limit_choices_to={'quantita__gte' : 1}, ) fattura = models.FileField(blank=True, upload_to="fatture/%Y/%m/%d") creato = models.DateField(verbose_name="data vendita") def dispositivi(self): return "\n, ".join([p.codiceProdotto for p in self.dispositivo.all()]) admin.py @admin.register(Dispositivo) class DispositivoModelAdmin(admin.ModelAdmin): model = Dispositivo list_display = ['codiceProdotto', 'descrizione', 'quantita' , 'venduto', 'fornitore', 'DDT', 'creato'] list_editable = ['venduto', 'quantita'] def get_queryset(self, request): qs = super(DispositivoModelAdmin, self).get_queryset(request) return qs.filter(quantita__gte=1) @admin.register(Fattura) class FatturaModelAdmin(admin.ModelAdmin): model = Fattura list_display = ['cliente', 'dispositivi', 'fattura', 'creato'] in admin pannel when i create a Fattura i select more Dispositvi, which method i must override for auto decrement of Dispositivi ? -
Stripe CLI webhook not invoked when card declined
I am using the stripe CLI to test webhooks in my django application. When a payment goes through, the webhook records this and seems to work perfectly fine. However, whenever I am using one of the stripe test cards that get declined (such as: 4000000000009987), its as if the webhook never gets called, even though stripe tells me the error that the card was declined. It's as if the webhook never even gets called from stripe when a payment fails. What am I missing? my webhook in python @require_POST @csrf_exempt def webhook_received(request): stripe.api_key = settings.STRIPE_SECRET_KEY endpoint_secret = settings.STRIPE_ENDPOINT_SECRET payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) print('THE EVENT: ', event) print('THE EVENT TYPE: ', event.type) # Handle the event if event.type == 'payment_intent.succeeded': payment_intent = event.data.object # contains a stripe.PaymentIntent # Then define and call a method to handle the successful payment intent. # handle_payment_intent_succeeded(payment_intent) elif event.type == 'payment_method.attached': payment_method = event.data.object # contains a stripe.PaymentMethod # Then define and call a method to handle the successful attachment of a PaymentMethod. # handle_payment_method_attached(payment_method) … -
django page not found when creating a register and sign up
I tries to fix this problem so many times but I get this error always and also I tired to make register page with django "404 page not found" any way this is some files in my code files in my code and also push this to git https://github.com/dtheekshanalinux/learnprogramming if don't mind go and check it out index.html in templates {% load static %} {% static "images" as baseUrl %} <!doctype html> <!-- Website Template by freewebsitetemplates.com --> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mustache Enthusiast</title> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/mobile.css' %}" media="screen and (max-width : 568px)"> <script type="text/javascript" src="{% static 'js/mobile.js' %}"></script> </head> <body> <div id="header"> <a href="{% static 'index.html' %}" class="logo"> <img src="{% static 'images/logo.jpg' %}" alt=""> </a> <ul id="navigation"> <li class="selected"> <a href="{% static 'index.html' %}">home</a> </li> <li> <a href="{% static 'about.html' %}">about</a> </li> <li> <a href="{% static 'accounts/register' %}">register</a> </li> <li> <a href="{% static 'contact.html' %}">contact</a> </li> </ul> </div> <div id="body"> <div id="featured"> <img src="{% static 'images/the-beacon.jpg' %}" alt=""> <div> <h2>the beacon to all mankind</h2> <span>Our website templates are created with</span> <span>inspiration, checked for quality and originality</span> <span>and meticulously sliced and coded.</span> <a href="{% static 'blog-single-post.html' … -
Installing nested Django app causes RuntimeError
So, basically, I have a project structure like that: project |__ admin_panel/ | |__ admins/ <- django application | |__ orderlist/ <-- another django application |__ project/ | |__ settings.pu <-- django settings module |__ manage.py And my INSTALLED_APPS config looks something like that: INSTALLED_APPS = [ ..., 'admin_panel.admins', 'admin_panel.orderlist', ] I want to use AppConfig class for my orderlist django application. It is not loaded by default: # admin_panel/orderlist/apps.py from django.apps import AppConfig class OrderlistConfig(AppConfig): name = 'orderlist' def ready(self): print('.ready() was called') from . import signals There is no .ready() was called message when starting Django test server I've tried to specify AppCofnig path directly on INSTALLED_APPS: INSTALLED_APPS = [ ..., 'admin_panel.admins', 'admin_panel.orderlist.apps.OrderlistConfig', ] But this causes error: Traceback (most recent call last): File ".../manage.py", line 22, in <module> main() File ".../manage.py", line 18, in main execute_from_command_line(sys.argv) File ".../lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File ".../lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File ".../lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File ".../lib/python3.9/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant django/apps/registry.py code that fails: # An RLock prevents other threads from entering this section. The # compare and set operation below is atomic. if self.loading: # … -
Django: How to display details of a product in a new page when i click on a product in the product page
I am a newbie to django and i am doing a code along with a youtube tutorial on how to build an ecommerce site. My challenge right now is this: On my product page, there is a list of products. What i want is when a user clicks on a particular product, i want the user to be redirected to a page (a product details page) that has the custom details of that particular product. This is the structure of my code. In my views.py file, i have the 'products1' as the page view for all my products and the 'product_details' page is where i want the details of a particular product to be displayed def products1(request): products = Product.objects.all() context = {'products':products} return render(request, 'shopping_app/products1.html', context) def product_details(request, id): product = get_object_or_404(Product, id) context = {'product': product} return render(request, 'shopping_app/product_details.html', context) In my urls.py. I created the urls for the following pages like so. path('products4/', views.products4, name='products4'), path('product_details/<int:id>', views.product_details, name='product_details'), THe problem is whenever i click on the product for me to be redirected to the details page, a TypeError is thrown. -
JavaScript DOM function is skipped in Django project
I have a JavaScript function scroll(); which works with DOM elements. Now it is working on just html file, but not on Django server. I know that Django automatically is skiping js dom function like document.getElementById so is there any solution? Maybe something change in settings or something? -
specific variable in loop in Django
i have a questions list in views and i knew how to pass it to template and how to print it in loop {% for q in questions %} and i knew how to pass it to JavaScript and how to bring a specific questions from the list for example : document.getElementById("p").innerHTML = "{{questions.0}}"; BUT my question is How to bring specific question based on variable i for example ?? i tried this way: document.getElementById("p").innerHTML = "{{questions."+i+"}}"; but it didn't work? do you have any solution? -
Django serialize a field of a model to a dictionary
I have this model, class MyModel(models.Model): some_id = models.PositiveIntegerField(primary_key=True) diff_id = models.PositiveIntegerField(null=True) some_data = models.JSONField(null=True) I need to paginate this and serialize the some_data to a dictionary. query = MyModel.objects \ .order_by('some_field') paginator = Paginator(query, self.batch_size) for i in paginator: data = list(i.object_list.values(*fields, **suffixed_fields)) some_data field contains a json as follows. {"diff_id" :6916} diff_id is a field from the same model. Is there a way to do this in the model or in a serialize it self? if so please help -
django can't find template when trying to use forms
I am trying to follow the django documentation howto create a form using sjango form class. I am doing every step but when trying to access my form it says that is cannot find the template: django.template.exceptions.TemplateDoesNotExist: lform heres is my forms.py: class LoginForm(Form): uname=CharField(label='user name',max_length=20) passw=CharField(label='password', max_length=20) the template lform.html: <form action="ulogin" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> and my view. I think the problem is in the render function: def testform(request): if request.method=='POST': form=LoginForm(request.POST) if form_is_valid(): return render('index') else: HttpResponseRedirect('index') else: form=LoginForm() return render(request,'lform',{'form':form}) and url.py: path('lform',views.testform,name='lform') the last line in the view function, return render(request,'lform',{'form':form}) gives the error any suggestions? -
HTML table copy to outlook
Hi when i copy html table from website to outlook the headers takes more space. I use Datatble as a html table.After Pasting into Outlook Image Given Actual Image -
Django how to create button that visible only some type of users
I created a system with Django. I have several users and these users can have different ranks. I have a page and only 'lead' users can see the page. In user profile page I want to create a button that visible to only leads. models.py class UserProfile(AbstractUser): ranks = ( .. ('lead', 'Lead'), ('manager', 'Manager'), ... ) comp_name = models.CharField(max_length=200, default='', blank=True, null=True) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) ... views.py def is_lead(user): return user.rank == 'lead' @user_passes_test(is_lead) @login_required def lead_page(request): return render(request, 'lead.html') profile.html <div class="col"> <a href="/leadpage" class="btn btn-outline-success"> Enter </a> </div> -
How to compare parameter passed through POST method with Django rest framework Model and generate custom response?
I am designing Basic Django rest framework based application, i need to compare external parameters passed through POST method in Postman with Coupon code in database and generate custom response like 'This code is redeemed/validate." or " This is invalid coupon/code." Here is my Model.py file : from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code here is my views.py file: from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Coupon from .serializers import CouponSerializer from rest_framework import viewsets class CouponViewSet(viewsets.ModelViewSet): queryset = Coupon.objects.all() serializer_class = CouponSerializer @api_view(['POST']) def coupon_redeem(request): if request.method =='POST': serializer = CouponSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) here is my Serializer.py file from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' Please help if possible, Thank you. -
Not Able To Deploy Django App Because of This Error How To Fix It
ERROR: mysqlclient-1.4.6-cp38-cp38-win32.whl is not a supported wheel on this platform. ! Push rejected, failed to compile Python app. ! Push failed -
Django Runserver fail without any error messag
I am trying to run Django application, when i run python manage.py runserver It fails without any error