Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting information from Jquery in Django views
in the jquery script, I get the information from the table into the data variable in json format: <script> var $table = $('#table') var $button = $('#button') $(function() { $button.click(function () { data = JSON.stringify($table.bootstrapTable('getData')) $.ajax({ url: "{%url 'addCampaign'%}", type: "POST", data: { 'mails_inf': data, 'csrfmiddlewaretoken': '{{ csrf_token }}', } }) }) }) </script> And in the function with views, I try to get this list for further processing as follows: def add_campaign(request): error = '' if request.method == 'POST': data = request.POST.get('mails_inf') print(data) But the data variable turns out to be None, when alerting this variable in the script itself, all the information is there. My tab where it all happens handles this url: path('addCampaign', views.add_campaign, name='addCampaign') I would be grateful if you could tell me where I am wrong, or offer another solution to the problem -
DRF Serializer relations Erro: Direct assignment to the forward side of a many-to-many set is prohibited. Use group.set() instead
I'm creating an api that will register users related to a customer and also to an organizational group, but I'm having problems registering the user's group. whenever I try to register I get the following error: "Direct assignment to the forward side of a many-to-many set is prohibited. Use group.set() instead." Could you help me understand what I'm doing wrong? my models.py class Cliente(models.Model): nome = models.CharField(max_length=100, unique=True, null=True) documento = models.CharField(max_length=30, blank=True, default='00.000.000/0001-00') logo = models.CharField(max_length=255, blank=True, null=True) data_de_criacao = models.DateField(default=date.today) cliente_ativo = models.BooleanField(default=True) background_img = models.CharField(max_length=255, blank=True, null=True) cor_primaria = models.CharField(max_length=10, blank=True, null=True) cor_secundaria = models.CharField(max_length=10, blank=True, null=True) def __str__(self): return self.nome class GrupoOrganizacional(models.Model): id_grupo = models.BigAutoField(primary_key=True, unique=True) nome_grupo = models.CharField(max_length=100, blank=False, null=False) cliente = models.ForeignKey(Cliente, blank=True, null=True ,on_delete=models.CASCADE) def __str__(self): return self.nome_grupo class Usuario(AbstractUser): objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] cliente = models.ForeignKey(Cliente, blank=True, null=True ,on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=False, null=False) last_name = models.CharField(max_length=100, blank=False, null=False) username = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=100, blank=False, null=False, unique=True, error_messages={'unique': "O email cadastrado já existe."}) password = models.CharField(max_length=100, blank=False, null=False) usuario_ativo = models.BooleanField(default=True) grupo = models.ManyToManyField(GrupoOrganizacional, related_name='grupos') is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) def __str__(self): return "%s (%s)" %(self.first_name, self.cliente) my views.py class GruposViewSet(viewsets.ModelViewSet): ''' Lista … -
pass a JSON data from React to Django using POST request problem
I'm trying to pass information using POST but I get a request in OPTIONS. the request - "OPTIONS /store-register HTTP/1.1" 200 13. when i change views.py request.method == 'POST' to: request.method == 'OPTIONS' i get "Broken pipe from ('127.0.0.1', 61126)" I can't figure out the problem. view.py: @csrf_exempt def store_register(request): if request.method == 'POST': form = json.loads(request.body) vendor = Vendors.objects.create(store_name=form['storeName'],company_name=form['companyName'],img=form['storeImage'],business_email=form['storeEmail'],pay_pal=form['payPalEmail']) vendor.save() return JsonResponse({'user': 'testONly'}) React Companent: class StoreRegister extends React.Component { constructor(props) { super (props); this.state = { acceps: '' } } getAndSendInput = () => { const storeName = document.getElementById('storeName').value const companyName = document.getElementById('companyName').value const storeImage = document.getElementById('storeImage').value const storeEmail = document.getElementById('storeEmail').value const payPalEmail = document.getElementById('payPalEmail').value this.setState({storeName: storeName,companyName: companyName,storeImage: storeImage, storeEmail: storeEmail,payPalEmail: payPalEmail}) fetch('http://127.0.0.1:8000/store-register', { method: "POST", body: JSON.stringify ({ 'storeName':storeName, 'companyName':companyName, 'storeImage':storeImage, 'storeEmail':storeEmail, 'payPalEmail':payPalEmail }), headers: new Headers ({'Content-type': 'application/json; charset=UTF-8'}) }) console.log(storeName,companyName,storeImage, storeEmail,payPalEmail) } render () { return ( <div> <label>Store Name</label> <input type={"text"} name={"storeName"} id={"storeName"} ></input> <br></br> <label>Company Name</label> <input type={"text"} name={"companyName"} id={"companyName"} ></input> <br></br> <label>Store Image</label> <input type={"file"} name={"storeImage"} id={"storeImage"}></input> <br></br> <label>Store Email</label> <input type={"email"} name={"storeEmail"} id={"storeEmail"} ></input> <br></br> <label>Pay Pal Email</label> <input type={"email"} name={"payPalEmail"} id={"payPalEmail"}></input> <br></br> <button onClick={() => this.getAndSendInput()}>Register</button> </div> ) } } export default StoreRegister -
How to perform a Django ORM calculation across an m2m field
I'm trying to figure out how to get a specific clients percentage share of income which may be split between multiple owners or shared equally. The models (simplified) are: class Client(Model): ... class Loan(Model): applicants = ManyToManyField(Client) class Income(Model): loan = ForeignKey(Loan) amount = DecimalField() income_type = CharField(choices=['INVESTMENT', ...]) proportions = CharField(default='EQUAL', choices=['EQUAL', 'SPECIFIED']) class IncomeOwner(Model): income = ForeignKey(Income, related_name='owners') client = ForeignKey(Client) percent = DecimalField() From those models I'm attempting the following to calculate income shares, by category, for a given client/loan combination. It's important to note that the owners relation only matters if proportions is 'SPECIFIED' - otherwise all applicants have an equal share. For performance reasons I'm trying to keep the logic in the ORM: def get_income(loan, client): # This income can be associated with multiple applicants as follows: # - If the "proportions" are "EQUAL" then assign this applicant an equal split # between the other applicants (amount / num_applicants) # - Otherwise use the amount directly assigned to the income owner # The percentage based on number of applicants or taken from the owner percent field equal_share_percent = ExpressionWrapper(100 / F('num_applicants'), output_field=PercentageValueField()) applicant_share_percent = Case( When(proportions='SPECIFIED', then=F('owners__percent')), <-- ONLY WANT % FOR THIS CLIENT default=equal_share_percent … -
Django: Display SessionWizard multi-step form inside a modal of existing view
I am trying to create an Instagram Clone and have the home page in the index view. I want to add a Multi-Step form to add a new Post as below: Step 1: Upload Image Step 2: Add caption and submit Just like Instagram, i want this form to show up as a Modal/Pop-up when the Create Post icon is clicked from the Home Page. From the documents and other sources, I was only able to create a SessionWizard form as a separate view. Also, i would like to know if the done() function can be modified/skipped and only a custom confirmation message can be shown inside the modal after submission. -
nginx is unconfigured and inactive after upgrading AL2 Docker platform to newest version
We have a dockerized Django application on Elastic Beanstalk running on the now-deprecated AMI platform, deployed via the EB CLI. I'm the sole technical employee and only recently inherited this environment with little to no handover and no prior experience with AWS. When I first deployed a new environment on the AL2 Docker 3.5.0 platform, following the upgrade guide from Amazon, the new instances come up and immediately fail all health checks. Turns out that nginx service is inactive and the applied config files are all just nginx defaults and neither the EB platform defaults nor the .conf files I placed in .platform/nginx/conf.d/elasticbeanstalk are present. Just starting the nginx service allows health checks to succeed but since the config is all missing all it shows is the default nginx welcome page. After some trials and tribulations I tried cloning the environment, then downgrading that to AL2 Docker 3.0.3. After deploying to the downgraded platform everything works out of the box. Primary difference I can see between 3.0.3 and 3.5.0 is a jump from docker version 19.03 to 20.10 (ref), and nginx from 1.16 to 1.20. I then tried the last platform version available that still used the docker 19 which … -
import "django.shortcuts" could not be resolved from sauce Pylance(reportMissingModuleSoucre)
[![import "django.shortcuts" could not be resolved from sauce Pylance(reportMissingModuleSoucre) from django.shortcuts import render # Create your views here. def get_home(request): return render(request,'home.html') i didnt try anything,i need some help -
Django - Error when I filter my form field's queryset
I created a form and view (FBV) to add new model. I overrided form's __init__ but now when I try to access my view it raise an error CreationForm' object has no attribute 'get' My view : def Creation(request): user = None if request.user.is_authenticated: user = request.user # POST METHOD if request.method == "POST": form = CreationForm(request.POST) form.user = user if form.is_valid(): sheet = form.save() return redirect("sheet_detail", pk=sheet.id) form = CreationForm(initial={'user': request.user}) return render(request, "jde/creation_form.html", context={"form": form}) My form : class CreationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreationForm, self).__init__(self, *args, **kwargs) self.fields["contest"].queryset = Contest.objects.filter(active=True) class Meta: ... -
In my django application I have a png image which is displayed well locally but when I deploy on heroku it is no longer displayed
In my django application I have a png image which is displayed well locally but when I deploy on heroku it is no longer displayed. All other images in my app display fine locally and on heroku. What could be the origins of this behavior? <img src="{% static 'assets/images/brand/logo_ozangue.png' %}" class="header-brand-img main-logo"> -
Is it possible to iterate over one query set but show the other in DRF?
We have a config object in our code and a simple table for config aliases (alias + config). I want to create a generic API using ModelSerializers for listing the following for each ALIAS: { "alias": "test", "config_param_1": 1, "config_param_2": True } How I imagined the serialiser to look like working with the standard ModelViewSet is like this: class DeviceConfigSerializer(serializers.ModelSerializer): class Meta: model = Alias fields = [f.name for f in Config._meta.get_fields() if f.name not in ['id', 'other_fields']] Then I would need to overwrite the method for getting the fields to take alias.conf fields. Trying a couple of ways (like below) I can't quite get it to work. def to_representation(self, instance): if isinstance(instance, Config): return super().to_representation(instance.conf) return super().to_representation(instance) TL;DR: I want the ListSerializer to iterate over the ALIAS model but really show the details for the CONFIG model plus the alias.id. -
Django.Programming Error: Table Name Does Not Exist - How to solve?
I deleted a model in Django which I created for testing purposed. Now when I try and run makemigrations and mirgrate I get the following error: django.db.utils.ProgrammingError: table "members_test" does not exist Is there a standard procedure I should be doing when deleting a model? I only deleteed the code out of my Models file and tried migrating after. I've only tried runing migrate and make migrations in addtion to scouring the web. -
Unittest sending binary protobuf file error
I'm trying to implement unit tests for my django rest framework project. I send protobuf files. My code is: def test_post_endpoint_new_version_existing_service(self): files_dir = os.path.join(settings.BASE_DIR, 'api/test_files') path = files_dir + '/test1_test2.bin' myfile = open(path,'rb') self.guest_client.post( '/config?content-disposition=%20attachment%3Bfilename%3D%22test1_test2.bin%22', data=myfile, content_type='application/octet-stream' ) And nothing happens. Where did I do wrong? -
Misuse of window function LAG() ocurred when i used sum() function
Stores are disabled with BLOCK_EVENTS events and enabled with UNBLOCK_EVENTS events. My requirement is the active range of the store. I have given the code I use below, but the problem that exists is that when I want to collect all the active_period's together, it gives an error. # models.py class PartnerEventHistory(models.Model): partner_object = models.ForeignKey(InternetShop, on_delete=models.CASCADE, related_name='events') event = models.CharField('رخداد', max_length=100, choices=EVENT_CH, null=True, blank=True) date = models.DateTimeField('تاریخ ایجاد', db_index=True, auto_now_add=True) query: PartnerEventHistory.objects.filter( event__in=PartnerEventHistory.BLOCK_EVENTS + PartnerEventHistory.UNBLOCK_EVENTS ).order_by('partner_object', 'date').annotate(prev_event=Window( expression=Lag('event'))).annotate(active_period=Case( When(Q(event__in=PartnerEventHistory.BLOCK_EVENTS) & Q(prev_event__in=PartnerEventHistory.UNBLOCK_EVENTS), then=(F('date') - Window(Lag('date'))) / (1000000 * 60 * 60 * 24)), default=Value(0), output_field=IntegerField())).order_by('partner_object').annotate( total=Window(expression=Sum('active_period'), order_by=F('partner_object').asc())).values( 'partner_object', 'cum_active_period') error: OperationalError: misuse of window function LAG() -
Unable to run migrations for a django web service with postgresql backend through docker
I am trying to grow on a bookstore project mentioned in the book titled Django for Professionals by Vincent As I try to grow on it my requirements.txt has grown to asgiref==3.5.2 Django==4.0.4 psycopg2-binary==2.9.3 sqlparse==0.4.2 django-crispy-forms==1.14.0 crispy-bootstrap5==0.6 django-allauth==0.50.0 with my Dockerfile as FROM python:3.8-slim-bullseye # set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # # Set working directory WORKDIR /code # # Installing python dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt and my docker-compose.yml as # Mentioning which format of dockerfile version: "3.9" # services or nicknamed the container services: # web service for the web web: # you should use the --build flag for every node package added build: . # Add additional commands for webpack to 'watch for changes and bundle it to production' command: python manage.py runserver 0.0.0.0:8000 volumes: - type: bind source: . target: /code ports: - "8000:8000" depends_on: - db environment: - "DJANGO_SECRET_KEY=django-insecure-m#x2vcrd_2un!9b4la%^)ou&hcib&nc9fvqn0s23z%i1e5))6&" - "DJANGO_DEBUG=True" # postgreSQL database server being constructed alongside db: image: postgres:13 # volumes: - postgres_data:/var/lib/postgresql/data/ # unsure of what this environment means. environment: - "POSTGRES_HOST_AUTH_METHOD=trust" # Volumes set up volumes: postgres_data: I have been unable to run migrations or create a super user. The primary … -
How to configure Cheetah on Django
Is there a tutorial on how to configure Django and cheetah to print out simple text like hello world in variables or lists? I'm trying to configure cheetah with Django or find instructions on how to or tutorials but without luck. I've already tried the cheetah docs Django module but it's much more going on Plz little help -
cannot connect Django to postgres
I am trying to connect my django app to postgres but it gives the following error. connection to server at "127.0.0.1", port 5432 failed: FATAL: database "testDB" does not exist the postgres server is running I have checked it also restarted the server still I get the same error my database settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'testDB', 'USER': 'postgres', 'PASSWORD': 'xxxxx', 'HOST': '127.0.0.1', 'PORT': '5432', } } I tried to check if the server is running and it is running, also restarted the server but still the same error. -
How do I display the django-quill-editor toolbar?
In my app I need to create, edit, and send html emails. I have installed the django-quill-editor package and was successful in displaying my html content inside the quill editor - but only in admin. In my campaign app, I can display the html, but not the toolbar for editing. In my settings.py file I added the 'django_quill' app. In campaign/models.py I have a QuillField called 'content': class CampaignStep(models.Model): id = models.IntegerField(primary_key=True) campaign = models.ForeignKey( Campaign, on_delete=models.DO_NOTHING, blank=False, null=False, related_name='campaigns',) subject = models.CharField(max_length=64, blank=False, null=False) content = QuillField() campaign/views.py: class CampaignStepContentUpdateView(UpdateView): model = CampaignStep context_object_name = 'csd' fields = ['content'] template_name = 'campaign/campaign_step_content_update.html' campaign/forms.py class ContentForm(ModelForm): class Meta: model = CampaignStep fields = ['content'] And here is the template: {% extends "base.html" %} <head> <!-- django-quill-editor Media --> {% include 'django_quill/media.html' %} </head> {% block content %} <!-- 'csd' abbreviates 'campaign step detail'. --> <h2>{{ csd.campaign }} - Step {{ csd }}</h2> <body> <p></p> <h3>Content</h3> <div class="card"> <div class="card-body"> <form action="" method="POST">{% csrf_token %} {{ csd.content }} </form> </div> </div> <p></p> <button type="submit" class="btn btn-primary btn-block mt-1">Save Changes</button> </body> {% endblock content %} The page then displays only this: <django_quill.fields.FieldQuill object at 0x104e134c0> How do I get the quill editor … -
How to send an email that doesn't need triggering a specific url?
I'm trying to build an automated email system for ecommerce purposes, So, I wanna send an email if a user is not registered, with the tracking_no whenever we have assigned a tracking_no for an OrderItem, I don't understand how I would be able to put this in a view function because it'll never get triggered if no one tries to access the url connected to the view, would I need to access the admin panel url for OrderItem save function? So that whenever the admin assigns a tracking number and saves the form, a function checks up if there's an assigned number and sends out the email to the Customer. If so how would I solve this? #Model #Customer is someone who is not registered class Customer(models.Model): email = models.EmailField(max_length=100) class Order(models.Model): customer = models.ForeignKey(Customer) class OrderItem(models.Model): order = models.ForeignKey(Order) tracking_no = models.CharField(max_length=300, null=True, blank=True) #Email subject = "tracking_no" html_message = render_to_string('emails/tracking_no.html', {'tracking_no': tracking_no}) send_mail() -
ImportError: libssl.so.1.0.0: cannot open shared object file: No such file or directory
When running a project via pipenv, I get the following stacktrace. As I typically do not work with pipenv and cookiecutter projects, I have been struggling to fix it. Any help is appreciated. In case it matters, it is this project that I am trying to build and launch. ➜ project-shop git:(master) ✗ pipenv run ./manage.py runserver [2022-11-04 13:08:19,329 autoreload] INFO: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/user/miniconda3/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/home/user/miniconda3/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/user/.local/share/virtualenvs/project-shop-d1PiLiCc/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/user/miniconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File … -
Pop values from a queue created on another view Django
I have two views: one that create a queue and add elements inside it and another that is called with an AJAX call, when a button is clicked, from the frontend. Now I would like to consume the things inside the queue on the view called by AJAX. The issue is that, obviusly, this view doesn't know the queue. So, my question is, is that a way to pass the queue on this view or is there another way too pass informations between different view in Django? -
Django Jazzmin custom templates error on Heroku
i have a trouble with submit_line.html on Heroku, when i deployed, my additional button does not display, some code from my project. When i run local with heroku (without debug) settings - all go good In app/module folder: templates/admin/module_name/model_name/ submit_line.html {% extends "admin/submit_line.html" %} {% load jazzmin %} {% get_jazzmin_ui_tweaks as jazzmin_ui %} {% block extra-actions %} <div class="form-group"> <a href="https://www.djangoproject.com/" class="btn {{ jazzmin_ui.button_classes.warning }} form-control" target="_blank">Go Django</a> </div> {# Process with form submission #} <div class="form-group"> <input type="submit" class="btn {{ jazzmin_ui.button_classes.primary }} form-control" value="Send message to chats" name="send"> </div> {% endblock %} In settings.py INSTALLED_APPS = [ 'jazzmin', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', .... ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' WHITENOISE_USE_FINDERS = True # Must be True, without this setting - don't work STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") JAZZMIN_SETTINGS = { "site_title": "Club", "site_header": "Club", "site_brand": "Club", "welcome_sign": "Welcome to Club", "copyright": "Hihi", "hide_models": ["auth.group"], # "show_ui_builder": True, # "site_logo": "/images/logo.png" "order_with_respect_to": ["channel"], "icons": { ".channel": "fas fa-comments", ".groups": "fas fa-users", ".message": "fas fa-comment-dots", ".botcommand": "fas fa-terminal", ".quiz": "fas fa-poll-h", "auth.user": "fas fa-user-circle", }, } … -
How to save files from Incoming email using imap_tools into AWS S3 bucket
I have an email server hosted on AWS EC2. I am using imap_tools for retrieving email content. when I tried to get the file through the payload, I get this return; att.payload # bytes: b'\xff\xd8\xff\xe0\' Please how do I get the actual file path from the payload or bytes to be saved on AWS S3 and be able to read it from my table? I can attach a file to my mail and save it on S3 but getting the attached file coming to a mail address is my challenge. This is a function for reading email contents with imap_tools def imap_inbox(self): unread_inbox = [] for msg in self.mailbox.fetch(): attachments = [] for att in msg.attachments: attachments += [{ "filename": att.filename, "content_type": att.content_type, "file": att.payload, }] msg_dict = { "subject": msg.subject.replace("***UNCHECKED*** ", ""), "from_mail": msg.from_, "to_mail": msg.to[0], "message": msg.text, "attachments": attachments, } if 'RECENT' in msg.flags: unread_inbox += [msg_dict] return { "unread_inbox": unread_inbox, } This is my function for mail_server_inbox def mail_server_inbox(self, request, *args, **kwargs): # imap authentication ad_imap = self.authenticate_imap() inbox = ad_imap.imap_inbox() unread_inbox = inbox.get("unread_inbox") for msg in unread_inbox: mail_instance = None file_name = None try: attachments = msg.pop("attachments", []) msg = { **msg, } attachments = list( … -
how to run a python script in cpanel command while using a subdomain
Hi I am having an issue related to running a python script.I just uploaded my django project on cpanel and want a python script to auto run itself but as I am newbee to cpanel I don't know how to provide path in the cron job command section. Here is what I am writing in the command section of cron jobs in cpanel /usr/bin/python subdomainName/folderName/folderName/folderName/folderName/fileName.py But it is not working -
DRF - How to redirect a user after already sending a response
I'm facing the following problem: I'm building a third-party integration into my Django app. Users that already use the third-party should be able to click on a button and be redirected to my app. In the redirect, the third-party will send a POST request with a JSON that contains some info (email, some IDs etc.). I'll use this info to see if I have the user in my DB already. If yes, I want to: return a response with a user ID and API Key for the third party to store then redirect the user to a login screen If no, I want to: create a user and return a response with a user ID and API Key for the third party to store then redirect the user to a confirmation screen. The question I have: How can I redirect the user AFTER returning the user ID & API key? My current logic is this: class UserList(APIView): .... def post(self, request): if account_exists: return Response(account_data) # NOW I WANT TO REDIRECT else: create_account() return Response(account_data) # NOW I WANT TO REDIRECT I'm currently using DRF to handle the POST requests, not sure whether that is the best way of doing … -
How to allow users to change their email address?
I would like sociallogins to have the ability to specify a local password (if they want to/not required), and local accounts to be able to change their email address. What is the best approach for this?