Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload an image through copy / paste using django modelform?
I'm pretty new with django, and trying to migrate a google apps script (GAS) webapp to django. One feature I had on google website was to capture a pasted image from clipboard and submit it through a form. That was done through a hidden field in the form: <input type="hidden" name="summaryImage" id='summaryImage' value=''> and then I capture the paste event to populate this hidden form field /* Handle paste events */ function pasteHandler(e) { if (e.clipboardData) { // Get the items from the clipboard var items = e.clipboardData.items; if (items) { // Loop through all items, looking for any kind of image for (var i = 0; i < items.length; i++) { if (items[i].type.indexOf("image") !== -1) { // We need to represent the image as a file, var blob = items[i].getAsFile(); var URLObj = window.URL || window.webkitURL; var source = URLObj.createObjectURL(blob); var reader = new FileReader(); reader.onload = function(e) { document.getElementById("summaryImage").value= reader.result; } reader.readAsDataURL(blob); } } } } } The above form when submitted through google, can be parsed on the server side google apps script (GAS) from the summaryImage field in the form, like below: var splitBase = form.summaryImage.split(','), var type = splitBase[0].split(';')[0].replace('data:',''); var byteCharacters = Utilities.base64Decode(splitBase[1]); var blob … -
Confirming SNS subscription request using Django(boto3)
I am trying to make a Django Application which subscribes to the SNS and displays the messages published. I am currently working on first part. I made a view function in which if there is any post data then the function should send confirm subscription to the arn using boto3.Currently i am working incrementally and for all http post requests it returns the subscription confirmation. I have tied this function to a url test. Now I deploy the application on ELB and give the HTTP endpoint as xyz.com/test where xyz.com is link given by Elastic bean stalk. But subscription request is never confirmed on aws console. Below is the code,can somebody point out the error or any other way. Code: client = boto3.client('sns',region_name='us-east-2') @csrf_exempt def test(request): if request.method =='POST': header = json.loads(request.body) token=header['Token'] arn=header['TopicArn'] response = client.confirm_subscription( TopicArn=arn, Token=token, AuthenticateOnUnsubscribe=False ) In urls.py: url(r'^test',test) -
Django Celery Elastic Beanstalk supervisord no such process error
My celery_config.txt in file script in .ebextensions #!/usr/bin/env bash # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryconf="[program:celeryd-worker] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery worker -A wellfie --loglevel=INFO directory=/opt/python/current/app user=nobody numprocs=1 stdout_logfile=/var/log/celery-worker.log stderr_logfile=/var/log/celery-worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 environment=$celeryenv [program:celeryd-beat] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery beat -A wellfie --loglevel=INFO --workdir=/tmp -S django directory=/opt/python/current/app user=nobody numprocs=1 stdout_logfile=/var/log/celery-beat.log stderr_logfile=/var/log/celery-beat.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send … -
JQuery autocomplete text search with results from remote source
I'm trying to implement an input field with an autocomplete feature. I'd be using Google Books API to autocomplete names of books based on the keyword that the user enters in the input text field. I'd be using Django as my framework to implement this feature. This is what I have been able to do so far: JS $( document ).ready(function() { $("#id_book_name").on("change paste keyup", function() { var app_url = document.location.origin; var book_name = $('#id_book_name').val(); var url = app_url+'/book-search/'; if(book_name.length > 4) { var data = { 'book_name': book_name, 'csrfmiddlewaretoken': document.getElementsByName('csrfmiddlewaretoken')[0].value, }; console.log(data); $.post(url, data).done(function(result) { for(var book_title of result) { console.log(book_title); } console.log(result); }).fail(function(error) { console.log(error) }); return false; } }); }); Here, #id_book_name is the id of my input text field. As soon as the length of the keyword entered by the user exceeds 4, I'm sending a POST request to /book-search which is mapped to the following Python function where I hit Google Books API's endpoint and return the book titles in a specific JSON format: def book_search(request): book_results = {'titles':[]} key = 'XXXXXXX' url = 'https://www.googleapis.com/books/v1/volumes?q=' + request.POST['book_name'] + '&maxResults=5&key=' + key result = requests.get(url) json_result = json.loads(result.text) if 'items' in json_result: for e in json_result['items']: … -
don't understand Usercreation form in django
class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ("username",) field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True}) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) self.instance.username = self.cleaned_data.get('username') password_validation.validate_password(self.cleaned_data.get('password2'), self.instance) return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user I get completely lost with Class Meta: and init method. What I think: Class Meta: Class Meta calls models.Model(USER), where all the fields are made. And then it select field ('Username')?? For what reason? Does Class Meta in this case means: "Look, we need password1 and password2, however we can call username from models.model(USER) and use username(max_length) as form object? I am really confused. __init__ if self._meta.model.USERNAME_FIELD in self.fields: I think I am just looking at alien. What this suppose to mean … -
The clickable-row doesn't affect a button
The .html file is <tbody> {% for row in results %} <tr class="{% cycle 'row1' 'row2' %} clickable-row" data-href="{% url "perception:detail" pk=row.object.pk %}"> {% for item in row.cols %} {{ item }} {% endfor %} {% if row_actions_template %} <td class="row-actions">{% include row_actions_template with object=row.object %}</td> {% endif %} </tr> {% endfor %} </tbody> The .js file is $(function(e){ $(".clickable-row").click(function() { window.location = $(this).data("href"); }); }); The views.py file is class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' # row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' def active(self, obj): if obj.is_active: return icon(obj.get_icon(), css_class='green-text', tooltip=_('Active')) else: return icon(obj.get_icon(), css_class='red-text', tooltip=_('Inactive')) def notes_count(self, obj): return obj.notes.count() notes_count_label = _('Notes') def get_change_url(self, obj): return obj.get_absolute_url() class Meta: ordering = ('-created', '-modified') sortable = ('start_date', 'end_date', 'created', 'state', 'modified') list_filter = ('state', 'is_active', customer, error) list_display = ( '__unicode__', 'context_menu', 'state', 'start_date', 'end_date', 'current_balance', 'operation_error', 'modified', 'created', 'notes_count', 'active' ) The part of the models.py file is @python_2_unicode_compatible class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) def get_absolute_url(self): return reverse('perception:detail', kwargs={'pk': … -
how to save TaggableManager with post and render it with get? django
I have read some threads and still confused how I can save taggableManager using post in view.py? My model.py class Profile(models.Model): tags = TaggableManager(blank=True) In my view.py profile = Profile() request.POST['tags'] // this would give me the tag value which I think should be correct for example "hello" or "hello,yellow" profile.tags = request.POST['tags'] profile.save() // saves the profile but when I try looking in the admin dashboard, it's not saved though. I tried rendering the tags out using a get method for example profile_obj = Profile.objects.get(pk=pk) // which returns my profile obj print(profile_obj.tags) // this would give me an error of no name attribute I am quite confused now. Can someone please give me a hand? Thanks in advance -
django - use chunk to read uploaded file will break down some row
I want to use for chunk in f.chunks() to read a huge csv file. It works well in first record, but I found it will break the row when the rows reach chunk's size As I know the chunk's default size is 64KB. For example, I have three rows in csv file: 'this is first row' 'this is second row' 'this is third row' when I use for chunk in f.chunks(), I expect to get chunk1 contains 'this is first row', chunk2 contains ('this is second row', 'this is third row' ) or chunk1 contains ('this is first row','this is second row'), chunk2 contains ( 'this is third row' ) but the real result will be: chunk1 contains ('this is first row', 'this is'), chunk2 contains ('second row', 'this is third row') That it is, it will break second row 'this is second row' into different chunks. Is it possible to prevent chunk breaking the row? Thanks. -
Django Chat (Communication bewteen Django and Python)
I want to create chat in Django. Scheme is like Server must be on Django Server and Clients will be installed on PCs. I want to know is there any way to create Django Chat Server on web and Client Software for PCs? -
What is the best way to handle functional django model field defaults?
Sometimes a ForeignKey field needs a default. For example: class ReleaseManager(BaseManager): def default(self): return self.filter(default=True).order_by('-modified').first() class Release(BaseModel): default = models.BooleanField(default=False) ... class Server(models.Model): ... release = models.ForeignKey(Release, null=True, default=Release.objects.default) All is well and good with the above code until the time comes for db migration whereupon the functional default causes big problems because the default function cannot be serialized. Manual migration can work around this but on a large project where migrations are perhaps squashed periodically this leaves a time bomb for the unwary. A common workaround is to move the default from the field to the save method of the model but this causes confusion if the model is used by things like the rest framework or in creating forms where the default is expected on the field. -
How to view a JSON file in Django
So I have a JSON file and I want to iterate over it and display the information using Django. How do I do that and do I need to set up a Model like normal? How do I transfer this data to the database model using SQLite? I found this code on a similar stackoverflow question but I don't know how to show the data like via HTTPResponse so the user can view the data: import json json_data = open('/static/prices.json') data1 = json.load(json_data) // deserialises it data2 = json.dumps(json_data) // json formatted string json_data.close() -
models not showing on django admin
I'm just starting my first project using Django 1.11. I followed the same steps I've used on multiple Django 1.10 projects, but for some reason my models are not showing up on my localhost/admin site. My INSTALLED_APPS from settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', ] My admin.py: from django.contrib import admin from home.models import Home # begin Admin Class Definitions class HomeAdmin(models.ModelAdmin): fieldsets = [ ('Title', {'fields': ['title']}), ('Publication Date', {'fields': ['pub_date']}), ('Home Page Text', {'fields': ['header', 'sub_header', 'link_text']}), ] list_display = ('title', 'pub_date') list_filter = ['pub_date'] admin.site.register(Home, HomeAdmin) My [main_app]/urls.py: from django.conf.urls import url, include from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('home.urls')) ] But when I go to localhost:8000/admin the only things present are Groups and Users as if I hadn't registered any models at all. I have run makemigrations and migrate, and I have tried putting admin.py within the app directory instead of the project directory. It's currently in the [project_name]/[project_name] directory (the one with settings.py, urls.py, and wsgi.py files). Any suggestions? -
'Post' object has no attribute 'COOKIES'
I have Mezzanine up and working, and another forum app works fine as a standalone project. Now when I try to plug in the forum app to the existing Mezzanine project, I get this error message and cannot figure it out. AttributeError at /forum/post/1/ 'Post' object has no attribute 'COOKIES' Request Method: GET Request URL: http://localhost:8000/forum/post/1/ Django Version: 1.10.5 Exception Type: AttributeError Exception Value: 'Post' object has no attribute 'COOKIES' Exception Location: /Users/jc/Desktop/ppp36/cjc/lib/python3.5/site-packages/mezzanine/generic/forms.py in __init__, line 106 Python Executable: /Users/jc/Desktop/ppp36/cjc/bin/python Python Version: 3.5.3 Python Path: ['/Users/jc/Downloads/All-About-Books-master', '/Users/jc/Desktop/ppp36/cjc/lib/python35.zip', '/Users/jc/Desktop/ppp36/cjc/lib/python3.5', '/Users/jc/Desktop/ppp36/cjc/lib/python3.5/plat-darwin', '/Users/jc/Desktop/ppp36/cjc/lib/python3.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Users/jc/Desktop/ppp36/cjc/lib/python3.5/site-packages'] Server time: Tue, 18 Apr 2017 17:27:49 +0000 The template error page: 'Post' object has no attribute 'COOKIES' 135 </ul> 136 </div> 137 </div> 138 </li> 139 {% endfor %} 140 </ul> 141 <div class="card"> 142 <div class="card-header">reply</div> 143 <div class="card-block"> 144 {% if user.is_authenticated %} 145 {% render_comment_form for post %} 146 {% else %} 147 <a href="{% url 'account_login' %}?next={{ request.path }}">log in</a> 148 {% endif %} 149 </div> 150 </div> 151 </main> 152 {% endblock main %} 153 154 {% block script %} 155 <script> This is where the error occurs: enter image description here -
How to parse to an int? Django
The user can select two objects to compare against. This is the where the ID's are retrieved ids = [id for id in request.GET.get('ids') if id != ','] aircraft_to_compare = Aircraft.objects.filter(id__in=ids) However it throws the IndexError at /delta/ - list index out of range error. I'm getting the list with ['5','6'] instead of [5,6] I have a feeling I need to parse it to an int, but I don't know how to do that. Any help? -
Edit related DB entries in different tables
I'm working on simple expenses managing app. Every user has number of Accounts and Operations related to him. Newly added operation has influence on the specific account's current_balance field. I want user to have a possibility of editing already added Operations. I have created edit_operation view which takes back changes made to current_balance field and then calculates new value based on new operation's amount provided by the user. Here is my edit_operation method code: def edit_operation(request, operation_id): instance = get_object_or_404(Operation, pk=operation_id) previous_account = instance.account previous_type = instance.type previous_amount = instance.amount if request.method == "POST": form = OperationForm(request.POST, instance=instance) if form.is_valid(): # restore the account balance account = Account.objects.get(name=previous_account) account.current_balance -= previous_type * previous_amount account.save() # apply new operation operation = form.save(commit=False) operation.user = request.user account = Account.objects.get(name=operation.account) account.current_balance += operation.type * operation.amount account.save() operation.save() return redirect('index') else: form = OperationForm(instance=instance) return render(request, 'expenses/operation.html', {'form': form}) It works just fine but I'm wondering why my previous solution didn't work as expected. With my original approach I didn't use previous_account, previous_type and previous_amount helping variables. I just used instance attributes directly: # restore the account balance account = Account.objects.get(name=instance.account) account.current_balance -= instance.type * instance.amount account.save() However it seemed like at this point … -
Removing fieldsets from a form
I've installed django-betterforms to simplify form templates and put an end to {% if field.name == 'blah' %} in templates to include arbitrary content. So I've got fieldsets defined, but need to remove a fieldset under a certain condition. The trouble I'm having is the form fieldsets seem to have been setup before I'm able to modify things. class EntrantForm(BetterModelForm): class Meta: fieldsets = ( Fieldset( 'details', ('first_name', 'surname', 'dob'), legend=_("Section 1") ), Fieldset( 'address', ('address_1', 'address_2', 'city', 'county'), legend=_("Address") ), Fieldset( 'section2', ('facts', ), legend=_("Section 2"), ), Fieldset( 'section3', ('needs', ), legend=_("Section 3"), additional_content=mark_safe("<p>Hello world</p>") ), Fieldset( 'terms', ('photo_accepted', 'terms_accepted') ) ) model = Entrant For certain users, we don't need to show section 3, so I've tried to remove it from the form fieldset and the meta fieldset, but it's a bit stubborn! class EntrantForm(BetterModelForm): """ Entrant form """ def __init__(self, *args, **kwargs): region_type = kwargs.pop('region_type', None) if int(region_type) != int(Manager.RegionTypes.REGION): self.Meta.fieldsets = tuple_without(self.Meta.fieldsets, 'section3') # returns a tuple without the Fieldset for 'section3' self.fieldsets.rows.pop('section3') -
Django : Checking if user exists, not showing validationerror
(New at Django)I've tried everything and spent the whole day trying to get this to work. I am trying to check if user exists and display ValidationError if it already exists. Right now, i am using views.py to show template that says account not created because the validation error that forms.py should be taking care of is not showing. forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['email'].required = True password = forms.CharField(widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError("That user is already taken") return username class Meta: model = User fields = ['username', 'password', 'email'] labels = { "email": "Email" } # including my login form too just in case class LoginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'password'] labels = { "email": "Email" } views.py from django.shortcuts import render, redirect from .forms import UserForm def index(request): if request.user.is_authenticated: return redirect('/myaccount') else: title = "welcome" form = UserForm() context = { "template_title": title, "form": form } return render(request, "index.html", context) def new_user(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") form.save() return … -
Django's FileField open(mode='r') opening as bytestring instead of string
I have a model with a FileField that saves a text file, here's how I'm accessing it: report = MyMoodel.objects.get() document_report = report.document document_report.open(mode='r') print(type(document_report.read())) The resulting "type" is <class 'bytes'> Shouldn't I be receiving a string instead of bytestrings? Am I using open incorrectly? -
Django formset return empty instances
I have a class that inheirts from BaseInlineFormSet, where I override the save() method: class CustomBaseModelFormSet(BaseInlineFormSet): def save(self, something=None, commit=True, *args, **kwargs): instances = super(CustomBaseModelFormSet, self).save(commit=False) but when I call formset.save() to create new objects with a bound and valid formset, the variable instances is an empty list! Why the the save() of the parent class is not saving? there's no trace of any error. I'm using Python 3 and Django 1.10.5. -
Form control in Django ForeignKey
My Models: class Faculty(models.Model): name = models.CharField(max_length=30) class Program(models.Model): name = models.CharField(max_length=30) faculty = models.ForeignKey(Faculty) class Student(models.Model): name = models.CharField(max_length=30) faculty = models.ForeignKey(Faculty) program = models.ForeignKey(Program) Let I have Two Faculty: Science Management And I have 3 Programs in each: Science B. Computer B. Software B. Civil Management BBA BBS BBI And What I want is When A studen Is Filling up a Form They can Select Faculty and Programs. So When a user select Science as Faculty. Then How to make django Gives Only Programs From That selected Faculty? That means when users select Science in Faculty Field Then in program field Computer, Software and Civil should be Shown. Is it possible? then how? I think I make a clear question. (easy to understand what I mean) -
Call API from React
I am trying to get React to get the JSON from the Django Rest Framework API. The link is written like so http://127.0.0.1:8000/band/api/1/?format=json and the structure is as below: { id: 1, name: "Muse", date_added: "2017-04-17", image: "https://upload.wikimedia.org/wikipedia/commons/a/a3/Muse_melbourne28012010.jpg", bio: "Muse are an English rock band from Teignmouth, Devon, formed in 1994. The band consists of Matt Bellamy (lead vocals, guitar, piano, keyboards), Chris Wolstenholme (bass guitar, backing vocals, keyboards) and Dominic Howard (drums, percussion)." } My react is written like so: class ItemLister extends React.Component { constructor() { super(); this.state={items:[]}; } componentDidMount(){ fetch(`http://127.0.0.1:8000/band/api/1/?format=json`) .then(result=>result.json()) .then(items=>this.setState({items})) } render() { return( <ul> {this.state.items.length ? this.state.items.map(item=><li key={item.id}>{item.name}</li>) : <li>Loading...</li> } </ul> ) } } ReactDOM.render( <ItemLister />, document.getElementById('container') ); The HTML container div stays at loading..., the console shows no errors. I know its something to do with the JSON but cannot figure out what it is, any help appreciated! -
Django user registration and authentication to mutiple databases
I'm looking for a way to register and authenticate custom users accross mutiple databases using Django and postgreSQL. The application will be cross countries (still brainstorming). Regarding the different laws we need to store the users details inside their own country. For exemple, US users must have data stored in the US, Canadians users stored in Canada and Europeans users stored in Europe. The problem is that Django (1.11) doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. So I came up with 2 options at the moment but I can't see the perfect one. I'm asking if you would have a better solution. Option 1: using postgres_fdw (PostgreSQL foreign data wrapper) Manually creating localized (us, can, euro) databases to store users’ details https://www.postgresql.org/docs/9.6/static/postgres-fdw.html Then integrate Django with a legacy database Pros: Supports foreign database relationships Cons: Manual migration, manual integration, custom scripts. Option 2 : Skip Django referential integrity https://gist.github.com/gcko/de1383080e9f8fb7d208 Pros: Easier Django integration Cons: Risk of data corruption. I would avoid it!! Thanks Django: 1.11 PostgreSQL 9.6 Python 3 -
Universal Angular with Django Backend?
I'm working on a project with a Django backend (DRF API) and an Angular 2 front end. I'd like to use Universal Angular for my SEO implementation; it's being developed by the Angular team for use with Google's bots, so it looks like it'll be well maintained, well documented, and a stable option for long-term maintenance. It doesn't look like Universal Angular is set up to work with backends that aren't Node.js or ASP.NET, however. Does anyone know if there's a way around this? Or would it be better to just use a service like Prerender.io? -
How to annotate in Django w/DRF with Co
I have an note field, which has email ID, and multiple notes can exist with same email_id. But when I am coalesce I want to count the value only once. So lets say I have a note with email_id=1 and status of "sent", and another with email_id=1 and status="sent", I want the total_sent to be 1, not 2. queryset = EmailTemplate.objects.annotate( total_sent=Coalesce( Sum( Case( When( Q(note__email_status="Sent") | Q(note__email_status="Opened") | Q(note__email_status="Clicked"), then=1), default=0, output_field=IntegerField() ) ), Value(0), ), total_opened=Coalesce( Sum( Case( When( Q(note__email_status="Opened") | Q(note__email_status="Clicked"), then=1), default=0, output_field=IntegerField() ) ), Value(0), ), total_clicked=Coalesce( Sum( Case( When(note__email_status='Clicked', then=1), default=0, output_field=IntegerField() ) ), Value(0), ) ) -
How can one setup Flask/Django apps on a server running cpanel/whm on my VPS?
I purchase web hosting and have setup cpanel/whm on a VPS server. This helps certain clients easily manage their sites/domains. Currently, I have Centos 7 for the OS. Is it possible to use a reverse proxy with Apache or is that unique to NGINX? Can I setup sub-domains to host Python web apps like django or flask without causing problems with the existing domains/accounts on the server - which are managed by cpanel? How would I do that - the easiest route would be to keep apache with cpanel but manually create sites that correspond to the sub-domain such as django.example.com Would it be easier to use NGINX or is Apache able to do this? Lastly, one thing that has left me uncertain was how to manage Docker containerized apps in production. The same issues, I mentioned above for just publishing Python apps without considering Docker, are relevant in the scenario of using Docker. I wonder if it is possible to use Docker on a VPS server that I already am paying to have without having to also use Digital Ocean, AWS, Azure cloud, or similar PAAS solutions - do I have the correct acronym, for what I am discussing? …