Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Password Change
Step 1: I logged into the Django Admin Step 2: Clicked in Password Change in Admin Step 3: Entered the Old Password and New Password Step 4: Clicked the Change My password button The password is being successfully changed in the database. But, I'm getting the following error: Environment: Request Method: GET Request URL: http://localhost:8000/admin/password_change/done/ Django Version: 2.2.24 Python Version: 3.7.10 Installed Applications: ['material.admin', 'material.admin.default', 'nested_inline', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'softdelete', 'reversion', 'actstream', 'rest_framework', 'rest_framework.authtoken', 'valital.api.apps.ApiConfig', 'cacheops', 'corsheaders', 'drf_yasg', 'storages', 'djmoney', 'mail_factory', 'mjml'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'reversion.middleware.RevisionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /usr/local/lib/python3.7/site-packages/material/admin/templates/registration/password_change_done.html, error at line 3 Invalid block tag on line 3: 'translate', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? 1 : {% extends "admin/base_site.html" %} 2 : {% load i18n %} 3 : {% block userlinks %}{% url 'django-admindocs-docroot' as docsroot %}{% if docsroot %}<a href="{{ docsroot }}"> {% translate 'Documentation' %} </a> / {% endif %}{% translate 'Change password' %} / <a href="{% url 'admin:logout' %}">{% translate 'Log out' %}</a>{% endblock %} 4 : {% block breadcrumbs %} 5 : <div class="breadcrumbs"> 6 : <a href="{% url 'admin:index' %}">{% translate 'Home' … -
validating uniqueness of many to many model by foreign key model field
I have 3 model: class Citizenship(models.Model): name = models.CharField() class Destination(models.Model): name = models.CharField() class RestrictionGroup(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) citizenship = models.ManyToManyField(Citizenship) I want my citizenship be unique based on related destination. If my destination is England, and if I have 5 restriction groups, each restriction groups related to destination have to unique citizenship. for example, at this image Greece is duplicated, but I need unique countries for destination country. so how can validate this and return back friendly error message? any help appreciated, thanks advance. -
Django-allauth apple login KeyError id_token
I am using django-allauth and django-rest-auth for authentication. I have implemented google login with these too. This is my urls url('rest-auth/apple/$', AppleLogin.as_view(), name='apple_login') and this is my views.py file from allauth.socialaccount.providers.apple.views import AppleOAuth2Adapter from rest_auth.registration.views import SocialLoginView class AppleLogin(SocialLoginView): adapter_class = AppleOAuth2Adapter serializer_class = CustomSocialLoginSerializer def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs) and this is my serializers.py file from rest_auth.registration.serializers import SocialLoginSerializer class CustomSocialLoginSerializer(SocialLoginSerializer): is_advertiser = serializers.BooleanField(required=False, default=False) def validate(self, attrs): attrs = super().validate(attrs) user = attrs['user'] if attrs.get('is_advertiser'): user.is_advertiser = True user.save() return attrs This is my settings.py file SOCIALACCOUNT_PROVIDERS = { 'apple': { "APP": { "client_id":'KEY GOES THERE', # APP ID "secret": 'APPLE SECRET KEY GOES THERE', "key": 'APPLE KEY GOES THERE', # The certificate you downloaded when generating the key. "certificate_key": """-----BEGIN PRIVATE KEY----- MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg806TKaQPgPJ7jj9e AFDJSKJFOW8495U93453SDVWFEOWI5U3405U34059U3450I304534095I34095I3 Mo4LCUa2GZhKDO2qHehLbAASDFSDFKJLKREKlok6MvuI8riC6xdnPGEcUp4 z5ihhVbY -----END PRIVATE KEY----- """ }, }, } above setup is straightforward But it's firing me this error KeyError at /rest-auth/apple/ 'id_token' Here you go for traceback ile "/home/py/.local/share/virtualenvs/backend-sje3MIgt/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation 422. value = self.validate(value) File "/home/py/Desktop/kidgistics/backend/home/api/v1/serializers.py" in validate 116. attrs = super().validate(attrs) File "/home/py/.local/share/virtualenvs/backend-sje3MIgt/lib/python3.7/site-packages/rest_auth/registration/serializers.py" in validate 118. social_token = adapter.parse_token({'access_token': access_token}) File "/home/py/.local/share/virtualenvs/backend-sje3MIgt/lib/python3.7/site-packages/allauth/socialaccount/providers/apple/views.py" in parse_token 92. identity_data = self.get_verified_identity_data(data["id_token"]) Exception Type: KeyError at … -
How to use bulk_create in django
I just learned that I can use bulk_create in django so that the query wont be too long and it will be fast rather than using for loop to add data to the database one by one. The problem is, I don't know how to do it, please help me. views.py: if request.method == "POST": csv_form = UploadCSVFileForm(request.POST or None, request.FILES or None) if csv_form.is_valid(): period = csv_form.cleaned_data.get('period') print(period) period = SchoolPeriod.objects.get(period = period) # save csv file uploaded_file = csv_form.cleaned_data.get('file_name') save_csv = GradeCSVFile.objects.create(file_name= uploaded_file) csv_file = GradeCSVFile.objects.get(grades_uploaded= False) #read csv file with open(csv_file.file_name.path, 'r') as file: reader = csv.reader(file) for i, row in enumerate(reader): if i == 0: pass else: subject = Subject.objects.get(subject_name = row[3]) profile = get_object_or_404(StudentProfile, LRN_or_student_number = row[0]) ######### **THIS IS THE PART WHERE I NEED THE `BULK_CREATE` ** ############ new_grade = StudentGrade.objects.create( student=profile.student.student, period = period, subject = subject, grade = row[4], ) csv_file.grades_uploaded = True csv_file.save() -
How to ensure sending ajax request happen after mouseevents?
I track mouse movement on several elements on an HTML page. I used this [question][1] for the mouse movement function. Then I send how much a user spent over an element using an ajax POST request to a Django view which save it into the db every time there is a new movement. Now I am able to do that, except I noticed that every now and then one of the elements store the time stamp rather than how many seconds. it seems that js is messing up the calculation here: mouseoverTime = currentTime.getTime() - mouseenterTime; it seems that mouseenterTime doesn't get updated with the mouseenter event and remains zero, hence mouseoverTime becomes currentTime.getTime() I am confused because this doesn't happen all the time and I am not getting any errors. could that be because of a problem when the page is loaded? or do I need to put the mouseenterTime variable inside the function? here is my js code: d3.select(window).on('load', function () { let mouseenterTime = 0; $(document).on('mouseenter mouseleave', '#gender_question', function (evt) { let currentTime = new Date(); if (evt.type === 'mouseenter') { mouseenterTime = currentTime.getTime(); } else if (evt.type === 'mouseleave') { mouseoverTime = currentTime.getTime() - mouseenterTime; $.ajax({ … -
How to use axios to post to my Django Rest server?
I am getting a 403 error when trying to post to my Django server from my frontend mobile app. However, it works totally fine when I post with the form on the browser. I managed to register once using my frontend mobile app, but ever since then, I get this 403 error. I've tried both signing up and logging in. Here is the error I get in my Django backend terminal: Bad Request: /rest-auth/registration/ [16/Aug/2021 14:51:37] "POST /rest-auth/registration/ HTTP/1.1" 403 58 Here is my settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'users', ] SITE_ID = 1 .... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } ACCOUNT_EMAIL_VERIFICATION = 'none' Here is my front end (register.js): axios .post("http://127.0.0.1:8002/rest-auth/registration/", { username: "tester1234@gmail.com", email: "tester1234@gmail.com", password1: "tester1234@gmail.com", password2: "tester1234@gmail.com", }) What am I doing wrong? I just want users to be able to register, log in, and log out of my app. -
Django AttributeError (object has no attribute...)
I have such a href in my html template: <link><a href="{% url 'delete_all' %}">Delete all texts</a></link> Here's the view, attached to 'delete_all' url: def delete_all_texts(request): Text.objects.all().delete() return HttpResponse('All texts deleted') But when this href is clicekd I get such an error message: AttributeError at /delete_all 'str' object has no attribute 'get' P.S: Here's my Text model: class Text(models.Model): title = models.TextField(null=True) text = models.TextField(null=True) language = models.ForeignKey('Language', null=True, on_delete=models.PROTECT, verbose_name='Язык') class Meta: verbose_name_plural = 'Текст' verbose_name = 'Текст' ordering = ['title', 'text'] def __unicode__(self): return self.title def __str__(self): return str(self.title) + '\n' + str(self.text) + '\n' -
replacing images inside MEDIA_ROOT doesn't change the images in live server
i have avatar.png inside my /media/ folder and after a created some profiles i went and replaced the avatar.png with another with same name and it seems it doesn't change it at all, how to replace it all over django server ? -
How can I show Subset from multiple model in Django Custom View with the UI same as other models?
I have created a Custom view in Admin Panel with this code in admin.py. I want the sometemplate.html template to have the information in the same UI format just like when I click on another model in the admin panel, and that information needs to be a combination of rows from multiple models. So, the data is displayed in this custom view will have all the entries from multiple models with valid = False How can I do that in my custom view of Django admin? class DummyModelAdmin(admin.ModelAdmin): model = DummyModel def my_custom_view(self,request): # return HttpResponse('Admin Custom View') context = dict( ) return TemplateResponse(request, "webapp/sometemplate.html", context) def get_urls(self): view_name = '{}_{}_changelist'.format( self.model._meta.app_label, self.model._meta.model_name) return [ path('my_admin_path/', self.my_custom_view, name=view_name), ] admin.site.register(DummyModel, DummyModelAdmin) sometemplate.html code: {% extends "admin/base_site.html" %} {% block content %} {% endblock %} -
Errors when get with axios in a django + vue app
I created an app with vue as front and django as back, now i try to make them communicate with axios, I've got this in my settings.py ... CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ... ] MIDDLEWARE = [ ... 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware' ] if I go to localhost:8000/API/questions I can POST new data or GET. In frontend, i've got this in an API.js file import axios from 'axios' const api = axios.create({ baseURL: 'http://127.0.0.1:8000/API/', timeout: 1000, withCredentials: false, headers: { 'Access-Control-Allow-Origin' : '*', 'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS', } }); export const getQuestions = async function() { const response = await api.get('questions/'); return response.data; } When I call my function, this error shows up Access to XMLHttpRequest at 'http://127.0.0.1:8000/API/questions/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. GET http://127.0.0.1:8000/API/questions/ net::ERR_FAILED Uncaught (in promise) Error: Network Error at createError (createError.js?2d83:16) at XMLHttpRequest.handleError (xhr.js?b50d:84) -
multi-selecting from dynamic dropdownlist in django
I come from MSAccess with extensive VBA. In a questionnaire I create dynamic dropdownlists. From the displayed list (1-15 items) users can select a number of items (kind of priority-sublist). The choices should be registered for later use in a couple of reports. How do I do this in Python/Django? -
How to send a simple data by Ajax jQuery to views.py in Django?
I want to send a simple data (a number) from home.html to a function in views.py by using Ajax jQuery. But it seems that the the function is not being called. home.html: I get the success response correctly. I see the tagID on the success notification. I want to see that in my views.py ... function GetInfo(e){ document.getElementById("test3").innerHTML = e.target.myCustomID; var tagID = e.target.myCustomID; $.ajax({ url: 'Ajax1', type: "POST", data: { 'tagID': tagID, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function (data) { alert ("Congrats! You sent some data: " + tagID);} , error: function() { alert ("Something went wrong"); } })}; views.py: I want to see that this function is called by the ajax. So if the command print ("AAAAAAAAAAAAA") works, I am happy! ... @csrf_exempt def Ajax1(request): print ("AAAAAAAAAAAAA") if request.is_ajax() and request.POST(): print("BBBBBBBBBBBBB") TagID = request.POST.get('tagID', None) else: raise Http404 my_app/urls.py urlpatterns = [ url(r'', views.home_map, name="home"), url(r'^ajax/$', views.Ajax1, name="Ajax") ] urls.py urlpatterns = [ path(r'', include('my_app.urls')), path('admin/', admin.site.urls), path(r'^ajax/$', Ajax1, name='Ajax') ] would you please let me know what I am missing? thanks -
djoser not sending activation email
im trying to get djoser or simple jwt(not sure which is supposed to send) to send an activation link after user registration but it doesnt seem to be doing anything. I registered my email account with an app password. Any help will be appreciated thanks. my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'kingrafiki61@gmail.com' EMAIL_HOST_PASSWORD = '*********' EMAIL_USE_TLS = True DJOSER = { 'LOGIN_FIELD':'Email_Address', 'USER_CREATE_PASSWORD_RETYPE':True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION':True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True, 'SEND_CONFIRMATION_EMAIL':True, 'SET_USERNAME_RETYPE':True, 'SET_PASSWORD_RETYPE':True, 'PASSWORD_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL':'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL':True, 'SERIALIZERS': { 'user_create': 'nerve.serializers.UserCreateSerializer', 'user': 'nerve.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } -
Downloading files using checkboxes in Django?
I have created a model using Django & am displaying its contents in form of a table on a HTML page. Each row of this table has download links for different files. I have also added a checkbox to each row of this table. I want to create a download button which will download the files corresponding to those rows whose checkboxes have been ticked . Is it possible to do this using django alone or do I need to use something else like jquery? -
format string before passing it to another filter
I have a filter which accepts string, and i should format this string with another filter before passing it to first filter. I know that I can do it with help of "with block", but this code is around whole code base and i was looking for more neat solution. May be there is a way to control order of operations in django template language Here what i have: # html file {{ params|get:'route[{}][input_address]'|format_string:0 }} # filters @register.filter def format_string(text, fmt): return text.format(fmt) @register.filter def get_list(querydict, item): if isinstance(querydict, QueryDict): return querydict.getlist(item) return querydict.get(item) I have also tried to take that in brackets but there is syntax error -
Why is my custom django-admin command not running on Heroku?
I have created a custom django-admin command that finds the average price for an item with prices from various retailers. The average price is saved as an object in my PriceHistory model to form data points for product history charts. My Command python manage.py average works on my computer and it also works on the Heroku CLI, however, Heroku Scheduler is not running the command and no data is being saved, even though Heroku Scheduler works fine with my other Custom Commands. Useful Docs: https://devcenter.heroku.com/articles/scheduling-custom-django-management-commands average.py class Command(BaseCommand): def handle(self,*args,**options): try: products = Product.objects.all() for i in range(len(products)): total = 0 count = 0 self.stdout.write(self.style.SUCCESS(products[i]._id)) array = RetailerProduct.objects.filter(product=products[i]) for item in array: #print(item.price) if item.price != 0.00: total += item.price count += 1 try: mean = total/count except ZeroDivisionError: mean=0.00 self.stdout.write(self.style.SUCCESS(products[i].name+" : £"+str(mean))) save_mean = PriceHistory(price=round(float(mean),2),product=products[i]) save_mean.save() except: self.stdout.write(self.style.ERROR(error)) return self.stdout.write(self.style.SUCCESS('Successfully calculated all averages')) return Product Model: class Product(models.Model): name = models.CharField(max_length=30,null=True,blank=True) brand = models.CharField(max_length=20,null=True,blank=True) image = models.ImageField(null=True,blank=True) _id = models.AutoField(primary_key=True, editable=False) Retailer Product Model: class RetailerProduct(models.Model): url = models.CharField(max_length=300,null=True,blank=True) price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) difference = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE) available = models.BooleanField(default=False) _id = models.AutoField(primary_key=True, editable=False) product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='sources') Price History Model: class PriceHistory(models.Model): price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2) product … -
Django: How to create a mixin to set common attributes for every model?
I have a model mixin that sets created_at, created_by, updated_at and updated_by which I then inherit to most of the models in my project. This model mixin works fine. Obviously setting created_at and modified_at is very easy due to auto_now_add and auto_now. class Timestampable(models.Model): created_at = models.DateTimeField( auto_now_add=True, db_index=True, verbose_name=_('created at') ) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="created%(app_label)s_%(class)s_related", on_delete=models.SET_NULL) updated_at = models.DateTimeField( auto_now=True, db_index=True, verbose_name=_('updated at') ) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="updated%(app_label)s_%(class)s_related", on_delete=models.SET_NULL) class Meta: abstract = True ordering = ['-created_at'] But, what I want is to also create a mixin (or maybe subclass) CreateView and UpdateView to set created_by and updated_by to be self.request.user everywhere those CBVs are used ( I would guess by modifying get_form() or form_valid()). I'll also need to create a similar admin mixin to modify save_model(). I have never created a custom mixin and the things I have found/tried aren't working. For example I got subclassing CreateView working by modifying get_form() but then, I couldn't further modify get_form() in the various class ModelXCreate(...) views I created. Does anybody know how I can achieve this? It'd be super useful to be able to have such a mixin and keep things DRY. -
Django Apache server error. no module named 'psycopg2._psycopg' [Dulicate, but duplicate answers didn't work :(]
I am running ubuntu-server 20 and I am trying to run django deplyments server on it with apache2 and libapache2-mod-wsgi-py3. I was having many errors but i somehow managed to fix them but I am stuck on this error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' psycopg2 and psycopg2-binary are installed in my env. Also I am using python version 3.9. Here are my apache server configs (if you need them) <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ServerName darkzone Alias /static /home/nika/HackerForum/staticfiles <Directory /home/nika/HackerForum/staticfiles> Require all granted </Directory> Alias /media /home/nika/HackerForum/media <Directory /home/nika/HackerForum/media> Require all granted </Directory> <Directory /home/nika/HackerForum/HackerForum> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/nika/HackerForum/HackerForum/wsgi.py WSGIDaemonProcess darkzone python-path=/home/nika/HackerForum python-home=/home/nika/HackerForum/venv WSGIProcessGroup darkzone </VirtualHost> WSGIPythonHome /home/nika/HackerForum/venv WSGIPythonPath /home/nika/HackerForum -
Get all object permissions of a group with Djano guardian
I am using Django Permission to have an object-level permission setting. I am finding it hard to display the permissions under a specific group. Group.objects.get_or_create(name="Admin") admin_group = Group.objects.get(name='Admin) task = Task.objects.get(id=1) assign_perm("view_task", admin_group, task) This will prompt: <GroupObjectPermission: Task1 | Admin | view_task> And I have to get the list of all the permissions under this Admin Group. I tried it this way: admin_group.permissions.all() # output is <QuerySet []> admin_group.permissions # output is auth.Permission.None Is there any way I can list out all the permissions under a specific group? -
How to set a fixed datetime.now() variable in Django using datetime.datetime
I want to have two record dates of a blog post, one is the date the post was created on, and the last time/date the post was updated. But the issues is the date_created variable reset every time I make any changes. ... from datetime import datetime class Post(models.Model): ... date_created = datetime.now() # how to not reset this variable everytime when I update changes to the post? last_edited_date = datetime.now() -
Django - foreign key to ManyToMany (through) fails with SystemCheckError
Using the following relations: class Author(models.Model): pass class Book(models.Model): authors = models.ManyToManyField(to=Author) class Contract(models.Model): work = models.ForeignKey(to=Book.authors.through, on_delete=models.CASCADE) we are trying to have a foreign key point at the through model without explicitly defining it (see also comment by Daniel Roseman in Django using a ManytoMany as a Foreign Key ) This fails with SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: Contract.work: (fields.E300) Field defines a relation with model 'Book_authors', which is either not installed, or is abstract. Book.authors.through is a model that is not abstract. Why does it not work anymore (django 3.2)? -
How do update last message date in Django model
I have two models where users create a post and comment on that post. When users comment this post I want updating last_message date on UserPost model. If there are no comments yet I want the default last_message date to be set to the date the post was created. Models: class UserPosts(models.Model): postTitle = models.CharField(max_length=100, verbose_name="Title") postContent = RichTextField(null=True, verbose_name="Content") created_at = models.DateTimeField( auto_now_add=True, verbose_name="Date of upload") last_message = ????????????????? def __str__(self): return self.postTitle class UserMessages(models.Model): postMessages = RichTextField(null=True, verbose_name="Message") post = models.ForeignKey( UserPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name="Date of upload") I couldn't find anything relevant to this topic in the Django docs, Google, and other sources. -
Django - How to get User_Id from the username String in HTML Template?
I have this HTML form containing an DropDown with All username (Passed in context data like this: users_name = User.objects.values_list('username', flat=True)), when admin select one user, he submit the form (using javascript), and an backup will render a certain table ( All of this are implemented and worked) The form : <form name="searchForm" id="searchForm" method="get"> <div class="input-append"> <input class="span2" id="user" name="user" type="hidden"> <div class="btn-group"> <button class="btn dropdown-toggle" data-toggle="dropdown"> User List <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li onclick="$('#user').val('All'); $('#searchForm').submit()" selected="selected" >All Users</li> {% for user_name in users_name %} <li onclick="$('#user').val('{{ user_name }}'); $('#searchForm').submit()">{{ user_name }}</li> {% endfor %} </ul> </div> </div> </form> What I need now is how can I get the ID of selected user, to use it on an link (a tag) the tag will be Like this : <a href="/CapDelKnowledge/export/{{formId}}/{{user}}/?type=XLS"> export</a> where {{user}} represent the ID of selected user, what can i do ? -
unable to rendered the object key,value using react js
I'm New to react js, Here, We have rendering the objects in table. first we will checking the keys, if it is available it will display the data.. Stored the objects in Claim_details using python and pass it to the frontend {Object.keys(this.state.claim_details).map((e)=>{ return (e != this.state.unique_field && e != "_id")? <tr className="text-center" key={e}> <td style={{lineHeight:"1.5", whiteSpace: "pre-line"}}>{e}</td> <td style={{lineHeight:"1.5", whiteSpace: "pre-line"}}>{convertISODateToApexon(this.state.claim_details[e])}</td> </tr> :"" })} -
How to Add class model data when condition is satisfied in Django
I am using django and have created 2 class models. class Student(models.Model): is_registered = models.CharField(max_length=50, blank=True, null=True) class Attribute(models.Model): student_id = models.ForeignKey(Student, on_deleted=models.SET_NULL, null=True, blank=True) statement = models.CharField(max_length=50, blank=True, null=True) I want to add 'end' to the statement field of the Attribute class model when off is added to the value of the is_registered field of the Studnet class. When you use the update statement, the existing value is changed. How do I add a new line of data? Please help.