Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is print(bid > highest_bid) returning true, when bid = 3 and highest_bid =2000?
I'm making a simple form in Django without using the in-built Django forms. To process the form I'm just using HTML/Django template and Python in the views.py file. I don't understand why print(bid > highest_bid) is returning True when: Highest bid = 2000.6 bid = 3 listing_detail.html <form method="POST" action="{% url 'listing-detail' object.id %}"> {% csrf_token %} <input type="hidden" name="highest_bid" value="{{ highest_bid }}"> <input type="number" step=".01" min="" placeholder="0.00" name="bid"> <button type="submit">Place bid</button> </form> views.py # place bid highest_bid = request.POST.get("highest_bid", "") #2000.6 print(f'Highest = {highest_bid}') bid = request.POST.get("bid", "") #3 print(f'bid = {bid}') print(bid > highest_bid) # returns True if 'bid' in request.POST and bid > highest_bid: #bid = float(request.POST['bid']) new_bid = Bids(bid_value=bid, bidder=self.request.user, item=item) new_bid.save() return redirect(reverse("listing-detail", args=listing_id)) This means that the bid is being saved to the database. Even though I am trying to only save the highest bid with the line if 'bid' in request.POST and bid > highest_bid: -
how to iterate over captured images and add to an input tag - js
i'm trying to capture multiple images and then save into the database here is the js code const player = document.getElementById('player') const canvas = document.getElementById('canvas') const form = document.getElementById('form') const docs = document.getElementById('documents') const captureButton = document.getElementById('capture') const context = canvas.getContext('2d') captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height) e.preventDefault(); let new_image = document.createElement('img') new_image.src = canvas.toDataURL() console.log(new_image) docs.value = canvas.toDataURL() form.insertAdjacentElement('beforeend',new_image) e.preventDefault(); }); navigator.mediaDevices.getUserMedia({video: true}) .then((stream) => { player.srcObject = stream;}) <form id="form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %} <video id="player" controls autoplay></video> <button type="button" id="capture">Capture</button> <button>save</button> <canvas id="canvas" width=320 height=240></canvas> <input type="text" name="documents" hidden id="documents"> </form> and here is my views.py to get multiple base64 data and split it by using its data attribute , here is my code @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = request.POST.get('documents') data,imgdata = images.split('data') for img in imgdata: print(img) format, imgstr = img.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) photo = Document.objects.create( booking = obj, docs = data ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('choose or capture right image ..')) return render(request,'booking/add_img.html',{'obj':obj}) but it raise this error : not enough values to unpack (expected 2, got 1) and the print(img) returns only : ! and … -
TypeError: save() got an unexpected keyword argument 'force_insert'
I'm trying to implement a signal that creates a Profile upon the save of a User instance. Trying to test this out with my form to register users gives me the following stacktrace: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/auth/register/ Django Version: 3.2.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'webpack_loader', 'home', 'personal_list', 'utils', 'authentication'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/noxlock/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/noxlock/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/noxlock/my-anime-openings-list/MAOL/authentication/views.py", line 12, in register form.save() File "/home/noxlock/.local/lib/python3.8/site-packages/django/contrib/auth/forms.py", line 131, in save user.save() File "/home/noxlock/.local/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 67, in save super().save(*args, **kwargs) File "/home/noxlock/.local/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/home/noxlock/.local/lib/python3.8/site-packages/django/db/models/base.py", line 774, in save_base post_save.send( File "/home/noxlock/.local/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/home/noxlock/.local/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 181, in &lt;listcomp&gt; (receiver, receiver(signal=self, sender=sender, **named)) File "/home/noxlock/my-anime-openings-list/MAOL/personal_list/models.py", line 45, in create_profile Profile.objects.create(user=instance) File "/home/noxlock/.local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/noxlock/.local/lib/python3.8/site-packages/django/db/models/query.py", line 453, in create obj.save(force_insert=True, using=self.db) Exception Type: TypeError at /auth/register/ Exception Value: save() got an unexpected keyword argument 'force_insert' Typically this is usually due to missing **kwargs in the definition … -
I want to save as null in database but not allowed (Django)
I have a model like this: class Maca(models.Model): maca_number = models.PositiveIntegerField( db_column='Maca Number' ) and a form like this: class MacaForm(forms.ModelForm): maca_number = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Maca Number'})) so I want if the user not fill this field to send empty in database. I got this error ValueError: Field 'maca_number' expected a number but got '' Thank you in advance -
Is somebody tried to build a 3D CAD wep app running on Browser?
I found an App which are able to use on Browser. I gonna build a similar one using python. Is possible by python? If someone experienced this, please help me. Thanks in advance! -
How do I fix this Getting no reverse match error in django
I have been facing this issue. And I have a url name post-page-detail but then also getting error please See the error screenshot below. My singlepost.html html page <a href="{% url "post-detail-page" slug=post.slug %}"> <h2>{{post.tractor_company}} || {{post.tractor_model}}</h2> <pre><h5>{{post.implimentaion}}</h5> {{post.farmer}} Uplode Date : {{post.date}}</pre> </a> </div> URLs.py from . import views urlpatterns = [ path("",views.starting_page,name = "starting-page"), path("posts",views.posts,name = "post-page"), path("posts/<slug:slug>",views.post_detail,name="post-detail-page"), ] View.py from django import forms from django.contrib.auth.models import User from django.shortcuts import render, redirect ,get_object_or_404 from .models import Post, Farmer # Create your views here. from django.http import HttpResponseRedirect # Create your views here. def starting_page(request): return render(request,"tractor/index.html") def posts(request): qs = Post.objects.all() context = {"posts":qs} return render(request,"tractor/all-post.html",context) def add_post(request): pass def post_detail(request,slug): indentified_post = get_object_or_404(Post,slug=slug) return render(request,"blog/post-detail.html",{'post':indentified_post}) i am iterating through posts and using the post-detail.html page all-post.html. {% load static %} {% block title %} All Tractors {% endblock %} {% block content%} <section id="all_events"> <br> <h1 style="text-align:center;">All Tractors</h1> <ul> {% for post in posts %} <br> {% include "tractor/includes/singlePost.html" %} {% endfor %} </ul> </section> {% endblock %} -
Deploying Django and Vue app to Elastic Beanstalk in the same instance
I want to deploy my Django/Vue app to Elastic Beanstalk. I have different endpoints for BE and FE through ports 8082 and 8080 respectively. I want to use Elastic Beanstalk's multicontainer deploy feature and deploy my BE and FE apps to the same instance. I initialized and configured my EB app and environment as a Python app. I can now deploy my BE to EB and access the api through the provided url. Is it possible to configure my EB app to deploy FE on the same instance as well. Or do I need to deploy my Vue app to another instance? It is described how to deploy multicontainer apps to eb here : https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker_v2config.html. But it only describes a php app running on nginx and it's not useful to me. Thanks. -
How to CreateAPIView using the request.user
Hi I'm wondering what the best practice is for creating a new model entry with a user based off the request in Django Rest Framework? Models: class Asset(models.Model): user = models.ForeignKey(UserAccount, on_delete=models.CASCADE, related_name="assets") name = models.CharField(max_length=200) amount = models.DecimalField(max_digits=10, decimal_places=2) Serializers: class AssetSerializer(serializers.ModelSerializer): class Meta: model = Asset fields = '__all__' Views class CreateAssetView(generics.CreateAPIView): serializer_class = AssetSerializer <Doesn't seem to work, possibly since user isn't in the json> def perform_create(self, serializer): serializer.save(user=self.request.user) Basically I want to be able to send a POST request {name: 'myasset', amount: '50'} to this endpoint and have a new Asset saved with the User field obtain from the request. What is the best way to do this? Thanks -
Django new line in output
i try to print model object in new line but my code don't work. Here is my code and I want to know how can I fix this problem? def list_create_tasks(request): if request.method == 'GET': all_tasks=Task.objects.all() return HttpResponse('\n'.join(map(str, all_tasks))) -
! [rejected] master -> master (fetch first) when pushing to git
Since the major change in policy- I used SSH key. All went well until changes were made. Now when I'm trying to push my changes this error pops :( ! [rejected] master -> master (fetch first) error: failed to push some refs to 'github.com:kohenm63/phone_book.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. -
Passing a Django database pk id to Dash app
I have successfully embedded a Dash application into my Django app. I can display simple plots. But what I want to do, and have been unable to do by following documentation, is pass a pk id variable into the Dash app, pull relevant DB information according to that pk, and then plot it. my urls.py: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^model/(?P<pk>\d+)/$', views.model, name='model'), views.py: def home(request): return render(request, 'home.html') def model(request, pk): context = {'data' : {'pk': pk}} return render(request, 'model_results.html', context) models.html template: {%load plotly_dash%} <body> <div class="container"> <!--Row with two equal columns--> <div class="row"> <div class="col-lg-1 col-md-1 col-xl-1 col-sm-1"> <div class = "card"> <div class = "card-body"> {%plotly_app name="tutorial_1" initial_arguments=data%} </div> </div> </div> </div> </div> </body> and lastly, my dash app: app = DjangoDash('tutorial_1') app.layout = html.Div(children=[ html.H1(children='Dash Tutorials'), dcc.Graph( id='example', figure={ 'data': [ {'x': [1, 2, 3, 4, 5], 'y': [9, 6, 2, 1, 5], 'type': 'line', 'name': 'Boats'}, {'x': [1, 2, 3, 4, 5], 'y': [8, 7, 2, 7, 3], 'type': 'bar', 'name': 'Cars'}, ], 'layout': { 'title': 'Basic Dash Example' } } ) ]) if __name__ == '__main__': app.run_server(debug=True) It is unclear to me from other examples how I can use the Django ORM … -
heroku git:remote -a command is not working
heroku git:remote -a mymailapp-live » Warning: heroku update available from 7.53.0 to 7.59.0. Error: Command failed: git remote fatal: not a git repository (or any of the parent directories): .git it is showing me above error. please help me. i am hosting this using heroku-cli. -
Multiple django forms with diferent placeholders, do i use form factory?
I have a main model Questionare, A list of ExtraQuestion's and a model to store the answers in... Questionare(model.Model): first_name = ... last_name = ... ExtraQuestion(model.Model): question = ... Answer(model.Model) questionare = models.ForeignKey(Questionare...) extra_qestion = models.ForignKey(ExtraQuestion...) answer = ... How do i create a bunch of ModelForms for each of the ExtraQuestions with the question as a placeholder to the input field and update the Answer model with the relevant foreign keys. I was looking at FormFactory but I think every form needs to be exactly the same and I cant differ the placeholder. Any advice is appreciated. -
Setting up create-react-app in docker shell only
I'm curious if anyone knows why it's not common practice to run create-react-app from within the shell. The goal here is to attempt to avoid having to install packages on my local machine per create-react-app since I'll never run 'npm start' on my local machine but rather from within the shell. The reason I ask is that I know this can be done in Django. Django can be done either way, where you can either create 'startproject' on your local machine, then create Dockerfile and docker-compose.yml file OR you can create an empty 'app' folder within the root folder, start with Dockerfile and docker-compose file, go into the shell and do startproject from within the shell with no problems as long as you have your volumes setup correctly. This might just be my lack of understanding of how Django dev projects are built vs React dev projects. Or could be just how python image works vs node image from dockerhub. I was able to create a simple Dockerfile (below). Then run 'docker-compose build' then run 'docker-compose run react_app sh -c "npx create-react-app ." ' and this worked, but this still copies over all the node_modules anyhow. The part that interests … -
I am getting No reverse match error in django but it is used urls.py
I have been facing this issue. And I have a url name post-page-detail but then also getting error please See the error screenshot below. My html page <a href="{% url "post-detail-page" slug=post.slug %}"> <h2>{{post.tractor_company}} || {{post.tractor_model}}</h2> <pre><h5>{{post.implimentaion}}</h5> {{post.farmer}} Uplode Date : {{post.date}}</pre> </a> </div> URLs.py from . import views urlpatterns = [ path("",views.starting_page,name = "starting-page"), path("posts",views.posts,name = "post-page"), path("posts/<slug:slug>",views.post_detail,name="post-detail-page"), ] View.py from django import forms from django.contrib.auth.models import User from django.shortcuts import render, redirect ,get_object_or_404 from .models import Post, Farmer # Create your views here. from django.http import HttpResponseRedirect # Create your views here. def starting_page(request): return render(request,"tractor/index.html") def posts(request): qs = Post.objects.all() context = {"posts":qs} return render(request,"tractor/all-post.html",context) def add_post(request): pass def post_detail(request,slug): indentified_post = get_object_or_404(Post,slug=slug) return render(request,"blog/post-detail.html",{'post':indentified_post}) i am iterating through posts and using the post-detail.html page all-post.html. {% load static %} {% block title %} All Tractors {% endblock %} {% block content%} <section id="all_events"> <br> <h1 style="text-align:center;">All Tractors</h1> <ul> {% for post in posts %} <br> {% include "tractor/includes/singlePost.html" %} {% endfor %} </ul> </section> {% endblock %}``` -
How to implement refresh token in react js
The response from the server set the access and refresh token to the client(reactjs) as an httponly cookie. How can I use the refresh token to generate another access token, because when I try to use document.cookie or cookie.get('refresh') it returned undefined. axios.post('http://localhost:8000/api/token/refresh/', { refresh: cookie.get('refresh') // Cookie here is undefined }).then(response => { // new access token }) -
Async run script from "python manage.py shell"?
As far as I can tell, running a script from python manage.py shell like python manage.py shell < import.py is done synchronously: # models.py class PersonManager(models.Manager): def generate_num_children(self, persons): for person in persons: person.generate_num_children() class ParentManager(models.Manager): def generate_num_grandchildren(self, parents): for parent in parents: parent.generate_num_grandchildren() class Person(models.Model): objects = PersonManager() num_children = models.IntegerField(default=0) parent = models.ForeignKey(related_name="children") def generate_num_children(self): self.num_children = 1 self.save() class Parent(models.Model): objects = ParentManager() num_grandchildren = models.IntegerField() def generate_num_grandchildren(self): num = 0 for child in self.children.all(): num += child.num_children self.num_grandchildren = num self.save() # import.py parent = Parent.objects.create(id=1) person1 = Person.objects.create(id=2, parent=parent) person2 = Person.objects.create(id=3, parent=parent) person3 = Person.objects.create(id=4, parent=parent) persons = Person.objects.all() Person.objects.generate_num_children(persons) parent.generate_num_grandchildren() # python manage.py shell Parent.objects.get(id=1).num_grandchildren # Returns 0 When I enter each line individually in python manage.py shell or in a test file however, the code runs asynchronously and gives me the correct result: parent = Parent.objects.create(id=1) person1 = Person.objects.create(id=2, parent=parent) person2 = Person.objects.create(id=3, parent=parent) person3 = Person.objects.create(id=4, parent=parent) persons = Person.objects.all() Person.objects.generate_num_children(persons) parent.generate_num_grandchildren() Parent.objects.get(id=1).num_grandchildren # Returns 3 So how can I make my import.py file async? # import.py # Run first parent = Parent.objects.create(id=1) person1 = Person.objects.create(id=2, parent=parent) person2 = Person.objects.create(id=3, parent=parent) person3 = Person.objects.create(id=4, parent=parent) persons = Person.objects.all() Person.objects.generate_num_children(persons) # Run … -
Django: AttributeError 'WSGIRequest' object has no attribute 'get'
I am trying to add a set of inline forms, but when I try to save the information of the forms it throws me this error views.py The intention is to create more orders for a particular client, for that reason I focus on the "createOrder" function to achieve it. from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from django.forms import inlineformset_factory from .forms import OrderForm, CustomerForm # Create your views here. def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request, pk): OrderFormSet= inlineformset_factory(Customer, Order, fields=('product', 'status')) customer = Customer.objects.get(id=pk) form_set_value= OrderFormSet(instance=customer) if request.method == 'POST': form_set_value= OrderFormSet(request, instance=customer) if form_set_value.is_valid: form_set_value.save() return redirect('/') context = {'form_set_key':form_set_value} return render(request, 'accounts/order_form.html', context) order_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{ … -
How do I resovle django saml2 authentication type errors in saml.py
I am attempting to integrate django-saml2-auth into legacy code running django1.11.29 with python2.7. From the IDP side I am completing authentication but when I then get the following error from my website. ValueError at /saml2_auth/acs/ Type and value do not match: string:<type 'unicode'>:19055 Request Method: POST Request URL: https://mysite/saml2_auth/acs/ Django Version: 1.11.29 Exception Type: ValueError Exception Value: Type and value do not match: string:<type 'unicode'>:19055 Exception Location: /abc/abc/abc/Django_Env/lib/python2.7/site-packages/saml2/saml.py in _wrong_type_value, line 171 Python Executable: /usr/bin/python Python Version: 2.7.5 This is the function that it fails at in saml.py, line 171 is raise ValueError(msg) def _wrong_type_value(xsd, value): msg = 'Type and value do not match: {xsd}:{type}:{value}' msg = msg.format(xsd=xsd, type=type(value), value=value) raise ValueError(msg) and here is my saml config in settings. SAML2_AUTH={ 'METADATA_LOCAL_FILE_PATH': '/abc/xyz/django-saml2/metadata_170CB91D5E5.xml', 'ASSERTION_URL': 'https://mysite', 'CREATE_USER': 'TRUE', 'ATTRIBUTES_MAP': { 'username': 'urn:mace:dir:attribute-def:UserNumber', 'ENTITY_ID': 'https://mysite/saml2_auth/acs', 'DEFAULT_NEXT_URL': '/site/' } I have been at this for a week now and have not found another package that works better than this package with in the constraints of my environment. And ideas on how to get past this. Thanks -
Django-admin can't run after fresh install
(I'm new to SO also so I'm happy to change anything wrong with my post) But I just installed Ubuntu LTS 16 and tried to get Django working. I ran these commands, and then got the error below. Commands: $ sudo apt-get install python3 $ sudo apt-get install python3-pip $ pip3 install Django $ sudo apt-get install python3-django $ sudo django-admin startproject yourprojectnamehere Error that I keep having, even after 2 OS reinstalls: File "/home/boo/.local/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line File "/home/boo/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.apps import apps File "/home/boo/.local/lib/python3.5/site-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/home/boo/.local/lib/python3.5/site-packages/django/apps/config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "/home/boo/.local/lib/python3.5/site-packages/django/utils/deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async File "/home/boo/.local/lib/python3.5/site-packages/asgiref/sync.py", line 115 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax anyone have any idea? Is it not connecting to python3 or something? My computer even says "System error, do you want to report?" and last time my whole Terminator terminal crashed and wouldn't restart so IDK if I'm messing up some system files or something too. -
Django model_formset not able to edit, save or delete information
I'm trying to create a simple modelformset to show multiple copies of the same form. My models.py table is called Driver and it has only one field, driver: class Driver(models.Model): driver = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.driver if self.driver else '' My urls.py: urlpatterns = [ path('driver/', DriverCreateView.as_view(), name = "driver-create"), ] My forms.py: class DriverForm(forms.ModelForm): class Meta: model = Driver fields = ['driver'] # exclude = ("id",) DriverFormSet = modelformset_factory(Driver, form = DriverForm, fields = ['driver'], extra = 1, max_num=20, can_delete=True) I'm fairly sure the issue is in views.py: class DriverCreateView(LoginRequiredMixin, CreateView): model = Driver form_class = DriverForm template_name = 'trucking/driver_form.html' def get_context_data(self, **kwargs): context = super(DriverCreateView, self).get_context_data(**kwargs) context['formset'] = DriverFormSet() return context def post(self, request, *args, **kwargs): formset = DriverFormSet(request.POST) form= DriverForm(request.POST) if formset.is_valid(): formset.save() if self.request.POST.get('Save_Exit'): return HttpResponseRedirect('/database/') if self.request.POST.get('Save'): return HttpResponseRedirect('/driver/') return render(request, self.template_name, {'formset': formset}) Finally my template driver_form.html: <form method = "POST"> <fieldset class = "form-group"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <table cellpadding="6" cellspacing="1" border="0"> <tbody> {% for form in formset %} {% for field in form.visible_fields %} <tr> <td class="column_name">{{field.label_tag}}{{field.auto_id}}</td> <td class="column_data">{{field}}</td> <td class="column_errors">{{field.errors|striptags}}</td> </tr> … -
What is the correct LANGUAGE_CODE for the UK?
Is the correct LANGUAGE_CODE for British English 'en-GB' or 'en-gb' when using I18N? Does it make a difference? -
Bootstrap and Django: Popper.js is not load after i rendering HTML with AJAX
I want to duplicate a tr that contains some buttons, one of them is a dropdown that works until I copy that line. This error happens even when the dropdown works, so I'm still not sure if that's what's causing this error. I've already made the imports, I've already placed them in the right order. image of error <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/popper.js' %}"></script> <script src="{% static 'js/bootstrap4.0.0.min.js' %}"></script> <script src="{% static 'js/jquery.bootstrap.modal.forms.min.js'%}"></script> <script src="{% static 'js/select2.min.js' %}"></script> [.... code here....] <td align="center"> <div class="btn-toolbar" role="toolbar" style="justify-content: center;"> <div class="dropdown d-inline-block"> <button type="button" id="botao-mudar-status-{{tarefa.id}}" class="border-0 ml-2 btn-icon btn-icon-only btn-pill btn btn-outline-primary btn-sm" aria-expanded="false" data-toggle="dropdown"> <i data-toggle="tooltip" data-placement="bottom" data-original-title="Alterar status" class="pe-7s-repeat" style=" transform: rotate(90deg); font-weight: bold; font-size: initial;"></i> </button> <div tabindex="-1" role="menu" aria-hidden="true" class="dropdown-menu-rounded dropdown-menu" x-placement="bottom-end" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(-174px, 33px, 0px);"> <form id="tarefa-mudar-status-{{tarefa.id}}"> {% csrf_token %} <button type="button" tabindex="0" id="a-fazer-{{tarefa.id}}" class="dropdown-item" data-id="{{tarefa.id|int_to_str}}">A Fazer</button> <button type="button" tabindex="0" id="em-andamento-{{tarefa.id}}" class="dropdown-item" data-id="{{tarefa.id|int_to_str}}">Em andamento</button> <button type="button" tabindex="0" id="feito-{{tarefa.id}}" class="dropdown-item" data-id="{{tarefa.id|int_to_str}}">Feito</button> <button type="button" tabindex="0" id="remover-status-{{tarefa.id}}" class="dropdown-item" data-id="{{tarefa.id|int_to_str}}">Remover status</button> </form> </div> </div> <button data-toggle="tooltip" data-placement="bottom" id="editar-tarefa-{{tarefa.id}}" data-original-title="Editar tarefa" class="border-0 ml-2 btn-icon btn-icon-only btn-pill btn btn-outline-focus btn-sm" data-form-url="{% url 'tasks:editar-tarefa' tarefa.id %}"> <i class="fa fa-edit" aria-hidden="true"></i> </button> … -
django_extensions runserver_plus returns NET::ERR_CERT_AUTHORITY_INVALID
I am following a tutorial (building a social website ~ Django 3 By Example by Antonio Mele) and attempting to implement social auth such as facebook/google by using social_django and django_extensions to provide an SSL. My installed apps are INSTALLED_APPS = [ 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django_extensions', ] with allowed hosts ALLOWED_HOSTS = [ 'mysite.com', 'localhost', '127.0.0.1' ] and have the following packages installed asgiref==3.4.1 autopep8==1.5.7 certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.6 cryptography==35.0.0 defusedxml==0.7.1 Django==3.2.6 django-extensions==3.1.3 idna==3.2 oauthlib==3.1.1 Pillow==8.3.2 pycodestyle==2.7.0 pycparser==2.20 PyJWT==2.1.0 pyOpenSSL==21.0.0 python3-openid==3.2.0 pytz==2021.1 requests==2.26.0 requests-oauthlib==1.3.0 six==1.16.0 social-auth-app-django==5.0.0 social-auth-core==4.1.0 sqlparse==0.4.1 toml==0.10.2 urllib3==1.26.7 Werkzeug==2.0.1 and my hosts file located at C:\Windows\System32\drivers\etc also contains the string 127.0.0.1 mysite.com However, whenever I run the command python manage.py runserver_plus --cert-file cert.crt, which does generate the crt and key files, and load the browser, it tells me Your connection is not private with error NET::ERR_CERT_AUTHORITY_INVALID. I have also tried django-sslserver and runsslserver however the same error results, and no resource I have found has helped. Thanks in advance for any ideas! -
Django setting a ManyToMany field to the current value of another ManyToMany field
I'm trying to set the value of my StudentMeeting model's current_courses ManyToManyField field to the value of my Student.course ManyToManyField so each meeting keeps a record of what courses the student was enrolled in at the time of the meeting. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.db.models.signals import post_save from django.dispatch import receiver # Unrelated models omitted... class Student(models.Model): """Model representing a student""" first_name = models.CharField(max_length=50, help_text="Student first name.") last_name = models.CharField(max_length=50, help_text="Student last name.") course = models.ManyToManyField(Course, help_text="Select courses student is enrolled in.", blank=True, default='') def __str__(self): """String representing the Model object""" return self.last_name + ", " + self.first_name def get_absolute_url(self): """Returns the url to access a detailed record for this student""" return reverse("checkin-student-detail", args=[str(self.id)]) class StudentMeeting(models.Model): """Model representing a check-in appointment""" instructor = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True, default='') student = models.ForeignKey(Student, help_text="Student Name.", on_delete=models.CASCADE, null=True) appointment_date = models.DateField("Date", default=timezone.now) attended_meeting = models.BooleanField() missing_work_amount = models.IntegerField(default=0) narrative = models.TextField(blank=True, default='') current_courses = models.ManyToManyField(Course, blank=True, default='') def __str__(self): """String representing the Model object""" return str(self.appointment_date) + ": " + self.student.last_name + ", " + self.student.first_name @receiver(post_save, sender=StudentMeeting) def set_current_courses(sender, instance, created, **kwargs): if created: instance.current_courses.set(instance.student.course.all()) The vary last line …