Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The current path, book/1/2/3/4/5/6/, didn’t match any of these
I've Created a view urlpatterns = [ path('book/<suffix>/', views.bookview, name='bookDetail')` ] what i want if someone hits url '127.0.0.1:8000/book/1/2/3/4/5/6/' i do not want django to raise an error of The current path, book/1/2/3/4/5/6/, didn’t match any of these. but instead it shows the same view of url book/<suffix>/ which is view.bookview. and somehow pass, suffix after book/ which is 1/2/3/4/5/6/ as arg so that i can access it in my view. -
How to make social media like front page in django
I am trying to make a socialmedia ,i have made profile system where user can upload their respective post but i want to make front page like social media (if any of my followings have uploaded any post i want to see it on my front page ).I have my follower and followngs system. models.py class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) date_of_birth=models.DateField(blank=True,null=True) photo=models.ImageField(default='default.jpg',upload_to='profile_pic') followers=models.ManyToManyField(User,related_name='followers',blank=True) following=models.ManyToManyField(User,related_name='following',blank=True) def __str__(self): return f'{self.user.username},{self.photo}' class Image(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,related_name='images_created') image=models.ImageField(upload_to='images/%d/%m/%y/') description=models.TextField(blank=True) created=models.DateField(auto_now_add=True,db_index=True) users_like=models.ManyToManyField(User,related_name='images_like',blank=True) def __str__(self): return f'{self.image},{self.description}' views.py def dashboard(request): context={} return render(request,'socialapp/dashboard.html',context) def UserRegistration(request): form=UserRegistrationForm() if request.method=='POST': form=UserRegistrationForm(request.POST) if form.is_valid(): new_user=form.save(commit=False) new_user.set_password(form.cleaned_data['password1']) new_user.save() Profile.objects.create(user=new_user) #return HttpResponse(f'Welcome {new_user.first_name} \n Accounted created successfully') #return redirect('/register_done/') return render(request,'registration/register_done.html',{'new_user': new_user}) else: form=UserRegistrationForm() context={'form':form,} return render(request,'registration/UserRegistration.html',context) def user_profile(request,username): user = get_object_or_404(User, username=username) profile = get_object_or_404(Profile, user=user) follower_count=profile.followers.count() following_count=profile.following.count() #photos uploaded user=get_object_or_404(User,username=username) img=user.images_created.all() context={'profile':profile,'user':user,'img':img,'follower_count':follower_count,'following_count':following_count} return render(request,'socialapp/user_profile.html',context) @login_required def editprofile(request): user_form=UserEditForm(instance=request.user) profile_form=ProfileEditForm(instance=request.user.profile) if request.method=='POST': user_form=UserEditForm(data=request.POST,instance=request.user) profile_form=ProfileEditForm(data=request.POST,instance=request.user.profile,files=request.FILES) if user_form.is_valid() and profile_form.is_valid() : user_form.save() profile_form.save() #return HttpResponse('profile saved') messages.success(request, 'Profile updated successfully') else: messages.error(request, 'Error updating your profile') context={'user_form':user_form,'profile_form':profile_form} return render(request,'socialapp/editprofile.html',context) @login_required def imageview(request): form=ImageForm() if request.method=='POST': form=ImageForm(request.POST,files=request.FILES) if form.is_valid(): #cd=form.cleaned_data new_form=form.save(commit=False) new_form.user=request.user new_form.save() return HttpResponse('form submitted successfully') else: return HttpResponse('invalid form') context={'form':form} return render(request,'socialapp/image.html',context) def search(request): search=request.GET['username'] profiles=Profile.objects.filter(user__username__icontains=search) #profile = get_object_or_404(Profile, id=user_id) #follower_count=profile.followers.count() #following_count=profile.following.count() context={'profiles':profiles,} return render(request,'socialapp/search.html',context) … -
django rest social auth custom PIPELINES does not work at all
I create social auth with facebook and google and they work just fine. However, when I user register by the classic django signup I would send them an email to verify their account then i set user.is_email_verified to True. So, it does not make sense to ask user to verify their email if they register via social auth, and I need to set is_email_verified==True in the custom pipeline. Problem: the handle_social_auth function does not work at all. I also set a print function to check if it is working from the console. #settings.py REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'oauth2', 'SDK_URL': '//connect.facebook.net/{locale}/sdk.js', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'first_name', 'last_name', 'middle_name', 'name', 'name_format', 'picture', ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v7.0', 'APP': { 'client_id': env.str('FACEBOOK_CLIENT_ID', ''), 'secret': env.str("FACEBOOK_SECRET", '') } }, 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, 'APP': { 'client_id': env.str('GOOGLE_CLIENT_ID', ''), 'secret': env.str("GOOGLE_SECRET", '') } }, "apple": { "APP": { "client_id": env.str('APPLE_CLIENT_ID', ''), "secret": os.environ.get('APPLE_KEY_ID', ''), "key": os.environ.get('APPLE_KEY_ID', ''), "certificate": SOCIAL_AUTH_APPLE_PRIVATE_KEY, }, } } SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', … -
DRF - Data not getting filtered with django-filters
FilterSet: class FieldFilter(django_filters.FilterSet): class Meta: meta = Field fields = ("table__id","type") List function: def field_list(*, filters=None): filters = filters or {} qs = Field.objects.all() return FieldFilter(filters, qs).qs FilterSerializer: class FieldFilterSerializer(serializers.Serializer): table__id = serializers.IntegerField(required=False) type = serializers.CharField(required=False) View: class FieldList(ApiAuthMixin, APIView): perm_slug = f"{Field._meta.app_label}.{Field._meta.object_name}" def get(self, request): field_filter_serializer = FieldFilterSerializer(data=request.query_params) field_filter_serializer.is_valid(raise_exception=True) fields = field_list(filters=field_filter_serializer.validated_data) serializer = FieldSerializer(fields, many=True) return Response(serializer.data, status=status.HTTP_200_OK) Model: class Field(BaseModel): """ Model for Fields. """ id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) type = models.CharField(max_length=255) # metric or dimension display_name = models.CharField(max_length=255, null=True, blank=True) table = models.ForeignKey( Table, db_column="table_id", on_delete=models.CASCADE ) from_table_column = models.BooleanField(default=True) class Meta: db_table = "fields" verbose_name_plural = "fields" The response from view is not getting filtered by the parameters, it is retrieving all the records from the db. -
Can't run a dev server easily
I'm on Windows 11 and I want to create a website with Django. The terminal that I use is Git Bash and I have a problem when I type the command python manage.py runserver. When I type it, it says: Watching for file changes with StatReloader but it doesn't show the typical: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 02, 2022 - 23:30:39 Django version 4.0.5, using settings 'TrialDebate.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. that I should have. the rest only shows when I press ctrl + c to close the server which, you might guess, is pretty problematic. The thing is that the server works. I just can't access it by copying the link so I run another server and then copy the link that the terminal gave me when I closed the previous server. Right... I don't think I use dockerfiles (I don't even know what it is) Could you tell me how to have the full text by only typing python manage.py runserver and not opening closing and reopening the server again. (pls) -
Python Unit Testing: Custom django exception handler
Is there any way to unit test a custom django REST framework exception handler --> default is exception_handler(exec, context)? I can't seem to find similar questions. Also, is it possible to mock a sys.exc_info()? -
Django - Answer matching query does not exist
I am working on a form builder similar to Google Forms but I came across an error when building the 'Edit response' function. The error stated that the "Answer matching query does not exist." This is my HTML code for the edit response page: 28 {% endif %} 29 {% for question in form.questions.all %} 30 <div class="margin-top-bottom box question-box"> 31 {% if form.is_quiz %} 32 <h1 class="question-title txtClr">{{question.question}} {% if question.required %}<span class="require-star">*</span>{% endif %}</h1> 33 {% else %} 34 <h1 class="question-title txtClr" oncopy = "return false">{{question.question}} {% if question.required %}<span class="require-star">*</span>{% endif %}</h1> 35 {% endif %} 36 {% if question.question_type == "short" %} 37 <input type="text" name="{{question.id}}" class="short-answer" placeholder="Your answer" {% if question.required %} required {% endif %} 38 value="{{response|get_response:question.pk}}"> 39 {% elif question.question_type == "paragraph" %} 40 <textarea name="{{question.id}}" placeholder="Your answer" class="long-answer textarea-adjust" 41 {% if question.required %} required {% endif %}>{{response|get_response:question.pk}}</textarea> 42 {% elif question.question_type == "multiple choice" %} 43 {% for choice in question.choices.all %} 44 <div class="multiple-choice"> 45 {% if response|get_response:question.pk|to_int == choice.pk|to_int %} 46 <input type="radio" name="{{question.id}}" id="{{choice.id}}" {% if question.required %} required {% endif %} value="{{choice.id}}" checked> 47 {% else %} 48 <input type="radio" name="{{question.id}}" id="{{choice.id}}" {% if question.required %} required … -
Will migrations that I make to a django app reflect on the DB that is present in Kubernetes?
I have a Django application and I'm using MariaDB as the database. Both of them have been deployed to a namespace on kubernetes. Now I want to add an additional field, so I made changes in the models.py file in the django app. These changes were made locally - I pulled the code from GIT and just made the changes locally. Normally to apply the changes, I have to run manage.py makemigrations and manage.py migrate and all the changes would've been reflected on to the DB if the DB was present locally. So now my questions are How can I apply the changes to MariaDb that is there on Kubernetes ? Will running manage.py makemigrations and manage.py migrate locally and redeploying the django app to kubernetes solve this issue ? -
Retrieving list of all online users using Django-online-users
I would like to retrieve a list of all users online on my, online meaning they have carried out some sort of activity on the app over the last 2 minutes. I am noticing however, that my list only shows people who have logged in as an admin (atleast from what I am observing). I am using the package django-online-users for this I created a view with a queryset that would retrieve all online users who have carried out some activity on the app class OnlineUsers(viewsets.ModelViewSet): queryset = online_users.models.OnlineUserActivity.get_user_activities(timedelta(seconds=120)) serializer_class = OnlineUsersSerializer My OnlineUsersSerializer class: class OnlineUsersSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' This is my profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) profile_pic = models.ImageField(upload_to='profile/%Y/%m/%d', default='media/placeholder.png', blank=False, null=False) #we are hooking create_user_profile and save_user profile methods to the User model whenever a save event occurs. This kind of signal is called post_save @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I created an API end-point that I would use to retrieve all online users from my React app: path('online_users',OnlineUsers.as_view({'get':'list'}), name='online_users'), Regardless of whether I login with … -
How to serialize a through relationship in django
I have my models here like this class individual(models.Model): individualName = models.CharField(*args) class family(models.Model): familyName = models.CharField(*args) individuals = models.ManyToManyField(individual, through='individualthroughfamily') class individualthroughfamily(OrderedModel): family = models.ForeignKey(family) individual = models.Foreignkey(individual) order_with_respect_to = 'family' class Meta: ordering = ['family', 'order'] Here "OrderedModel" is an open-source app available for Django. So, now I want to serialize the family model such that I can get nested individuals according to the order defined in the third class. But, I can't find my way, and it is getting too confusing. Happy to answer any queries. -
The view home.views.verification didn't return an HttpResponse object. It returned None instead
def verification(request): if request.method != 'POST': return HttpResponse("methode not allowed") else: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse("page_accueil")) def page_accueil(request): return render(request, 'acc.html', {}) -
Return a Model.objects.create in Django
I have this code: def returnInvestment(): investment = Investment.objects.create(field='value') return investment thisInvestment = returnInvestment() I expected this will return my created investment but it produces this error: 'NoneType' object is not iterable I don't know why it's not returning my investment object, but I see it got populated inside my database. WHat could I be missing here? -
Heroku not recognising users
Managed to install Heroku today and it looks like some functionality that work perfectly on my local disk are not recognised on Heroku. On my local version: Users that register can leave a comment through a form. When accessing the form, the user that can select their name from a dropdown list and leave a comment against a specific product. ON the Heroku version: the users that are registered on the app are not listed on the comment form. The list is empty. I am happy to post some code, but not sure where to start and would end up copy/pasting a big chunk of code. Have I done something wrong with the upload? Again, the local verison work perfectly fine. So, it must be due to the transfer from Local to Heroku Any pointers? -
Django Field lookup
I have trouble using objects.filter in Django Field lookup. I have a Django model as shown below in my models.py: class operationOPCSmatcher(models.Model): operationID = models.IntegerField(primary_key = True) operationName = models.CharField(max_length=255, blank=True, null=True) opcsName = models.CharField(max_length=255, blank=True, null=True) opcsCode = models.CharField(max_length=20, blank=True, null=True) class Meta: ordering = ['-operationID'] I am using a field-level look up of my table using the code below in my views.py file: from .models import operationOPCSmatcher def opnotenerOutput(request): context = {} opnote = request.POST.get("opnote") doc = nlp(opnote) context['doc'] = doc #find matching OPCS codes opcsNames = {} for ent in doc.ents: if ent.label_ == "OPERATION": opcsNames = operationOPCSmatcher.objects.filter(operationName__contains=ent.text).values() context['opcsNames'] = opcsNames return render(request, "opnotener-output1.html", context) I am trying to find matching records with "operationName" LIKE ent.text SQL: WHERE operationName LIKE ent.text) I have the following code in my template file opnotener-output1.html: <h2>Operation(s)</h2> <ol> {% for ent in doc.ents %} {% if ent.label_ == "OPERATION" %} <li> <!-- create table--> <table border='1'> <tr> <th>{{ ent.text }}</th> <th>OPCS Name</th> <th>OPCS Code</th> </tr> {% for x in opcsNames %} {% if x.OperationName == ent.text %} <tr> <th></th> <th>{{ x.OpcsName }}</th> <th>{{ x.OpcsCode }}</th> </tr> {% else %} <tr> <th></th> <th>No OPCS codes</th> <th>No OPCS coses</th> </tr> {% endif %} {% … -
how to extract data from queryset in django
i am trying to add reply to my blog project's comments section here is the models.py class Comment(models.Model): blog= models.ForeignKey(Blog, on_delete=models.CASCADE,related_name='Blog_comment') user=models.ForeignKey(User,on_delete=models.CASCADE, related_name='user_comment') comment=models.TextField(default='Your Comment') parent = models.ForeignKey('self', on_delete=models.CASCADE,null=True,related_name='paren_comment') comment_date=models.DateTimeField(auto_now_add=True) here is the replies that i passed to the template through replies key replies=Comment.objects.filter(blog=blog).exclude(parent=None) it's type is <class 'django.db.models.query.QuerySet'> So i am running a loop for comment where i can get comment id by comment.id. In that loop i want to run another loop for replies and compare if their(replies) parent.id is equal to the comment.id; then print them in template under the comment. something like this {% if comment.id == reply.parent.id %} {{reply}} {% endif %} i just want to compare by replies parent id; if they match then allow replies under that comment. how can i do that? should i use some custom template?( kindly ask me if there is more to be explained about this problem) -
Besides DB queries and serialization what could be causing the slow down of my drf view?
I followed this guide on profiling django rest apis https://www.dabapps.com/blog/api-performance-profiling-django-rest-framework/ Their results looked like: Database lookup 0.0090 65.7% Serialization 0.0025 18.2% Django request/response 0.0015 10.9% API view 0.0005 3.6% Response rendering 0.0002 1.5% However, for some reason most of my bottle neck is in the Api view: Database lookup | 0.0006s Serialization | 0.0003s Django request/response | 0.0017s API view | 1.2626s Paginated Response | 0.0701s Response rendering | 0.0003s I know that around half of it is my authentication backend, but what could the other half be? -
How to access Oauth Response from Square URL redirect
I am building a website in Django that utilizes the Square OAuth system. https://developer.squareup.com/docs/oauth-api/overview I am able to access the link they provide, login to my account, redirect to my website with the access code in the URL link. From here I am at a loss at how to actually access the code that is being provided in my redirect from Square. How do i access to code being given to me in the url that I receive from the redirect? -
How do I add reset button for crispy filter.form in Django to reset current selection in filter fields?
I have django-filters fields above django-table2 and I would like to add reset button which would clear values selected in particular filter fields. My code: filters.py class DiaryFilter(django_filters.FilterSet): def trade_win_loss(self, queryset, name, value): if (value == 'Win'): return queryset.filter(netpnl__gt=0) if (value == 'Loss'): return queryset.filter(netpnl__lt=0) if (value == 'BE'): return queryset.filter(netpnl=0) return queryset class Meta: model = Diary fields = ("ticker", "strategy", "position", "entryDate", "netpnl") WIN_LOSS_CHOICES = ( ('Win', 'Win'), ('Loss', 'Loss'), ('BE', 'Break Even'), ) ticker = django_filters.CharFilter(label="Ticker", lookup_expr='icontains') entryDate = django_filters.DateFilter(widget=DateInput(attrs={'type': 'date'})) netpnl = django_filters.ChoiceFilter(empty_label='---------', label="NetP/L", choices=WIN_LOSS_CHOICES, method="trade_win_loss") class DiaryFilterFormHelper(FormHelper): form_method = 'GET' layout = Layout( Div( Div("ticker", css_class="col-6 col-sm-4 col-md-2"), Div("strategy", css_class="col-6 col-sm-4 col-md-2"), Div("position", css_class="col-6 col-sm-4 col-md-2"), Div("entryDate", css_class="col-6 col-sm-4 col-md-3 col-lg-2"), Div("netpnl", css_class="col-6 col-sm-4 col-md-2"), Div(Submit('submit', 'Filter', css_class='btn btn-dark'), css_class="col-2 col-md-2 col-lg-1 block my-auto align-bottom"), Div(Submit('reset', 'Clear', css_class='btn btn-dark'), css_class="col-1 block my-auto align-bottom"), css_class="row" ) ) views.py class DiaryView(LoginRequiredMixin, SingleTableMixin, FilterView): template_name = "diary.html" model = Diary table_class = DiaryTable filterset_class = DiaryFilter table_pagination = { "per_page": 10 } def get_filterset(self, filterset_class): filterset = super().get_filterset(filterset_class) filterset.form.helper = DiaryFilterFormHelper() return filterset html template <div class="col-11"> <div class="text-center justify-content-center align-bottom"> {% crispy filter.form %} </div> {% render_table table %} </div> As I am beginner, I was searching … -
How to render an Image from API that returns a file location Django/React
I am making an e-commerce web app with Django as the backend and React frontend. I am coming across an issue of how to render images saved locally on my machine(via a file path) in react. My API is feeding across a path location to the image but my React app isnt able to access the photo. Any idea how to get the images to render? I have the image saved via my Django model in a imagefield. This is how i am accessing the API in react import React, {useState, useEffect} from 'react' import ListItem from '../components/ListItem' import {Container} from 'react-bootstrap' const ItemsListPage = () => { let [items, setItems] = useState([]) useEffect(()=> { getItems() },[]) //function to ping API for list of store items from django backend let getItems = async () => { let response = await fetch('/api/items') let data = await response.json() console.log('DATA:', data) setItems(data) } return ( <div> <Container> <div className='styles.grid'> {items.map((item, index) => <ListItem key={index} item={item}/> )} </div> </Container> </div> ) } export default ItemsListPage This is my django model from django.db import models from PIL import Image # Create your models here. class StoreItems(models.Model): name = models.CharField(max_length=20) price = models.DecimalField(max_digits= 10, decimal_places=2) color … -
Notify Django Channels websocket from Rest Framework action
My app uses Django Rest Framework for the API. I wanted to add live notifications/status to it. The flow would be User loads page then makes a get API request to load data Websocket connects on page load and subscribes to 'notifications' channel that's in ServerNotifConsumer User clicks a button which sends a POST request to API that does some db stuff that would return success or failure info. Returns status 202 Accepted immediately then processes command. Return info via websocket to all subscribed clients Is there a way from within the DRF viewset action to send anything to the websocket consumer? Or would the best way to go about this be to rewrite the API endpoint to only receive via websocket? (rather not do) -
Long running Celery tasks result in ConnectionResetError: [Errno 104] Connection reset by peer
At my Django application, I use Celery to process very long-running tasks. One of these tasks has to write a record into the database at the very end, to confirm that the process is completed. For some reason if the tasks runs for so long (talking 4 hrs or more here) I get this back: ConnectionResetError: [Errno 104] Connection reset by peer This happens as soon as I trigger a write operation against the Database at the very end of the task, e.g.: Files.objects.filter(pk=files_obj).update ... etc It would be interesting to know why the peer resets the connection (MariaDB in my case). Doesn't Django manage database connections for me using a connection pool? I also checked my Redis config on Django side where in my opinion only these lines really matters: BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 86400} # 24 hrs. CELERYD_TASK_TIME_LIMIT = 86400 # 24 Hrs. CELERYD_TASK_SOFT_TIME_LIMIT = 86400 # 24 Hrs. Isn't there a way to make the function trigger a new connection or so? To me, it seems that the Celery task keeps the SQL connection alive for as long as the task is running. But the DB backend doesn't respect this for so long. This is how I start … -
Django : Add a searchbar to filter the dropdown menu of form.ChoiceField
I want to add a search to filter the items of the dropdown menu because it can contain 100 items depending on the user. How can I add that to my code ? Is it in the view or in the Form. forms.py class SelectClient(forms.Form): ID_Customer = forms.ChoiceField(label="Company :", widget=forms.Select(attrs={'onchange': 'submit();'})) def __init__(self, *args, **kwargs) : self.user = kwargs.pop('user') super(SelectClient, self).__init__(*args, **kwargs) id_client_list = AADJNTGroupAPI.objects.filter(ID_User_id=self.user.id).values_list('ID_Group_id', flat=True) id_client_list = list(id_client_list) client_choices = GroupsAPI.objects.all().filter(ID__in=id_client_list).values_list('UUID_Group','GroupName') self.fields['ID_Customer'].choices = client_choices views.py @authenticated_user def selectcontrat(request) : context = initialize_context(request) form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): uuid_contrat = request.POST.get("ID_Customer") return redirect(reverse('home', args=(uuid_contrat,))) context['form_client'] = form_client return render(request, 'classify/selectcontrat.html', context) html <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'selectcontrat.css' %}"> </head> <body> <div class="selectcontract"> <h2>{{ user.name }}, Bienvenue chez EFID</h2> <div class="imagedroite"> <img src="{% static 'image/logo.svg' %}" alt=""> </div> <div class="contrats"> <h2>Veuillez selectionner un contrat :</h2> <form method="post" id="SelectCompany"> {% csrf_token %} {{ form_client.as_p }} <input type="submit" value="Select"> </form> </div> </div> </body> -
quiz.js:12 Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')
I keep getting this error so this code is responsible for displaying questions on the screen from a JSON response. I also attached my views if needed I have been googling and still can't seem to find anything to help me fix this issue not sure what I am doing wrong I am new to Django and ajax from the backend s://i.stack.imgur.com/kMnJw.png -
Dynamically assign HTML values to django for loop
I want to assign an innerHTML value to a django for loop in my django templates. Currently, when I click on a button, the HTML changes to reflect the innerHTML of the button ("individual_project_container"). I then want to run the innerHTML captured in the "individual_project_container" through a for loop in my django template {% for project in projects %} {% if project.project == "HTMLVariable" %} Pass {% else %} Fail {% endif %} {% endfor %} I know that I cannot add a element into my for loop and I am not sure how else to pull the variable. In my template, I am using the following JavaScript to assign the innerHTML of "individual_project_container" to "new_note_header" <script> document.addEventListener('DOMContentLoaded', function() { const nnHead = document.getElementById('new_note_header'); document.getElementById("project_container").addEventListener("click", e => { const tgt = e.target.closest("button"); if (!tgt.matches(".individual_project_container")) return; // not a button nnHead.textContent = tgt.textContent.trim(); }); }); </script> The relevant HTML is below: <div class = "project_container", id = "project_container"> {% for project in projects %} <button class = individual_project_container> {{ project }} </button> {% endfor %} </div> <div class = note_header_container> <div class = new_note_header, id = new_note_header> New Note </div> </div> {% for project in projects %} {% if project.project == … -
send information from a js variable to python
I need to send an object that contains a variable in js, the idea is to be able to send that information to python (I use django) and capture that info to be able to perform the validations that I need from the backend (python) and not from js, how can I do it ? code ajax: function CapturarDatosOrden() { $.ajax({ url: window.location.pathname, type: 'POST', data: { 'action': 'prueba', }, beforeSend: function (jqXHR) { $.xhrPool.push(jqXHR); $(".loader").fadeIn('fast'); }, dataType: 'json', complete: function (jqXHR) { // boton.disabled = false; $('.loader').fadeOut('fast'); var index = $.xhrPool.indexOf(jqXHR); if (index > -1) { $.xhrPool.splice(index, 1); } }, }).done(function (data) { // alert('entro al primer ajax para comparar el tipo de orden y su tecnologia') var info = data.find(data => data.id__ordenes == idOrden); the "info" variable has the object I need to capture in python, the object is something like this: { id__ordenes: "219661981", fk_ot__tipo_orden: "4", fk_bss__contratos: "3257733", otciudad: "1", otdireccion: "----", fk_ot__cc: "1", open_orden: "42588165", instalador: "4320", fk_contratistas__equipos_vendedores: "1", fk_ot__causales: "88" } how can i do it?