Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django server 127.0.0.1:18000 doesn't work on browser for openedx project
I am using docker container(devstack) for openedx project on Mac. Since I exited all containers accidentally, I can't run the server. I started containers again and it's running fine. When I type command below in the docker container, python /edx/app/edxapp/edx-platform/manage.py lms runserver 18000 System check identified no issues (0 silenced). October 08, 2021 - 15:38:25 Django version 1.11.18, using settings 'lms.envs.devstack_docker' Starting development server at http://127.0.0.1:18000/ Quit the server with CONTROL-C. It seems like working on terminal but Chrome browser shows ERR_EMPTY_RESPONSE error sign. when I tried with 0.0.0.0:18000 or localhost:18000, it also connects to the server but gives me error like this but the difference is it's django debug mode. IOError at /dashboard [Errno 13] Permission denied: '/tmp/mako_lms/7fa50c86c772c2affd8b5a04d05a85da/dashboard.html.py' Strangely, When I run server on 0.0.0.0:18000, I am able to see django admin site with 127.0.0.1 or localhost or 0.0.0.0 :18000/admin but I get the error with the other urls. I am a complete novice on programming. Could someone give me ideas on what else to try? Thanks. -
Django Detecting delete or update method
mixins.py class ObjectViewMixin: def dispatch(self, request, *args, **kwargs): print(request.method, self.get_object()) return super().dispatch(request, *args, **kwargs) so if self.get_object() is None then I can detect its for Creating object if self.get_object() is found then it can be either update or delete method, because request.method always returns POST Now how can I distinguish them? -
(Django Rest Framework) got an error when I used RefreshToken class in rest_framework_simplejwt.tokens
I got an error which is related to RefreshToken class implemented in rest_framework_simplejst. I defined a function: def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token)} when I made a request to the server that is in the development environment, it ran perfectly: "POST /account/signup HTTP/1.1" 200 332 but when I made a request to the server that is in the production environment, it ran poorly: Forbidden: /account/signup I try to debug it and find the breaking point is "refresh = RefresgToken.for_user(user)", when I printed "refresh", it got the same result mentioned before and jumped to the exception block. Forbidden: /account/signup /account/signup is the endpoint that calls the function "get_tokens_for_user". Can anyone explain what is going on and why the production and development environment make the difference? Thanks so much. -
Covert list of lists in Python to json array [closed]
I've a list of lists in python [[0.3818, 0.028437499999999994, 0.09428, 0.08117894736842104, 0.15704, 0.1623230769230769, 0.21171470588235294, 0.23636], [nan, 0.0, 0.195925, 0.2216625, -0.04444, 0.05940769230769231, 0.016263333333333328, 0.201525]] I want to convert it into Json array When tried with just one list [[0.3818, 0.028437499999999994, 0.09428, 0.08117894736842104, 0.15704, 0.1623230769230769, 0.21171470588235294, 0.23636]] It works fine, when added second list it gives parseerror I've tried json.dumps and json.loads, doesn't seem to work data= json.dumps(data) data = json.loads(data) -
Django translation system
I have a small problem that I can't solve. With reference to Django's automated translation system, I wanted to do a teaching test: I went to django / contrib / auth / models.py in the AbstractUser class and in line 340 (Django version 3.2.7) I changed _ ('first name') to _ ('dog') then I went to the django.po file located in django / contrib / auth / locale / it / django.po and there I inserted a new reference, that is: msgid "dog" msgid "cane" i saved and restarted the server. I logged into the administration panel and in the users section the name field comes with "Dog", but I was expecting "Cane" ... What did I do wrong? Thanks so much for the support! -
Reverse for 'packing' with keyword arguments '{'id': '15'}' not found. 1 pattern(s) tried: ['packing/(?P<pk>[^/]+)$'] django
I got an issue here, so whenever the users click on the button, the url can show that it manage to get the ID from the link: http://127.0.0.1:8000/packing/15 but it show me this error when it is redirected to the link: Reverse for 'packing' with keyword arguments '{'id': '15'}' not found. 1 pattern(s) tried: ['packing/(?P[^/]+)$']. How do I fix this error? This is how after redirect it should looks like, but it just give me an error. views.py @login_required() def packing(request, pk): photo = get_object_or_404(Photo, id=pk) if request.method == "POST": form = packingForm(request.POST, instance=photo) pickingform = pickingForm(request.POST, instance=photo) if form.is_valid(): if form != photo.packing: photo.status = 'Packing' photo.Datetime = datetime.now() form.save() return redirect('packing', id=pk) if pickingform.is_valid(): if pickingform != photo.picking: photo.status = 'Picking' photo.Datetime = datetime.now() form.save() return redirect('packing', id=pk) else: pickingform = pickingForm(instance=photo) form = packingForm(instance=photo) context = { "pickingform": pickingform, "form": form, "photo": photo } return render(request, 'packing.html', context, ) forms.py class packingForm(forms.ModelForm): USER_TYPE_CHOICES = ( ('Yes', 'Yes'), ('No', 'No'),) packing = forms.ChoiceField(required=True, widget=forms.RadioSelect, choices=USER_TYPE_CHOICES) class Meta: model = Photo fields = ("packing", ) def __init__(self, *args, **kwargs): super(packingForm, self).__init__(*args, **kwargs) self.fields['packing'].required = False class pickingForm(forms.ModelForm): PICKING = ( ('Yes', 'Yes'), ('No', 'No'), ) picking = forms.ChoiceField(required=True, widget=forms.RadioSelect, … -
postman only showing "This field is required" to ManyToMany field in django
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. When I use post request, raw-data works, but not form-data. module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() room_list = models.CharField(max_length = 100, blank=True) rooms = models.ManyToManyField(Rooms, blank=True) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) level = models.CharField(max_length=100) desc = models.TextField() module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(many=True) class Meta: model = Module fields = '__all__' def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room = Rooms.objects.get(**data) module.rooms.add(room) return module def update(self, instance, validated_data): # Updating rooms rooms_data = validated_data.get('rooms') instance.rooms.clear() for room_data in rooms_data: room = Rooms.objects.get(**room_data) instance.rooms.add(room) # Updating other fields fields = [ 'title', 'desc', 'thumbnail', 'is_deleted', ] for field in fields: setattr(instance, field, validated_data[field]) instance.save() return instance rooms/serialier.py - class RoomSerialize(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): # Adding the rooms to module from room_list new_request = request.data.copy() room_list=[] if 'room_list' in new_request: room_list_data = list(new_request['room_list'].split(" … -
Why are script tags auto converting & to &?
I'm experiencing a strange problem I haven't run into before. My html is generated via Django templates, and consist of some basic code that initializes a DataTable based on a query string with some GET variables (i.e. "/report1/?filter1=abc&filter2=def"). However, all of a sudden, whenever I write the Django template variable out within a <script></script> tag the & is converted to &amp;, like this: <script> var link = "/report1/?filter1=abc&amp;filter2=def" </script> However, when not inside a script tag, the string outputs as originally intended: "/report1/?filter1=abc&filter2=def" This is based off the exact same Django template variable with no changes. What about the script is causing the & to be encoded? This happens in current versions of Edge and Firefox. Django clearly doesn't know anything about the <script></script> tags so it must be a browser thing. Any ideas how to prevent this from happening? It is something that didn't seem to happen in the past. Thanks! For reference, my Django template looks something like this: {{ string }}<br> <script> var link = "{{ string }}" </script> -
Normalize CRLF line endings in Django form input
I have a ModelForm with a TextArea. If the user submits text with a newline, it gets converted into a \r\n by the browser. I would expect Django to normalize this text for me, but it doesn't. This is an issue because Django's maxlength validation doesn't line up with the maxlength in HTML, since in-browser lines endings are treated only as "\n". So if the textarea has a maxlength of 5, and the user enters "ab\ncd", they think that's fine, but when they submit the form, Django error because it sees "ab\r\ncd", which is 6 characters. I want to fix this by doing everything with \n, and not save \r\n into the database. -
Django Class Model choices from json file
When creating class in Django, why upload from json file instead of entering CHOICES directly? Is it not stored as a string in the Database, but as a 'pk' to relieve the burden on the DB? Or is it to facilitate when outputting values from a template? [models.py] class StudyFieldModel(models.Model): class Meta: abstract = True CHOICES = tuple() class Stage(StudyFieldModel): --> Method1 STAGE1 = 'stage1' STAGE2 = 'stage2' STAGE3 = 'stage3' NA = 'na' CHOICES = ( (NA, '해당없음'), (STAGE1, 'Stage 1'), (STAGE2, 'Stage 2'), (STAGE3, 'Stage 3'), ) class Stage(StudyFieldModel): --> Method2 CHOICES = ( ('na', '해당없음'), ('stage1', 'Stage 1'), ('stage2', 'Stage 2'), ('stage3', 'Stage 3'), ) [stage.json] [ { "model": "study.Stage", "pk": 1, "fields": { "value": "na" } }, { "model": "study.Stage", "pk": 2, "fields": { "value": "stage1" } }, { "model": "study.Stage", "pk": 3, "fields": { "value": "stage2" } }, { "model": "study.Stage", "pk": 4, "fields": { "value": "stage3" } } ] -
show selected checked boxes in update form that are saved in database while create form in django
In my create form i have saved certain values of soil_type as clay, chalk in my database these values should be shown ticked in update form let us consider my forms.py as SOIL_TYPE_CHOICES = ( ('Acidic','Acidic'), ('Alkaline','Alkaline'), ('Chalk','Chalk'), ('Clay','Clay'), ('Damp','Damp'), ) soil_type = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}), choices=SOIL_TYPE_CHOICES, ) When i am using widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}) in updateform it is showing all the choices as ticked rather than the values that are saved in database(i.e clay, chalk only should be ticked in updateform display) Currently it is showing in this way in update form How i need the image to be is Please help me to display ticks only on the saved values in database -
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?