Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django-rest-resetpassword to update password in the database
I'm trying to use django-rest-resetpassword to create password reset session in my django app. The programme is returning token already, and when I send post request with the token I get a success message, but the password never enters the django-rest-resetpassword table in the database (Which was created when I migrated). And as such I'm unable to loginh with the new password. Please, is there anything missing from the code? I have the following blocks of code: urls.py path('account/password-reset/', include('django_rest_resetpassword.urls', namespace='password_reset')), views.py @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): # send an e-mail to the user context = { 'current_user': reset_password_token.user, 'user_name': reset_password_token.user.user_name, 'email': reset_password_token.user.email, 'reset_password_url': "{}?token={}".format( instance.request.build_absolute_uri(reverse('password_reset:reset-password-confirm')), reset_password_token.key), 'site_name': "crispy" } # render email text email_html_message = render_to_string('account/user/reset_password.html', context) msg = EmailMultiAlternatives( # title: "Password Reset for {title}".format(title="Account API"), # message: email_html_message, # from: "noreply@example.com", # to: [reset_password_token.user.email] ) msg.attach_alternative(email_html_message, "text/html") msg.send() Templates User/rest_password.html {% load i18n %}{% autoescape off %}Hello from {{ site_name }}! You're receiving this e-mail because you requested to change your password. It can be safely ignored if you did not request a password reset. Click the link below to reset your password. {{ reset_password_url }} {% if user_name %}{% blocktranslate %}In case you forgot, … -
How to change content if the page is requested from a specific url in django?
Say I have two pages one is example.com/login and another page is example.com/admin And when I put the credentials on the login page I get redirected to the admin page. Admin page has a logout button. If I press that button then it redirects me to the login page again. What I exactly want to do is, I want to display a message "Login again" dynamically (I know how to display a message dynamically) but only when user gets redirected from the login page via admin panel. How can I do that? -
Photo does not display in Django
I spent a few hours trying to display the image in Django, I am trying to display a wordcloud in Django. Here's my views.py: import tweepy from tweepy.auth import OAuthHandler from .models import Tweet from .models import Dates from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.shortcuts import render from django.db import models, transaction from django.db.models import Q import os import tweepy as tw import pandas as pd import nltk from .forms import TweetIDForm from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt import pandas as pd from io import StringIO from django import template import urllib, base64 import io import requests consumer_key = 'IkzuYMak76UcXdnL9HabgIfAq' consumer_secret = 'Lt8wrtZ72ayMEcgZrItNodSJbHOPOBk5YnSpIjWbhXpB4GtEme' access_token = '1405021249416286208-GdU18LuSmXpbLTz9mBdq2dl3YqKKIR' access_token_secret = 'kOjGBSL2qOeSNtB07RN3oJbLHpgB05iILxT1NV3WyZZBO' def clean_tweet_id(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TweetIDForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required tweet_id = form.cleaned_data.get("tweet_id") auth = tw.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tw.API(auth, wait_on_rate_limit=True) twtjson = requests.get('https://publish.twitter.com/oembed?url=' + tweet_id + '&omit_script=true') tweets = twtjson.json() tweet = tweets.get('html') ida = tweet_id.split('/')[-1].split('?')[0] identification = int(ida) status = api.get_status(identification) user_name … -
Import model from one app to another app in Django
I am very new to Python and Django so please excuse this "noob" question! I have the following project structure: rr |-rr |-settings.py |-kg |-models.py |-lp |-lpint.py |-manage.py I have omitted all other files and dirs for brevity. The script I am working on is 'lpint.py' and this is not working out: #lpint.py from kg.models import ModelName I get the error: "ModuleNotFoundError: No module named 'kg'". . I have read a lot of SO answers on this and nothing seems to be working. I tried adding this to my lpint.py file: import os os.environ["DJANGO_SETTINGS_MODULE"] = "rr.settings" import django django.setup() And I get this error message: "ModuleNotFoundError: No module named 'rr'" Any input would be greatly appreciated! -
Django - Not Recognizing Javascript File - Problem with Static?
When I try to go to five_day_forecast.html I'm getting the error: 127.0.0.1/:3 GET http://127.0.0.1:8000/five_day/static/capstone/five_day.js net::ERR_ABORTED 404 (Not Found) It's not recognizing my Javascript file but I don't know why. Here is how my files are setup, I'm using Django: five_day_forecast.html currently is just: HELLO <script src="static/capstone/five_day.js"></script> I've tried having all my code there as well, or just this, and it still doesn't work. I don't understand because when I'm on home.html (which calls temp.js file) it works totally fine. And both js files are under static/capstone. I just don't know why it's not recognizing the js file here. -
trying to instantiate the record in a model for CRUD operations in Django getting error "update_user() missing 1 required positional argument: 'eid'
# models.py.......................................... from django.db import models class angelaFormModel(models.Model): First_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.IntegerField() email = models.EmailField(max_length=50) confirm_email=models.EmailField(unique= True) password=models.CharField(max_length=50) confirm_password=models.CharField(max_length=50) def __str__(self): return self.First_name # forms.py.................................................... from django.forms import ModelForm from .models import angelaFormModel from django import forms class angelaFormModel_form(ModelForm): class Meta: model = angelaFormModel widgets = { 'password': forms.PasswordInput(), 'confirm_password': forms.PasswordInput(), } fields = '__all__' class angelaFormModelUpdate_form(ModelForm): class Meta: model = angelaFormModel widgets = { 'password': forms.PasswordInput(), 'confirm_password': forms.PasswordInput(), } fields = ['First_name', 'last_name', 'phone', 'password', 'confirm_password'] # views.py.................................................. from django.shortcuts import render, get_object_or_404, redirect from .forms import angelaFormModel_form, angelaFormModelUpdate_form from .models import angelaFormModel # working def home(request): return render(request, 'home.html') # working def create(request): if request.method == 'GET': return render(request, 'create.html', {'form': angelaFormModel_form, 'message': 'Please, fill the form carefully...'}) else: form = angelaFormModel_form(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') confirm_email = form.cleaned_data.get('confirm_email') password = form.cleaned_data.get('password') confirm_password = form.cleaned_data.get('confirm_password') if email != confirm_email: return render(request, 'create.html', {'form': angelaFormModel_form, 'message': 'Please, fill the form again! Provided email is not matching'}) if password != confirm_password: return render(request, 'create.html', {'form': angelaFormModel_form, 'message': 'Please, fill the form again!, Provided password is not matching'}) form.save() return render(request, 'create.html',{'form': angelaFormModel_form, 'message': 'Bingo! your form hase been submitted.'}) # return render(request, 'create.html') return … -
How to overwrite MinValueValidator error message in Django?
I have a field in the model: my_date = models.DateField('my date', validators=[MinValueValidator(date(2021, 1, 14))], null=True) and when my_date is earlier than 2021-1-14 i get message: Ensure this value is greater than or equal to 2021-01-14 but i want date in format: "%d.%m.%Y" so it should be: Ensure this value is greater than or equal to 01.14.2021 How to change format of date? maybe in forms.py? -
Turn off http buffering between Django and Windows IIS
I've created a web application using Django 3.2.3 and Python 3.6.8. The web app has a long running process so I use the Django yield function to output activity to the browser to keep the user informed. The app worked brilliantly in development until I moved it into production on a Windows server and fronted it with IIS, now the yield function is effectively crippled as IIS buffers the output before returning it to the user. Now they now sit and wait with a blank page for up to a minute and all the output is returned at once. This is a real shame as the app was informative and well presented until this point. Does anyone know of a way that I can disable buffering under IIS when used in conjunction with Python/Django so that the yield function can work again or, a creative way of achieving the same thing without the Django yield function. Thank you. -
Django admin page no reverse match error when adding a model instance
In the admin site, I get a NoreverseMatch error: raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'Main_client_change' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/Main/client/(?P<object_id>.+)/change/$'] Command Prompt: (virtualEnv) C:\Users\maria\Desktop\siteLast\djangoProject>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 05, 2021 - 14:02:52 Django version 3.2.5, using settings 'djangoProject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [05/Jul/2021 14:02:54] "GET /admin/Main/client/add/ HTTP/1.1" 200 14835 Internal Server Error: /admin/Main/client/add/ Traceback (most recent call last): File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner return view(request, *args, **kwargs) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\contrib\admin\options.py", line 1657, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\contrib\admin\options.py", line 1540, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\contrib\admin\options.py", line 1591, in _changeform_view return self.response_add(request, new_object) File "C:\Users\maria\Desktop\siteLast\virtualEnv\lib\site-packages\django\contrib\admin\options.py", line 1182, in … -
DRF - Create Serializer: accepting ForeignKey data with Non-Primary Field value
I am totally new to Django/DRF, and trying to work with Create/Read/Update of a Model. Here are the dummy model/serializers: AddressModel and UserModel: class AddressModel(models.Model): name = models.CharField(max_length=255) street = models.CharField(max_length=255) class UserModel(models.Model): email = models.CharField(max_length=255) address = models.ForeignKey(Address, on_delete=models.PROTECT) And I have BaseSerializer and WriteSerializer: class UserBaseSerializer(serializers.ModelSerializer): email = serializers.CharField(required=True) address = AddressSerializer() class Meta: model = User fields = ['email', 'address'] class UserWriteSerializer(UserBaseSerializer): class Meta(UserBaseSerializer.Meta): read_only_fields = ["created_by"] def create(self, validated_data): return super().create(validated_data) Now the problem is, reading data through BaseSerializer, is working fine, I am able to display User and Address on UI correctly. But having issues with Create/Update. For creating new user from UI, I have a select dropdown for Address, which has some constant values, these constant values are on UI side, it's not getting fetched from Backend. But backend will have related row in database. And the issue is, I am not sending primary key of the address, I am sending name field of the address in the post call, so how can I still handle name field on Create serializer to store correct address, and return it in success? validated_data in create method does not contain Address instance. It's omitting that, may be … -
Docker doesn't refresh code inside it when I pull my backend repo
I'm getting this issue when I deploy my code it works fine. But when I pull the main branch again then the code in my repo is the latest but not inside the docker container. I know it's because the volume is already created but I want them to sync whenever I pull new changes. so this is my main docker-compose.prod.yml file: - version: '3' services: django: build: context: ./ dockerfile: docker-compose/django/Dockerfile.prod expose: - 8000 volumes: - static_volume:/app/django/staticfiles environment: CHOKIDAR_USEPOLLING: "true" stdin_open: true tty: true env_file: - ./.env.prod nginx-proxy: container_name: nginx-proxy build: nginx restart: always ports: - 443:443 - 80:80 volumes: - static_volume:/app/django/staticfiles - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - django nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy volumes: static_volume: certs: html: vhost: Then I have my Dockerfile.prod: - ########### # BUILDER # ########### # pull official base image FROM python:3.9.1-buster as builder # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apt-get update && apt-get -y install libpq-dev gcc && pip install psycopg2 && apt-get -y install nginx # lint RUN pip install … -
If statement in table in django-templates
say we have table in template <table class="table"> <thead> <tr> <th>Status</th> </tr> </thead> <tbody> {% for student in students %} <tr> {% if {{student.academic_status}}=="promoted" %} <td class=text-success>promoted</td> {% endif %} </tr> {% endfor %} </tbody> </table> So is it possible using if statement in table in django-templates -
Question related to MySQL , html,css,js,django
Hi I was making a website but when I decided to use MySQL with django as database I had question from where do you connect your MySQL to your website while hosting your website,is it in the server or you should have a api or what ? Please help if you can -
Django Paypal integration - Rendering button not working when changing language
I've integrated Paypal to my website and everything worked as expected. However when i added a new language (greek) i got a problem when pressing pay with paypal button. When change back to english everything works and button is rendering with no probs. The error i got from paypal is: Since is the first attempt to work with paypal i would appreciate any help if you can give me any hint on the below error or any idea on how to troubleshoot. Many Thanks -
I am confused when i should use these
I am really confused about when I should use these, urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django - how to check if email is already exists
I need to show error message if email is already exists, but I can't check if new customer trying to enter used email. I am using UserChangeForm. forms.py class UserChangeForm(forms.ModelForm): class Meta: model = Account fields = ('email', 'fname', 'lname', 'phone','bday', 'country', 'gender','picture') # email = forms.CharField(widget=forms.EmailInput(attrs={'class':'form-control'})) # fname = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Name'})) # lname = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Surname'})) phone = PhoneNumberField(widget=PhoneNumberPrefixWidget(initial='GE'), required=False) phone.error_messages['invalid'] = 'Incorrect international code or Phone number!' # bday = forms.CharField(widget=DatePickerInput(attrs={'class':'form-control', 'placeholder':'Birth Date'})) # country = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Country'})) # gender = forms.ChoiceField(choices=Account.GENDER_CHOICES, widget=forms.Select(attrs={'class':'regDropDown'})) # picture = forms.FileField(widget=forms.ClearableFileInput(attrs={'class':'form-control'})) def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] views.py @login_required def edit_profile(request, id): account = Account.objects.all() # context['DATA_UPLOAD_MAX_MEMORY_SIZE'] = settings.DATA_UPLOAD_MAX_MEMORY_SIZE user = Account.objects.get(id=id) form = UserChangeForm(instance=user) if request.method == "POST": form = UserChangeForm(request.POST, files=request.FILES, instance=user) if form.is_valid(): for info in account: if info.email == form.email: messages.warning(request, 'email already exists.') data = form.save(commit=False) data.is_active = True data.save() return redirect('account:editprofile', id) context = {'form':form, 'user':user} return render(request, 'edit_profile.html', context) I saw some examples but they don't work in my case as I do. Also, I find … -
There Is No Django HTML language
Hay, i'm learning python, and in The Django Tutorial: While Using Django Templates To View Something in the Server..in the html File When I Try To Select The Django Html Language it doesn't Exist: Like This: enter image description here OS : Windows 7 64bit Python Version: 3.8.10 Django Version : 3.2.5 VS Code Version : 1.57.1 I Wish Someone Can Help. -
What should I add in my views.py if I want to accept complaints from different users in my complaint management system in django
I am making a complaint management system where different users can log in and add complaints to the system. I need to make a page where the user can add complaints that will be saved in the admin panel but idk how to do it. I have created the model and the template but idk what else to add in the views or the forms. I've tried a bunch of different things but none seem to work. can someone please tell me how to do it? Models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title Template: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="email" class="form-control col-lg-10 comp-title-field" placeholder="Complain title"> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <textarea class="form-control comp-textarea" rows="7" placeholder="Enter text here"></textarea> <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" class="btn btn-secondary save-btn" value="submit"><i class="fas fa-save"></i> Save</button> </form> </div> It needs to look like this: Please help me with this... I've been at this the whole day and Idk what else … -
How to use another template engine in Django
I want to create an engine that i will later use when working with Template instances. I do not want to define it in the settings due to the fact that the logic defined in it should not be distributed everywhere, but only in specific cases. Here's what I did: from django.template.engine import Engine class ModelEngine(Engine): def find_template(self, name, dirs=None, skip=None): # some another logic to get a template instance ... engine = ModelEngine() # Usage template_code = "{% include \"some_template.html\" %}" Template(template_code, engine=engine).render(Context()) Is this solution correct? Is there something wrong with not inheriting from BaseEngine, but from Engine? If yes, please advise something. -
Django failed to insert data that has a foreign key relation
I have two tables: Company and Address. The Company table has the basic contact information of the company, and the Address contains the address and geolocation of the company. These two tables are connected with a foreign key named "company_name," which is neither a primary key of both tables. I inserted some mock data of a company named "FF2" into the company table, it went great. However, when I attempted to insert "FF2" with its mock address into the Address table, I failed and received this: company_name: ["Incorrect type. Expected pk value, received str."] I tried every solution I found online, but none of them worked. Please help and be specific as possible, thank you so much!! model.py: class Address(models.Model): city = models.CharField(max_length=200) state = models.CharField(max_length=200) zip = models.CharField(max_length=20) address1 = models.CharField(max_length=200) address2 = models.CharField(max_length=200, blank=True, null=True) company_name = models.ForeignKey('Company', models.DO_NOTHING, db_column='company_name') lat = models.DecimalField(max_digits=50, decimal_places=6) long = models.DecimalField(max_digits=50, decimal_places=6) class Meta: managed = False db_table = 'address' class Company(models.Model): company_name = models.CharField(unique=True, max_length=200) contact_name = models.CharField(max_length=100) phone = models.CharField(max_length=100) email = models.CharField(max_length=100) website = models.TextField() class Meta: managed = False db_table = 'company' views.py: class AddressView(APIView): serializer_class = AddressSerializer def get(self, request): address = [ {"city": address.city, "state": address.state, … -
how to validate wehther the URL given is from a specific domain or not in django
I have a model: class Profile(models.Model): social_github = models.URLField(blank=True, null=True) social_twitter = models.URLField(blank=True, null=True) social_linkedin = models.URLField(blank=True, null=True) social_youtube = models.URLField(blank=True, null=True) I want to validate the URL to their respective domain for example, the user should only be able to submit the URL of the domain `GitHub in the Github field -
Multiple forms in one Django class-based view with one submit button
I have 2 models, User and Profile. User is Django's baked-in user model, and has a username, and the email the user used to sign up. Profile is the model shown below: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True, null=True) bio = models.TextField(blank=True, null=True) email = models.EmailField(blank=True, null=True) def __str__(self): return f'{self.user.username}\'s Profile' def get_absolute_url(self): return reverse('profile-detail', kwargs={'pk': self.user.pk}) The detail view for these profiles can be accessed using the following URL pattern: # ... path('profiles/<int:pk>', user_views.ProfileDetailView.as_view(template_name='users/profile.html'), name='profile-detail'), # ... What I want to do is to create an update view that allows a user to update both their User details, and their Profile details, with a URL pattern that looks like this: path('profiles/<int:pk>/update', user_views.ProfileUpdateView.as_view(template_name='users/profile_form.html'), name='profile-update'), I know that such an update view can be created for one model using Django's generic UpdateView, but I haven't been able to figure out how I can accomplish this for 2 models. -
How to grey out a button after buttonpress in Django until the associated function returns
When I click on my button an associated function in my views.py is executed. After execution a result page is rendered. However, if I click on the button multiple times the website shows a runtime error: RuntimeError: main thread is not in main loop To avoid this error and unnecessary parallel execution I want to grey out (disable) the button on buttonpress and make it active after the result page is shown (result page extends the normal page, so the button is still there). How do I achieve this? -
How do I use a field in another HTML page in my current HTML page's field to carry out a calculation using JS? It's a Django project
I have three models, Student, Camp, Activity: class Student(models.Model): id_pattern = RegexValidator(r'BSK\/[0-9]{2}\/[0-9]{4}', 'Enter Your ID properly!') student_id=models.IntegerField(primary_key=True, validators=[id_pattern]) name=models.CharField(max_length=70) roll_number=models.IntegerField(max_length=3) def __str__(self): return self.student_id class Camp(models.Model): student_id=ForeignKey(Student, on_delete=CASCADE) batch=models.CharField(max_length=10, default=None) fee=models.DecimalField(max_digits=7, decimal_places=2) class Activity_type(models.Model): activity_type=models.CharField(max_length=20, blank=True) def __str__(self): return self.activity_type class Activity(models.Model): student_id=ForeignKey(Student, on_delete=CASCADE) activity_type=ForeignKey(Activity_type, on_delete=CASCADE) discount=models.DecimalField(max_digits=4, decimal_places=2) final_amount=models.DecimalField(max_digits=7, decimal_places=2) The respective views: def student_view(request): if request.method=='POST': fm_student=StudentForm(request.POST) if fm_student.is_valid(): fm_student.save() fm_student=StudentForm() return render(request, 'account/student.html', {'student_form':fm_student}) else: fm_student=StudentForm() return render(request, 'account/student.html', {'student_form':fm_student}) def activity_type_view(request): if request.method=='POST': fm_activity_type=Activity_Type_Form(request.POST) if fm_activity_type.is_valid(): fm_activity_type.save() fm_activity_type=Activity_Type_Form() return render(request, 'account/activity_type.html', {'activity_type_form':fm_activity_type}) else: fm_activity_type=Activity_Type_Form() return render(request, 'account/activity_type.html', {'activity_type_form':fm_activity_type}) def activity_view(request): if request.method=='POST': fm_activity=ActivityForm(request.POST) if fm_activity.is_valid(): fm_activity.save() fm_activity=ActivityForm() return render(request, 'account/activity.html', {'activity_form':fm_activity}) else: fm_activity=ActivityForm() return render(request, 'account/activity.html', {'activity_form':fm_activity}) def camp_view(request): if request.method=='POST': fm_camp=CampForm(request.POST) if fm_camp.is_valid(): fm_camp.save() fm_camp=CampForm() return render(request, 'account/camp.html', {'camp_form':fm_camp}) else: fm_camp=CampForm() return render(request, 'account/camp.html', {'camp_form':fm_camp}) Now, I want to use JavaScript to calculate the final_amount (Activity class/model) field's value but the basis for that calculation would be the fields, fee from Camp model, which will be on a separate HTML page, and activity_type and discount fields of Activity model. So how do I do that? I can capture the elements on the single page, but how do I use fee field's value and activity_type and discount … -
Multiple file uploading in django with session management
I am trying to use the multiupload2 library along with form wizard in django. The issue is that the input field tends to replace the fields on new files being selected and I also need the cancel/delete functionality on the input fields. In order to maintain the input field states,I can use ajax but that requires me to trigger the set_step_files function of the form wizard which I can't because ajax requires static methods, same goes for the delete functionality. Is there a way to handle this without using ajax?