Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a conditional context to a function to work in a Django Template
I have a Django form and I am trying show text only once the form is successfully completed I added context so that when the form is successfull successful_submit is true and in the template I add a conditional to only show the text once it is successfully done but everytime I refresh the page or open it is showing even without submitting the form as if there is no if statement so here is what I have done in my views: def add__plan(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = infoForm(request.POST) # check whether it's valid: if form.is_valid(): form.save() _name = form.cleaned_data.get('Name') messages.success(request, f'PDF created for {_name}!') # return redirect('plan:plan') # redirect(reverse('plan:plan', kwargs={'successful_submit': True})) return render(request, 'plan/plan.html', {'successful_submit': True}) # if a GET (or any other method) we'll create a blank form else: form = infoForm() print(form.errors) return render(request, 'plan/plan.html', {'form': form, 'successful_submit': True }) here is the text template: {% if successful_submit %} <!--Grid column--> <div class="col-md-3 mb-4"> <div class="toast fade show" role="alert" aria-live="assertive" aria-atomic="true" > <div class="toast-header"> <strong class="me-auto">MDBootstrap</strong> <small>11 mins ago</small> <button type="button" class="btn-close" data-mdb-dismiss="toast" aria-label="Close" ></button> </div> <div class="toast-body"> Hello, world! This is … -
I don't understand how creating a custom user works
I'm reading the Django 3.2 documentation (custom authentication) and there are some lines of code that I can't understand. I will try to read and explain what I can understand, or what I think I understand. Please correct me if I am wrong Resource link: https://docs.djangoproject.com/es/3.2/topics/auth/customizing/ Code: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # … -
Pass Array to backend using Ajax (Django)
I am learning AJAX and I am having trouble passing an array to the backend. I can pass a simple variable and my code works great, but when I pass an array I am not able to pass the data successfully. My code is below (this works): function add_var() { var aa = 5; $.ajax({ url : "add_variable/", type : "POST", data : { num1 : aa}, success : function(json) { $('#num3').val(json); }, error : function() { console.log("fail"); } }); }; This works just fine and I can pass 5 to the backend. However when I change aa to an array, the function no longer works and returns a 'None' on the Views backend. function add_var() { var aa = [5,10,15]; $.ajax({ url : "add_variable/", type : "POST", data : { num1 : aa}, success : function(json) { $('#num3').val(json); }, error : function() { console.log("fail"); } }); }; Could someone point me in the right direction here? Any help is appreciated! -
Django Paypal Client/Server Data doesn't seem to come to server
I use this implementation for frontend: https://developer.paypal.com/demo/checkout/#/pattern/server my frontend in particular: ............ // Call your server to set up the transaction createOrder: function (data, actions) { return fetch("/createOrder", { method: "post", credentials: "same-origin", headers: { "X-CSRFToken": csrftoken, }, }) .then(function (res) { console.log("res"); console.log(res); return res; }) .then(function (orderData) { console.log("orderData"); console.log(orderData); return orderData.id; }); }, ...................... My backend: def sth(request): logger.error('called') t = gettoken() d = {"intent": "CAPTURE","purchase_units": [{"amount": {"currency_code": "USD","value": "100.00"}}]} h = {"Content-Type": "application/json", "Authorization": "Bearer "+t} r = requests.post('https://api-m.sandbox.paypal.com/v2/checkout/orders', headers=h, json=d).json() logger.error(r) return r Python console (logger.error(r)): {'id': '597275692P0354804', 'status': 'CREATED', 'links': [{'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/597275692P0354804', 'rel': 'self', 'method': 'GET'}, {'href': 'https://www.sandbox.paypal.com/checkoutnow?token=597275692P0354804', 'rel': 'approve', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/597275692P0354804', 'rel': 'update', 'method': 'PATCH'}, {'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/597275692P0354804/capture', 'rel': 'capture', 'method': 'POST'}]} My errorcode in Frontend Uncaught Error: Expected an order id to be passed For me it looks like the response doesn't reacht my frontend. Do i missed something? -
Correct use for post_save signal?
My goal is: Whenever a new Note object is created, I want a row to be inserted in Review, which corresponds to Note via OnetoOne. Whenever Note is modified, I want to modify its corresponding entry in Review in some way. I've currently implemented this (partially) using post_save signal. Although, this feels slightly hacky to me, and I'm wondering if there is a more appropriate method to doing this in Django? Or am I doing it correctly. class Review(models.Model): note = models.OneToOneField(Note, on_delete=models.CASCADE, primary_key=True) easiness = models.DecimalField(decimal_places=3,max_digits=6) interval = models.IntegerField() repetitions = models.IntegerField() due_date = models.DateField(auto_now=False,auto_now_add=False) last_reviewed = models.DateField(auto_now=True,auto_now_add=False) class User(AbstractUser): pass # Create your models here. @receiver(post_save, sender=Note) def append_review(sender, instance, created, **kwargs): blank_review = {'easiness':0,'interval':0,'repetitions':0,'due_date':date.today(),'last_reviewed':date.today()} if created: Review.objects.create(note=instance, **blank_review) else: # modify existing entry instead... -
How to get list of tables and return it with REST API Django?
I'm new with Django. Currently, I want to connect to a postgres database, retrieve the data from a database, and return the value with REST API. I want to return the data dynamically. So, I created a module/function which can retrieve data and return data in json format. The reason why I created a module/function is to retrieve data dynamically from any tables from databases in the future. (Each table might have different columns names). My questions: Is it possible to retrieve the data from a database using a standalone module/function (.py) and return the output from that module/function into REST API? Could you give me the next instructions, what I need to create in Django project to show/return the output data from DbLoader.py into REST API? Thank you very much. My Project tree: C:. ├───DBD │ └───__pycache__ ├───demopage │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───restapi │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ └───src └───__pycache__ This is my standalone function to connect and retrieve data in json, DBD\src\DbLoader.py: import psycopg2 import json class DbLoader: def __init__(self, host, port, dbname, user, password): # postgres self.host = host self.port = port self.dbname = dbname self.user = user self.password = … -
Django form keeps information after submission
I have a Django form and I am trying different options to do 2 things when the form is submitted: Redirect the form back without any information Trigger a Modal after a Django Form is submitted. I have followed this answer but it did not work the form was successfully submitted but the modal did not appear. I have added the context of successful_submit in the views so that it can be triggered after submitting the form Here is part of the HTML Template: <div class="text-center"> <button class="btn btn-primary mt-5" onclick="stepper1.previous()" > Previous </button> <button type="submit" class="btn btn-success mt-5"> Submit </button> <button type="button" class="btn btn-primary" data-mdb-toggle="modal" data-mdb-target="#exampleModal" > Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"> Modal title </h5> <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body">...</div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal" > Close </button> <button type="button" class="btn btn-primary"> Save changes </button> </div> </div> </div> </div> here is the javascript part to show it when it is successfully submitted {% if successful_submit %} <script type="text/javascript"> $(document).ready(function(){ $("#exampleModal").modal('show'); }); </script> {% endif %} here is the views.py def add__plan(request): if request.method == … -
Django Form keeps information even after submission
I have a Django form and I am trying different options to do 2 things when the form is submitted: Redirect the form back without any information Trigger a Modal after a Django Form is submitted. I have followed this answer but it did not work the form was successfully submitted but the modal did not appear. I have added the context of successful_submit in the views so that it can be triggered after submitting the form Here is part of the HTML Template: <div class="text-center"> <button class="btn btn-primary mt-5" onclick="stepper1.previous()" > Previous </button> <button type="submit" class="btn btn-success mt-5"> Submit </button> <button type="button" class="btn btn-primary" data-mdb-toggle="modal" data-mdb-target="#exampleModal" > Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"> Modal title </h5> <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body">...</div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal" > Close </button> <button type="button" class="btn btn-primary"> Save changes </button> </div> </div> </div> </div> here is the javascript part to show it when it is successfully submitted {% if successful_submit %} <script type="text/javascript"> $(document).ready(function(){ $("#exampleModal").modal('show'); }); </script> {% endif %} here is the views.py def add_business_plan(request): if request.method == … -
Django should I take any further step for secure my login system?
I want to know is my current login system secure? Do you think is there any security risk in my login system ? def login_view(request): if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) User = get_user_model() if user is not None and user.is_active: user_mail = user.userprofile.filter(user=user,email_confirmed=True) if user_mail: login(request, user) messages.add_message(request, messages.INFO,'Login Sucessfull') return redirect('members:user-profile-private') elif user.userprofile.filter(user=user,email_confirmed=False): messages.info(request, "we sent account activation link to your mail") -
django cors_allowed_origin setting doesn't work, possible securities impacts
I would like to restrict the consume of my api to some origins, but i'm struggling to make it work even on the most basic scenario. my django key settings are the following: INSTALLED_APPS = [ 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'rest_framework_simplejwt', 'users.apps.UsersConfig', 'trainings.apps.TrainingsConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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', 'users.middlewares.MoveJWTRefreshCookieIntoTheBody' ] DEBUG = True ALLOWED_HOSTS = [] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://0.0.0.0:8080", ] CORS_ALLOW_CREDENTIALS = True as far as i know, all my settings followed the documentation: https://github.com/adamchainz/django-cors-headers but it just doesn't work and i still get CORS issue when the frontend try to make api calls: i know i could set the following and all would work, but i'm afraid of the securities consequences (if any): # CORS_ALLOWED_ORIGINS = [ # "https://example.com", # "https://sub.example.com", # "http://localhost:8080", # "http://127.0.0.1:8080", # "http://0.0.0.0:8080", # ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True my django-app is running as a docker container. The frontend is a different project, using vuejs app listening on port 8080 (without using docker). My concern and question on security is the following: I want to implement the authentication using jwt + cookies, how bad it could … -
Trying to read multipart/form-data in Django
I am learning NextJS/Django, and trying to send some data using FormData that contains some string and an image file to my Django back end but I get the following error: django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None Form: <form className={styles.formContainer} method="post" encType="multipart/form-data" onSubmit={handleSubmit} > <div className="form-group"> <label htmlFor="email" className={styles.text}> Email address </label> <input type="email" className="form-control" id="email" aria-describedby="emailHelp" placeholder="Change email here" onChange={(e) => setEmail(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="image" className={styles.text}> Image </label> <input type="file" className="form-control" id="image" accept="image/*" onChange={(e) => setImageLink(e.target.files[0])} /> </div> <div className="form-group"> <label htmlFor="description" className={styles.text}> Description </label> <textarea className="form-control" id="description" rows="5" onChange={(e) => setDescription(e.target.value)} ></textarea> </div> <button type="submit" className="btn btn-primary" style={{ marginTop: "7px" }} > Submit </button> </form> Submit Button: function handleSubmit(e) { e.preventDefault(); let data = new FormData(); data.append("userID", loggedInID); data.append("email", email); data.append("description", description); data.append("image", imageLink); fetch("http://127.0.0.1:8000/user/edit_profile/", { method: "POST", headers: { "Content-Type": "multipart/form-data", "X-CSRFToken": csrfToken, }, credentials: "include", body: data, }).then((response) => response); } Django View: @parser_classes([FormParser, MultiPartParser]) @csrf_exempt def editProfileView(request): print(request.data) return JsonResponse({}) The Django view is currently unfinished as I cannot read the data in the sent FormData right now. Any help would be appreciated. -
How to interact with python terminal in front end
I'm trying to convert a python project Im working on into a website. I was going to write it in Django/React. The project uses telethon to get messages from telegram, and to start the session, an interactive program runs in the python terminal. Ex: Client.start() ##enter phone number: ##enter passcode we sent: ##enter 2fa password: How would I be able to interact with this from the frontend? -
Login to Django admin with firebase token - what is the most secure way?
I'm building an app with Django (Wagtail) backend for REST API and firebase frontend for auth and firestore. The backend runs on api.domain.com, while the frontend runs on domain.com. I want to give my firebase users the ability to login into Django (Wagtail) admin. I'm trying to implement it in two ways: Easy: I get firebase token on the frontend and send my user to api.domain.com/<<firebase token>> The backend than does all the job to log the user in. The approach works just fine, but I don't like it, since I expose the token in my url. Hard: I make an api GET request from my frontend to backend with firebase token in Authorization Header: axios.get('http://localhost:8000', { withCredentials: true, headers: { Authorization: <<firebase token>> } })... On my backend I respond with the sessionid cookie for the api.domain.com and than redirect the user to my django admin backend. The approach seems to be feasible in theory but I struggle with setting cross-domain cookies via API call. I already tried CORS_ALLOW_HEADERS = list(default_headers) + [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", "http://localhost:8000", "http://127.0.0.1:8000", "http://127.0.0.1", "http://localhost", "http://test.com:8000", "http://test.com" ] CORS_ALLOW_METHODS … -
Django: User vs UserProfile
I'm building a site where we ask users several personal details (birth date, phone number, address, marital status etc. many more). Option 1: User model only. Put these personal fields in class User(AbstractUser) model class User(AbstractUser): birth_date = ... phone_number = ... Option 2: User + UserProfile models: separate login-related data (User) from personal data (UserProfile) like: class User(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField( User, to_field="id", primary_key=True, on_delete=models.CASCADE, related_name="user_profile", ) birth_date = ... phone_number = ... Which one is the best practice? -
update django template without reloading and without javascript
so if I have this code in django template {% for item in items %} <p>{{ item.name }}</p> <hr> {% endfor %} can I update it without refreshing? and wothout javascript? is it possible? -
Django Rest Framework (DRF) how to get value of GenericRelation field?
at my models.py I have a "Movies" model with the following field setup: video_stream_relation = GenericRelation(VideoStreamInfo, related_query_name='video_stream_relation') This GenericRelation field points to the following model class: class VideoStreamInfo(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_type = models.ForeignKey(ContentType, limit_choices_to=referential_stream_models, on_delete=models.CASCADE, verbose_name=_("Content Type")) object_id = models.CharField(max_length=36, verbose_name=_("Object ID")) content_object = GenericForeignKey('content_type', 'object_id') index = models.IntegerField(verbose_name=_("Stream Index"), blank=False) bit_rate = models.IntegerField(verbose_name=_("Bitrate (bps)"), blank=True, null=True, editable=False) codec_name = models.CharField(verbose_name=_("Codec Name"), blank=True, null=True, editable=False, max_length=255) width = models.IntegerField(verbose_name=_("Width"), blank=True, null=True, editable=False) height = models.IntegerField(verbose_name=_("Height"), blank=True, null=True, editable=False) date_added = models.DateTimeField(auto_now_add=True, verbose_name=_("Date Added")) Now the Question is how can I get video_stream_relation.codec_name value in a ModelSerializer like this: class MovieSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=Movies.objects.all()) class Meta: model = Movies fields = ('id', ...) I want to be able to display the codec_name as a API JsonResponse. If needed, this is how my API view currently looks like: @api_view(['GET',]) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([AllowAny]) def movies(request): if request.method == 'GET': obj = Movies.objects.all() serializer = MovieSerializer(obj, many=True) return JsonResponse(serializer.data, safe=False) If I try to add the video_stream_relation field to my MovieSerializer I get back the following error: TypeError: Object of type GenericRelatedObjectManager is not JSON serializable Thanks in advance. -
how to pass the username to the member who fill a form?
i have a form, and i want to pass the user to it to see which logged in user filled it. this is my forms.py from .models import UserInfo from django import forms class InfoForm(forms.ModelForm): class Meta: model = UserInfo fields = ('name', 'age', 'male', 'female', 'height', 'weight', 'BMI', 'BFP', 'phone', 'r_g_weight', 'physical_ready', 'fitness', 'workour_sports', 'others', 'goal_expression', 'body_change', 'noob','low_pro','semi_pro','pro','motivation_level','goal_block', 'change_time','past_sports','injury','work','work_time','wakeup_time', 'work_start_time','sleep_time','daily','hard_to_wake','ready_to_work', 'life_situation','weight_feel','daily_jobs','health_ready','workout_period', 'what_sport','where_sport','home_sport','weekly_time','sport_dislike','daily_food', 'food_quantity','hunger','vitamins','rejims','vegetables','goal_rec', 'stop','rec','heart','chest','chest_month','dizzy','bones','blood','other_reason') and this is my view, i asked for the user with request.user , but the field in db always is empty for username. def userForm(request): if request.method == "POST": form = InfoForm(request.POST) if form.is_valid(): form.user = request.user form.save() return redirect('profile') else: form = InfoForm() context = { 'form':form } return render(request, 'fitness/user_form.html', context) so i have user in my models which has foreign key to my account user = models.ForeignKey(Account,on_delete=models.CASCADE, null=True, blank=True) and this is my template: <div class="container"> <form action="{% url 'user-form' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="submit"> </form> </div> -
Test for removed permission implemented in form_valid() in Django
I cannot understand why my test doesn't pass. I used RequestFactory as mentioned in this answer which, unfortunately, proved useless for me. from io import BytesIO, StringIO from django.contrib.auth.models import User, Permission from django.test import TestCase, RequestFactory from graph.views import NewRecord class NewRecordViewTests(TestCase): def setUp(self): # Every test needs access to the request factory. self.factory = RequestFactory() self.user = User.objects.create_user( username='jacob', email='jacob@example.com', password='top_secret') permissions = [Permission.objects.get_by_natural_key('add_record', 'graph', 'record'), Permission.objects.get_by_natural_key('add_extend', 'graph', 'extend')] self.user.user_permissions.set(permissions) def test_user_permissions(self): """Tests that a user has been denied permission to add a record.""" for i in range(2): img = BytesIO(b'mybinarydata') fp = StringIO('Auxillary info') img.name = 'myimage.jpg' data = {'name': 'New Record', 'description': 'A new record', 'picture': img, 'content': 'Content', 'files': fp, 'author': self.user} request = self.factory.post('/cascades/add', data=data) request.user = self.user response = NewRecord.as_view()(request) self.assertEqual(response.status_code, 403, "Access should be denied") self.assertFalse(self.user.has_perm('graph.add_record'), "Permission remains") self.assertTrue(self.user.has_perm('graph.add_extend'), "No permission to extend a record") The output: ====================================================================== FAIL: test_user_permissions (graph.tests.NewRecordViewTests) Tests that a user has been denied permission to add a record. ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\pavel\Documents\repos\Artcascade\graph\tests.py", line 34, in test_user_permissions self.assertEqual(response.status_code, 403, "Access should be denied") AssertionError: 200 != 403 : Access should be denied views.py: class NewRecord(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, generic.CreateView): model = Record fields = ['name', … -
What are the best practices for getting data through http headers?
I have a backend application where one user can belong to more than one 'organization' and manage these organizations (organization's users' settings vs). I decided to create a middleware where I can catch the organization the user wants to manage and set this organization on the user object. I want to get active organization per request, "request. user. organization". I thought that the react client could send me an HTTP header, and I could get this and make validation. If the user is authorized for this organization, I can set it as an active user organization. What do you think about this approach? -
net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep
I really do not know what exactly I am doing wrong but I need help. My web application works correctly on my localhost but when in production, All external links hosted on AWS are blocked for some reason and I have tweaked everything possible but still no solution. All search, has yielded no results. Failed to load resource MIDDLEWARE MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'core.middleware.SessionTimeoutMiddleware', "django.middleware.http.ConditionalGetMiddleware", "django.middleware.gzip.GZipMiddleware", "django.middleware.locale.LocaleMiddleware", # "core.middleware.SecurityHeadersMiddleware", "django.middleware.security.SecurityMiddleware", "django_permissions_policy.PermissionsPolicyMiddleware", # "core.middleware.ReportUriMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", # "django.middleware.clickjacking.XFrameOptionsMiddleware", "simple_history.middleware.HistoryRequestMiddleware", "django.contrib.admindocs.middleware.XViewMiddleware", 'htmlmin.middleware.HtmlMinifyMiddleware', 'htmlmin.middleware.MarkRequestMiddleware', "django_user_agents.middleware.UserAgentMiddleware", 'waffle.middleware.WaffleMiddleware', ] SETTINGS.PY SESSION_COOKIE_SAMESITE = "Lax" ALLOWED_HOSTS = ["*"] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'HEAD' ] CORS_ALLOW_HEADERS = list(default_headers) + [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'In', 'access-control-allow-origin' ] CORS CONFIGURATION OF BUCKET [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] -
Modal Trigger not working after submitting Django Form
I am trying to show a Modal after a Django Form is submitted. I have followed this answer but it did not work the form was successfully submitted but the modal did not appear. I have added the context of successful_submit in the views so that it can be triggered after submitting the form Here is part of the HTML Template: <div class="text-center"> <button class="btn btn-primary mt-5" onclick="stepper1.previous()" > Previous </button> <button type="submit" class="btn btn-success mt-5"> Submit </button> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"> Modal title </h5> <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body">...</div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal" > Close </button> <button type="button" class="btn btn-primary"> Save changes </button> </div> </div> </div> </div> {% if successful_submit %} <script type="text/javascript"> $(document).ready(function(){ $("#exampleModal").modal('show'); }); </script> {% endif %} </div> Here is the views.py def add_plan(request): if request.method == 'POST': form = infoForm(request.POST) if form.is_valid(): form.save() name = form.cleaned_data.get('Name') messages.success(request, f'PDF created for {name}!') return render(request, 'plan/plan.html', {'successful_submit': True}) else: form = infoForm() print(form.errors) return render(request, 'plan/plan.html', {'form': form}) -
Django crispy-form FormHelper Field() won't accept 'password' as HTML attr type
I am trying to omit writing a widget attr dict for a password field to set the input type="password" (which BTW works). But I'm trying to set the said attr using FormHelper() and Field() functions. However Field() seems to be taking type as a **kwarg but nothing happens when I pass the "password" value but, e.g. "hidden" works. I have been referencing the docs and looked under the hood but can not seem to wrap my head around this... What am I missing here? Disclaimer, I am new to Django. -
Forms for multiple nested related models in Django
I am developing a website for schoolchildren on a voluntary basis, there are several nested models, that is: I have a Question associated with it 1to1 Comment, and a ForeignKey CoImage associated with Comment (I need the ability to add many illustrations to Comment). To edit the entire Question on one page, I use inlineformset_factory. PROBLEM: when uploading files, for some reason, all images are added to QuImage (these are illustrations to the question that are processed in the same form), even those that were uploaded to CoImage. My forms: from .models import Question, QuImage, Comment, CoImage, CoFile from django.forms import ModelForm, inlineformset_factory class QuestionForm(ModelForm): class Meta: model = Question fields = [ 'year', 'stage', 'grade', 'part', 'number', 'text', 'tags', 'topics', 'flag', 'type'] QuImageFormSet = inlineformset_factory(Question, QuImage, extra = 5, fields=['file', 'label']) CommentFormSet = inlineformset_factory(Question, Comment, extra = 1, fields=['text']) CoImageFormSet = inlineformset_factory(Comment, CoImage, extra = 3, fields=['file', 'label']) My views: def add(request): if request.method == 'POST': addform = QuestionForm(request.POST) question = quicksave(addform) if question: quimageform = QuImageFormSet(request.POST, request.FILES, instance=question) quicksave(quimageform) commentform = CommentFormSet(request.POST, instance=question) comment = quicksave(commentform) if comment: coimageform = CoImageFormSet(request.POST, request.FILES, instance=comment) quicksave(coimageform) return redirect('problems') addform = QuestionForm() quimage = QuImageFormSet() comment = CommentFormSet() coimage = CoImageFormSet() … -
A Simple Calculator using Django
I want to create a website where the user is asked to type a given number to get the square number and the square root. This is from index.html: <div class="d-flex typeW"> <form action="add"> Enter a number : <input type="text" name="num1"> <input type="submit"> </form> </div> This is from the result page (where you can see the result): <div class="d-flex title2"> <h2> {% block content %} {{result}} {% endblock %} <br><br> This is from view: def add(request): num1 = int(request.GET["num1"]) return render(request, 'result.html' , {result2: num1 * num1}) Now I want to take the square root of that number but I'm not sure how. How do I take one input and then do two calculations by using two functions? help much appreciated -
Mounting a virtual environment via SSHFS on local machine using it's Python3 file not working
So I have mounted a part of a development server which hold a virtual environment that is used for development testing. The reason for this is to get access to the installed packages such as Django-rest-framework and Django itself and not having it set up locally (to be sure to use the same version as the development server has). I know that it's perhaps better to use Docker for this, but that's not the case right now. The way I've done it is installing SSHFS via an external brew (as it's no longer supported in the brew core) - via this link https://github.com/gromgit/homebrew-fuse After that I've run this command in the terminal to via SSH mount the specific part of the development server that holds the virtual enviornment: sshfs -o ssh_command='ssh -i /Users/myusername/.ssh/id_rsa' myusername@servername:/home/myusername/projectname/env/bin ~/mnt/projectname It works fine and I have it mounted on my local disk in mnt/projectname. Now I go into VSCode and go into the folder and select the file called "python3" as my interpreter (which I should, right?). However, this file is just an alias, being 16 bytes in size. I suspect something is wrong here, but I'm not sure on how to fix it. Can …